From f62d2e96dcdb72a2e6ccf83873dec7cc12c50670 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 2 Aug 2024 01:55:45 +0000 Subject: [PATCH 1/4] feat: enable Dynamic Mute feat: New values `EXPLOITATION_FOR_PRIVILEGE_ESCALATION` corresponding to T1068 and `INDICATOR_REMOVAL_FILE_DELETION` corresponding to T1070.004 are added to enum `Technique` docs: T1068 is added for value `EXPLOITATION_FOR_PRIVILEGE_ESCALATION` and T1070.004 is added for value `INDICATOR_REMOVAL_FILE_DELETION` for enum `Technique PiperOrigin-RevId: 658541020 Source-Link: https://github.com/googleapis/googleapis/commit/c37b7f00ae5b9ce0d33ae28473d993cdaa5550cb Source-Link: https://github.com/googleapis/googleapis-gen/commit/2472a8c0cd0a2e9759af8e04134be08b6a3a5ed5 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLXNlY3VyaXR5Y2VudGVyLy5Pd2xCb3QueWFtbCIsImgiOiIyNDcyYThjMGNkMGEyZTk3NTlhZjhlMDQxMzRiZTA4YjZhM2E1ZWQ1In0= --- .../v1/.coveragerc | 13 + .../google-cloud-securitycenter/v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../google-cloud-securitycenter/v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../v1/docs/conf.py | 376 + .../v1/docs/index.rst | 7 + .../securitycenter_v1/security_center.rst | 10 + .../v1/docs/securitycenter_v1/services_.rst | 6 + .../v1/docs/securitycenter_v1/types_.rst | 6 + .../google/cloud/securitycenter/__init__.py | 343 + .../cloud/securitycenter/gapic_version.py | 16 + .../v1/google/cloud/securitycenter/py.typed | 2 + .../cloud/securitycenter_v1/__init__.py | 344 + .../securitycenter_v1/gapic_metadata.json | 973 + .../cloud/securitycenter_v1/gapic_version.py | 16 + .../google/cloud/securitycenter_v1/py.typed | 2 + .../securitycenter_v1/services/__init__.py | 15 + .../services/security_center/__init__.py | 22 + .../services/security_center/async_client.py | 7965 +++ .../services/security_center/client.py | 8455 +++ .../services/security_center/pagers.py | 2333 + .../security_center/transports/__init__.py | 38 + .../security_center/transports/base.py | 1251 + .../security_center/transports/grpc.py | 2103 + .../transports/grpc_asyncio.py | 2583 + .../security_center/transports/rest.py | 8529 +++ .../cloud/securitycenter_v1/types/__init__.py | 440 + .../cloud/securitycenter_v1/types/access.py | 193 + .../securitycenter_v1/types/application.py | 55 + .../cloud/securitycenter_v1/types/asset.py | 227 + .../types/attack_exposure.py | 113 + .../securitycenter_v1/types/attack_path.py | 223 + .../types/backup_disaster_recovery.py | 137 + .../types/bigquery_export.py | 135 + .../securitycenter_v1/types/cloud_armor.py | 217 + .../types/cloud_dlp_data_profile.py | 71 + .../types/cloud_dlp_inspection.py | 70 + .../securitycenter_v1/types/compliance.py | 61 + .../securitycenter_v1/types/connection.py | 97 + .../types/contact_details.py | 61 + .../securitycenter_v1/types/container.py | 80 + .../cloud/securitycenter_v1/types/database.py | 98 + ...ve_event_threat_detection_custom_module.py | 113 + ...security_health_analytics_custom_module.py | 104 + .../event_threat_detection_custom_module.py | 138 + ...tection_custom_module_validation_errors.py | 123 + .../securitycenter_v1/types/exfiltration.py | 96 + .../types/external_system.py | 180 + .../cloud/securitycenter_v1/types/file.py | 113 + .../cloud/securitycenter_v1/types/finding.py | 691 + .../cloud/securitycenter_v1/types/folder.py | 54 + .../types/group_membership.py | 65 + .../securitycenter_v1/types/iam_binding.py | 77 + .../securitycenter_v1/types/indicator.py | 186 + .../securitycenter_v1/types/kernel_rootkit.py | 107 + .../securitycenter_v1/types/kubernetes.py | 398 + .../cloud/securitycenter_v1/types/label.py | 54 + .../securitycenter_v1/types/load_balancer.py | 47 + .../securitycenter_v1/types/log_entry.py | 96 + .../securitycenter_v1/types/mitre_attack.py | 334 + .../securitycenter_v1/types/mute_config.py | 123 + .../cloud/securitycenter_v1/types/notebook.py | 72 + .../types/notification_config.py | 127 + .../types/notification_message.py | 70 + .../securitycenter_v1/types/org_policy.py | 47 + .../types/organization_settings.py | 123 + .../cloud/securitycenter_v1/types/process.py | 136 + .../cloud/securitycenter_v1/types/resource.py | 474 + .../types/resource_value_config.py | 189 + .../types/run_asset_discovery_response.py | 76 + ...security_health_analytics_custom_config.py | 173 + ...security_health_analytics_custom_module.py | 138 + .../securitycenter_v1/types/security_marks.py | 80 + .../types/security_posture.py | 128 + .../types/securitycenter_service.py | 3494 ++ .../securitycenter_v1/types/simulation.py | 73 + .../cloud/securitycenter_v1/types/source.py | 88 + .../types/toxic_combination.py | 60 + .../types/valued_resource.py | 126 + .../securitycenter_v1/types/vulnerability.py | 538 + .../google-cloud-securitycenter/v1/mypy.ini | 3 + .../google-cloud-securitycenter/v1/noxfile.py | 280 + ...tch_create_resource_value_configs_async.py | 58 + ...atch_create_resource_value_configs_sync.py | 58 + ...ecurity_center_bulk_mute_findings_async.py | 56 + ...security_center_bulk_mute_findings_sync.py | 56 + ...ty_center_create_big_query_export_async.py | 53 + ...ity_center_create_big_query_export_sync.py | 53 + ...nt_threat_detection_custom_module_async.py | 52 + ...ent_threat_detection_custom_module_sync.py | 52 + ...ed_security_center_create_finding_async.py | 53 + ...ted_security_center_create_finding_sync.py | 53 + ...ecurity_center_create_mute_config_async.py | 57 + ...security_center_create_mute_config_sync.py | 57 + ...center_create_notification_config_async.py | 53 + ..._center_create_notification_config_sync.py | 53 + ...ty_health_analytics_custom_module_async.py | 52 + ...ity_health_analytics_custom_module_sync.py | 52 + ...ted_security_center_create_source_async.py | 52 + ...ated_security_center_create_source_sync.py | 52 + ...ty_center_delete_big_query_export_async.py | 50 + ...ity_center_delete_big_query_export_sync.py | 50 + ...nt_threat_detection_custom_module_async.py | 50 + ...ent_threat_detection_custom_module_sync.py | 50 + ...ecurity_center_delete_mute_config_async.py | 50 + ...security_center_delete_mute_config_sync.py | 50 + ...center_delete_notification_config_async.py | 50 + ..._center_delete_notification_config_sync.py | 50 + ...nter_delete_resource_value_config_async.py | 50 + ...enter_delete_resource_value_config_sync.py | 50 + ...ty_health_analytics_custom_module_async.py | 50 + ...ity_health_analytics_custom_module_sync.py | 50 + ...urity_center_get_big_query_export_async.py | 52 + ...curity_center_get_big_query_export_sync.py | 52 + ...nt_threat_detection_custom_module_async.py | 52 + ...ent_threat_detection_custom_module_sync.py | 52 + ...ty_health_analytics_custom_module_async.py | 52 + ...ity_health_analytics_custom_module_sync.py | 52 + ...nt_threat_detection_custom_module_async.py | 52 + ...ent_threat_detection_custom_module_sync.py | 52 + ...ed_security_center_get_iam_policy_async.py | 53 + ...ted_security_center_get_iam_policy_sync.py | 53 + ...d_security_center_get_mute_config_async.py | 52 + ...ed_security_center_get_mute_config_sync.py | 52 + ...ty_center_get_notification_config_async.py | 52 + ...ity_center_get_notification_config_sync.py | 52 + ..._center_get_organization_settings_async.py | 52 + ...y_center_get_organization_settings_sync.py | 52 + ..._center_get_resource_value_config_async.py | 52 + ...y_center_get_resource_value_config_sync.py | 52 + ...ty_health_analytics_custom_module_async.py | 52 + ...ity_health_analytics_custom_module_sync.py | 52 + ...ed_security_center_get_simulation_async.py | 52 + ...ted_security_center_get_simulation_sync.py | 52 + ...erated_security_center_get_source_async.py | 52 + ...nerated_security_center_get_source_sync.py | 52 + ...curity_center_get_valued_resource_async.py | 52 + ...ecurity_center_get_valued_resource_sync.py | 52 + ...ated_security_center_group_assets_async.py | 54 + ...rated_security_center_group_assets_sync.py | 54 + ...ed_security_center_group_findings_async.py | 54 + ...ted_security_center_group_findings_sync.py | 54 + ...rated_security_center_list_assets_async.py | 53 + ...erated_security_center_list_assets_sync.py | 53 + ...security_center_list_attack_paths_async.py | 53 + ..._security_center_list_attack_paths_sync.py | 53 + ...ity_center_list_big_query_exports_async.py | 53 + ...rity_center_list_big_query_exports_sync.py | 53 + ...t_threat_detection_custom_modules_async.py | 53 + ...nt_threat_detection_custom_modules_sync.py | 53 + ...y_health_analytics_custom_modules_async.py | 53 + ...ty_health_analytics_custom_modules_sync.py | 53 + ...t_threat_detection_custom_modules_async.py | 53 + ...nt_threat_detection_custom_modules_sync.py | 53 + ...y_health_analytics_custom_modules_async.py | 53 + ...ty_health_analytics_custom_modules_sync.py | 53 + ...t_threat_detection_custom_modules_async.py | 53 + ...nt_threat_detection_custom_modules_sync.py | 53 + ...ted_security_center_list_findings_async.py | 53 + ...ated_security_center_list_findings_sync.py | 53 + ...security_center_list_mute_configs_async.py | 53 + ..._security_center_list_mute_configs_sync.py | 53 + ..._center_list_notification_configs_async.py | 53 + ...y_center_list_notification_configs_sync.py | 53 + ...enter_list_resource_value_configs_async.py | 53 + ...center_list_resource_value_configs_sync.py | 53 + ...y_health_analytics_custom_modules_async.py | 53 + ...ty_health_analytics_custom_modules_sync.py | 53 + ...ated_security_center_list_sources_async.py | 53 + ...rated_security_center_list_sources_sync.py | 53 + ...rity_center_list_valued_resources_async.py | 53 + ...urity_center_list_valued_resources_sync.py | 53 + ...curity_center_run_asset_discovery_async.py | 56 + ...ecurity_center_run_asset_discovery_sync.py | 56 + ...security_center_set_finding_state_async.py | 53 + ..._security_center_set_finding_state_sync.py | 53 + ...ed_security_center_set_iam_policy_async.py | 53 + ...ted_security_center_set_iam_policy_sync.py | 53 + ...enerated_security_center_set_mute_async.py | 53 + ...generated_security_center_set_mute_sync.py | 53 + ...ty_health_analytics_custom_module_async.py | 56 + ...ity_health_analytics_custom_module_sync.py | 56 + ...urity_center_test_iam_permissions_async.py | 54 + ...curity_center_test_iam_permissions_sync.py | 54 + ...ty_center_update_big_query_export_async.py | 51 + ...ity_center_update_big_query_export_sync.py | 51 + ...nt_threat_detection_custom_module_async.py | 51 + ...ent_threat_detection_custom_module_sync.py | 51 + ...ity_center_update_external_system_async.py | 51 + ...rity_center_update_external_system_sync.py | 51 + ...ed_security_center_update_finding_async.py | 51 + ...ted_security_center_update_finding_sync.py | 51 + ...ecurity_center_update_mute_config_async.py | 55 + ...security_center_update_mute_config_sync.py | 55 + ...center_update_notification_config_async.py | 51 + ..._center_update_notification_config_sync.py | 51 + ...nter_update_organization_settings_async.py | 51 + ...enter_update_organization_settings_sync.py | 51 + ...nter_update_resource_value_config_async.py | 56 + ...enter_update_resource_value_config_sync.py | 56 + ...ty_health_analytics_custom_module_async.py | 51 + ...ity_health_analytics_custom_module_sync.py | 51 + ...rity_center_update_security_marks_async.py | 51 + ...urity_center_update_security_marks_sync.py | 51 + ...ted_security_center_update_source_async.py | 51 + ...ated_security_center_update_source_sync.py | 51 + ...nt_threat_detection_custom_module_async.py | 54 + ...ent_threat_detection_custom_module_sync.py | 54 + ...tadata_google.cloud.securitycenter.v1.json | 10298 ++++ .../fixup_securitycenter_v1_keywords.py | 238 + .../google-cloud-securitycenter/v1/setup.py | 94 + .../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/securitycenter_v1/__init__.py | 16 + .../securitycenter_v1/test_security_center.py | 48250 ++++++++++++++++ .../v1beta1/.coveragerc | 13 + .../v1beta1/.flake8 | 33 + .../v1beta1/MANIFEST.in | 2 + .../v1beta1/README.rst | 49 + .../v1beta1/docs/_static/custom.css | 3 + .../v1beta1/docs/conf.py | 376 + .../v1beta1/docs/index.rst | 7 + .../security_center.rst | 10 + .../docs/securitycenter_v1beta1/services_.rst | 6 + .../docs/securitycenter_v1beta1/types_.rst | 6 + .../google/cloud/securitycenter/__init__.py | 81 + .../cloud/securitycenter/gapic_version.py | 16 + .../google/cloud/securitycenter/py.typed | 2 + .../cloud/securitycenter_v1beta1/__init__.py | 82 + .../gapic_metadata.json | 298 + .../securitycenter_v1beta1/gapic_version.py | 16 + .../cloud/securitycenter_v1beta1/py.typed | 2 + .../services/__init__.py | 15 + .../services/security_center/__init__.py | 22 + .../services/security_center/async_client.py | 2364 + .../services/security_center/client.py | 2755 + .../services/security_center/pagers.py | 704 + .../security_center/transports/__init__.py | 38 + .../security_center/transports/base.py | 498 + .../security_center/transports/grpc.py | 760 + .../transports/grpc_asyncio.py | 945 + .../security_center/transports/rest.py | 2542 + .../securitycenter_v1beta1/types/__init__.py | 86 + .../securitycenter_v1beta1/types/asset.py | 155 + .../securitycenter_v1beta1/types/finding.py | 165 + .../types/organization_settings.py | 115 + .../types/run_asset_discovery_response.py | 76 + .../types/security_marks.py | 68 + .../types/securitycenter_service.py | 1053 + .../securitycenter_v1beta1/types/source.py | 77 + .../v1beta1/mypy.ini | 3 + .../v1beta1/noxfile.py | 280 + ...ed_security_center_create_finding_async.py | 53 + ...ted_security_center_create_finding_sync.py | 53 + ...ted_security_center_create_source_async.py | 52 + ...ated_security_center_create_source_sync.py | 52 + ...ed_security_center_get_iam_policy_async.py | 53 + ...ted_security_center_get_iam_policy_sync.py | 53 + ..._center_get_organization_settings_async.py | 52 + ...y_center_get_organization_settings_sync.py | 52 + ...erated_security_center_get_source_async.py | 52 + ...nerated_security_center_get_source_sync.py | 52 + ...ated_security_center_group_assets_async.py | 54 + ...rated_security_center_group_assets_sync.py | 54 + ...ed_security_center_group_findings_async.py | 54 + ...ted_security_center_group_findings_sync.py | 54 + ...rated_security_center_list_assets_async.py | 53 + ...erated_security_center_list_assets_sync.py | 53 + ...ted_security_center_list_findings_async.py | 53 + ...ated_security_center_list_findings_sync.py | 53 + ...ated_security_center_list_sources_async.py | 53 + ...rated_security_center_list_sources_sync.py | 53 + ...curity_center_run_asset_discovery_async.py | 56 + ...ecurity_center_run_asset_discovery_sync.py | 56 + ...security_center_set_finding_state_async.py | 53 + ..._security_center_set_finding_state_sync.py | 53 + ...ed_security_center_set_iam_policy_async.py | 53 + ...ted_security_center_set_iam_policy_sync.py | 53 + ...urity_center_test_iam_permissions_async.py | 54 + ...curity_center_test_iam_permissions_sync.py | 54 + ...ed_security_center_update_finding_async.py | 51 + ...ted_security_center_update_finding_sync.py | 51 + ...nter_update_organization_settings_async.py | 51 + ...enter_update_organization_settings_sync.py | 51 + ...rity_center_update_security_marks_async.py | 51 + ...urity_center_update_security_marks_sync.py | 51 + ...ted_security_center_update_source_async.py | 51 + ...ated_security_center_update_source_sync.py | 51 + ...a_google.cloud.securitycenter.v1beta1.json | 2945 + .../fixup_securitycenter_v1beta1_keywords.py | 193 + .../v1beta1/setup.py | 94 + .../v1beta1/testing/constraints-3.10.txt | 7 + .../v1beta1/testing/constraints-3.11.txt | 7 + .../v1beta1/testing/constraints-3.12.txt | 7 + .../v1beta1/testing/constraints-3.7.txt | 11 + .../v1beta1/testing/constraints-3.8.txt | 7 + .../v1beta1/testing/constraints-3.9.txt | 7 + .../v1beta1/tests/__init__.py | 16 + .../v1beta1/tests/unit/__init__.py | 16 + .../v1beta1/tests/unit/gapic/__init__.py | 16 + .../gapic/securitycenter_v1beta1/__init__.py | 16 + .../test_security_center.py | 14372 +++++ .../v1p1beta1/.coveragerc | 13 + .../v1p1beta1/.flake8 | 33 + .../v1p1beta1/MANIFEST.in | 2 + .../v1p1beta1/README.rst | 49 + .../v1p1beta1/docs/_static/custom.css | 3 + .../v1p1beta1/docs/conf.py | 376 + .../v1p1beta1/docs/index.rst | 7 + .../security_center.rst | 10 + .../securitycenter_v1p1beta1/services_.rst | 6 + .../docs/securitycenter_v1p1beta1/types_.rst | 6 + .../google/cloud/securitycenter/__init__.py | 101 + .../cloud/securitycenter/gapic_version.py | 16 + .../google/cloud/securitycenter/py.typed | 2 + .../securitycenter_v1p1beta1/__init__.py | 102 + .../gapic_metadata.json | 373 + .../securitycenter_v1p1beta1/gapic_version.py | 16 + .../cloud/securitycenter_v1p1beta1/py.typed | 2 + .../services/__init__.py | 15 + .../services/security_center/__init__.py | 22 + .../services/security_center/async_client.py | 3039 + .../services/security_center/client.py | 3441 ++ .../services/security_center/pagers.py | 839 + .../security_center/transports/__init__.py | 38 + .../security_center/transports/base.py | 591 + .../security_center/transports/grpc.py | 895 + .../transports/grpc_asyncio.py | 1125 + .../security_center/transports/rest.py | 3197 + .../types/__init__.py | 114 + .../securitycenter_v1p1beta1/types/asset.py | 227 + .../securitycenter_v1p1beta1/types/finding.py | 209 + .../securitycenter_v1p1beta1/types/folder.py | 54 + .../types/notification_config.py | 143 + .../types/notification_message.py | 69 + .../types/organization_settings.py | 123 + .../types/resource.py | 85 + .../types/run_asset_discovery_response.py | 76 + .../types/security_marks.py | 80 + .../types/securitycenter_service.py | 1641 + .../securitycenter_v1p1beta1/types/source.py | 88 + .../v1p1beta1/mypy.ini | 3 + .../v1p1beta1/noxfile.py | 280 + ...ed_security_center_create_finding_async.py | 53 + ...ted_security_center_create_finding_sync.py | 53 + ...center_create_notification_config_async.py | 53 + ..._center_create_notification_config_sync.py | 53 + ...ted_security_center_create_source_async.py | 52 + ...ated_security_center_create_source_sync.py | 52 + ...center_delete_notification_config_async.py | 50 + ..._center_delete_notification_config_sync.py | 50 + ...ed_security_center_get_iam_policy_async.py | 53 + ...ted_security_center_get_iam_policy_sync.py | 53 + ...ty_center_get_notification_config_async.py | 52 + ...ity_center_get_notification_config_sync.py | 52 + ..._center_get_organization_settings_async.py | 52 + ...y_center_get_organization_settings_sync.py | 52 + ...erated_security_center_get_source_async.py | 52 + ...nerated_security_center_get_source_sync.py | 52 + ...ated_security_center_group_assets_async.py | 54 + ...rated_security_center_group_assets_sync.py | 54 + ...ed_security_center_group_findings_async.py | 54 + ...ted_security_center_group_findings_sync.py | 54 + ...rated_security_center_list_assets_async.py | 53 + ...erated_security_center_list_assets_sync.py | 53 + ...ted_security_center_list_findings_async.py | 53 + ...ated_security_center_list_findings_sync.py | 53 + ..._center_list_notification_configs_async.py | 53 + ...y_center_list_notification_configs_sync.py | 53 + ...ated_security_center_list_sources_async.py | 53 + ...rated_security_center_list_sources_sync.py | 53 + ...curity_center_run_asset_discovery_async.py | 56 + ...ecurity_center_run_asset_discovery_sync.py | 56 + ...security_center_set_finding_state_async.py | 53 + ..._security_center_set_finding_state_sync.py | 53 + ...ed_security_center_set_iam_policy_async.py | 53 + ...ted_security_center_set_iam_policy_sync.py | 53 + ...urity_center_test_iam_permissions_async.py | 54 + ...curity_center_test_iam_permissions_sync.py | 54 + ...ed_security_center_update_finding_async.py | 51 + ...ted_security_center_update_finding_sync.py | 51 + ...center_update_notification_config_async.py | 51 + ..._center_update_notification_config_sync.py | 51 + ...nter_update_organization_settings_async.py | 51 + ...enter_update_organization_settings_sync.py | 51 + ...rity_center_update_security_marks_async.py | 51 + ...urity_center_update_security_marks_sync.py | 51 + ...ted_security_center_update_source_async.py | 51 + ...ated_security_center_update_source_sync.py | 51 + ...google.cloud.securitycenter.v1p1beta1.json | 3808 ++ ...fixup_securitycenter_v1p1beta1_keywords.py | 198 + .../v1p1beta1/setup.py | 94 + .../v1p1beta1/testing/constraints-3.10.txt | 7 + .../v1p1beta1/testing/constraints-3.11.txt | 7 + .../v1p1beta1/testing/constraints-3.12.txt | 7 + .../v1p1beta1/testing/constraints-3.7.txt | 11 + .../v1p1beta1/testing/constraints-3.8.txt | 7 + .../v1p1beta1/testing/constraints-3.9.txt | 7 + .../v1p1beta1/tests/__init__.py | 16 + .../v1p1beta1/tests/unit/__init__.py | 16 + .../v1p1beta1/tests/unit/gapic/__init__.py | 16 + .../securitycenter_v1p1beta1/__init__.py | 16 + .../test_security_center.py | 18405 ++++++ .../v2/.coveragerc | 13 + .../google-cloud-securitycenter/v2/.flake8 | 33 + .../v2/MANIFEST.in | 2 + .../google-cloud-securitycenter/v2/README.rst | 49 + .../v2/docs/_static/custom.css | 3 + .../v2/docs/conf.py | 376 + .../v2/docs/index.rst | 7 + .../securitycenter_v2/security_center.rst | 10 + .../v2/docs/securitycenter_v2/services_.rst | 6 + .../v2/docs/securitycenter_v2/types_.rst | 6 + .../google/cloud/securitycenter/__init__.py | 257 + .../cloud/securitycenter/gapic_version.py | 16 + .../v2/google/cloud/securitycenter/py.typed | 2 + .../cloud/securitycenter_v2/__init__.py | 258 + .../securitycenter_v2/gapic_metadata.json | 628 + .../cloud/securitycenter_v2/gapic_version.py | 16 + .../google/cloud/securitycenter_v2/py.typed | 2 + .../securitycenter_v2/services/__init__.py | 15 + .../services/security_center/__init__.py | 22 + .../services/security_center/async_client.py | 5422 ++ .../services/security_center/client.py | 5948 ++ .../services/security_center/pagers.py | 1249 + .../security_center/transports/__init__.py | 38 + .../security_center/transports/base.py | 761 + .../security_center/transports/grpc.py | 1452 + .../transports/grpc_asyncio.py | 1657 + .../security_center/transports/rest.py | 5820 ++ .../cloud/securitycenter_v2/types/__init__.py | 336 + .../cloud/securitycenter_v2/types/access.py | 193 + .../securitycenter_v2/types/application.py | 55 + .../types/attack_exposure.py | 113 + .../securitycenter_v2/types/attack_path.py | 223 + .../types/backup_disaster_recovery.py | 137 + .../types/bigquery_export.py | 141 + .../securitycenter_v2/types/cloud_armor.py | 217 + .../types/cloud_dlp_data_profile.py | 71 + .../types/cloud_dlp_inspection.py | 70 + .../securitycenter_v2/types/compliance.py | 61 + .../securitycenter_v2/types/connection.py | 97 + .../types/contact_details.py | 61 + .../securitycenter_v2/types/container.py | 80 + .../cloud/securitycenter_v2/types/database.py | 98 + .../securitycenter_v2/types/exfiltration.py | 96 + .../types/external_system.py | 192 + .../cloud/securitycenter_v2/types/file.py | 113 + .../cloud/securitycenter_v2/types/finding.py | 808 + .../cloud/securitycenter_v2/types/folder.py | 54 + .../types/group_membership.py | 65 + .../securitycenter_v2/types/iam_binding.py | 77 + .../securitycenter_v2/types/indicator.py | 186 + .../securitycenter_v2/types/kernel_rootkit.py | 107 + .../securitycenter_v2/types/kubernetes.py | 398 + .../cloud/securitycenter_v2/types/label.py | 54 + .../securitycenter_v2/types/load_balancer.py | 47 + .../securitycenter_v2/types/log_entry.py | 95 + .../securitycenter_v2/types/mitre_attack.py | 340 + .../securitycenter_v2/types/mute_config.py | 166 + .../cloud/securitycenter_v2/types/notebook.py | 72 + .../types/notification_config.py | 129 + .../types/notification_message.py | 70 + .../securitycenter_v2/types/org_policy.py | 47 + .../cloud/securitycenter_v2/types/process.py | 136 + .../cloud/securitycenter_v2/types/resource.py | 493 + .../types/resource_value_config.py | 190 + .../securitycenter_v2/types/security_marks.py | 101 + .../types/security_posture.py | 128 + .../types/securitycenter_service.py | 1932 + .../securitycenter_v2/types/simulation.py | 73 + .../cloud/securitycenter_v2/types/source.py | 88 + .../types/toxic_combination.py | 60 + .../types/valued_resource.py | 126 + .../securitycenter_v2/types/vulnerability.py | 546 + .../google-cloud-securitycenter/v2/mypy.ini | 3 + .../google-cloud-securitycenter/v2/noxfile.py | 280 + ...tch_create_resource_value_configs_async.py | 56 + ...atch_create_resource_value_configs_sync.py | 56 + ...ecurity_center_bulk_mute_findings_async.py | 56 + ...security_center_bulk_mute_findings_sync.py | 56 + ...ty_center_create_big_query_export_async.py | 53 + ...ity_center_create_big_query_export_sync.py | 53 + ...ed_security_center_create_finding_async.py | 53 + ...ted_security_center_create_finding_sync.py | 53 + ...ecurity_center_create_mute_config_async.py | 58 + ...security_center_create_mute_config_sync.py | 58 + ...center_create_notification_config_async.py | 53 + ..._center_create_notification_config_sync.py | 53 + ...ted_security_center_create_source_async.py | 52 + ...ated_security_center_create_source_sync.py | 52 + ...ty_center_delete_big_query_export_async.py | 50 + ...ity_center_delete_big_query_export_sync.py | 50 + ...ecurity_center_delete_mute_config_async.py | 50 + ...security_center_delete_mute_config_sync.py | 50 + ...center_delete_notification_config_async.py | 50 + ..._center_delete_notification_config_sync.py | 50 + ...nter_delete_resource_value_config_async.py | 50 + ...enter_delete_resource_value_config_sync.py | 50 + ...urity_center_get_big_query_export_async.py | 52 + ...curity_center_get_big_query_export_sync.py | 52 + ...ed_security_center_get_iam_policy_async.py | 53 + ...ted_security_center_get_iam_policy_sync.py | 53 + ...d_security_center_get_mute_config_async.py | 52 + ...ed_security_center_get_mute_config_sync.py | 52 + ...ty_center_get_notification_config_async.py | 52 + ...ity_center_get_notification_config_sync.py | 52 + ..._center_get_resource_value_config_async.py | 52 + ...y_center_get_resource_value_config_sync.py | 52 + ...ed_security_center_get_simulation_async.py | 52 + ...ted_security_center_get_simulation_sync.py | 52 + ...erated_security_center_get_source_async.py | 52 + ...nerated_security_center_get_source_sync.py | 52 + ...curity_center_get_valued_resource_async.py | 52 + ...ecurity_center_get_valued_resource_sync.py | 52 + ...ed_security_center_group_findings_async.py | 54 + ...ted_security_center_group_findings_sync.py | 54 + ...security_center_list_attack_paths_async.py | 53 + ..._security_center_list_attack_paths_sync.py | 53 + ...ity_center_list_big_query_exports_async.py | 53 + ...rity_center_list_big_query_exports_sync.py | 53 + ...ted_security_center_list_findings_async.py | 53 + ...ated_security_center_list_findings_sync.py | 53 + ...security_center_list_mute_configs_async.py | 53 + ..._security_center_list_mute_configs_sync.py | 53 + ..._center_list_notification_configs_async.py | 53 + ...y_center_list_notification_configs_sync.py | 53 + ...enter_list_resource_value_configs_async.py | 53 + ...center_list_resource_value_configs_sync.py | 53 + ...ated_security_center_list_sources_async.py | 53 + ...rated_security_center_list_sources_sync.py | 53 + ...rity_center_list_valued_resources_async.py | 53 + ...urity_center_list_valued_resources_sync.py | 53 + ...security_center_set_finding_state_async.py | 53 + ..._security_center_set_finding_state_sync.py | 53 + ...ed_security_center_set_iam_policy_async.py | 53 + ...ted_security_center_set_iam_policy_sync.py | 53 + ...enerated_security_center_set_mute_async.py | 53 + ...generated_security_center_set_mute_sync.py | 53 + ...urity_center_test_iam_permissions_async.py | 54 + ...curity_center_test_iam_permissions_sync.py | 54 + ...ty_center_update_big_query_export_async.py | 51 + ...ity_center_update_big_query_export_sync.py | 51 + ...ity_center_update_external_system_async.py | 51 + ...rity_center_update_external_system_sync.py | 51 + ...ed_security_center_update_finding_async.py | 51 + ...ted_security_center_update_finding_sync.py | 51 + ...ecurity_center_update_mute_config_async.py | 56 + ...security_center_update_mute_config_sync.py | 56 + ...center_update_notification_config_async.py | 51 + ..._center_update_notification_config_sync.py | 51 + ...nter_update_resource_value_config_async.py | 51 + ...enter_update_resource_value_config_sync.py | 51 + ...rity_center_update_security_marks_async.py | 51 + ...urity_center_update_security_marks_sync.py | 51 + ...ted_security_center_update_source_async.py | 51 + ...ated_security_center_update_source_sync.py | 51 + ...tadata_google.cloud.securitycenter.v2.json | 6607 +++ .../fixup_securitycenter_v2_keywords.py | 215 + .../google-cloud-securitycenter/v2/setup.py | 94 + .../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 + .../v2/tests/__init__.py | 16 + .../v2/tests/unit/__init__.py | 16 + .../v2/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/securitycenter_v2/__init__.py | 16 + .../securitycenter_v2/test_security_center.py | 31716 ++++++++++ 579 files changed, 265103 insertions(+) create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/.flake8 create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/setup.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.flake8 create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/setup.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/.coveragerc create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/.flake8 create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/README.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/noxfile.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/setup.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc new file mode 100644 index 000000000000..45cb273f8f7c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/securitycenter/__init__.py + google/cloud/securitycenter/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-securitycenter/v1/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v1/MANIFEST.in new file mode 100644 index 000000000000..a18e3d0b6821 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/securitycenter *.py +recursive-include google/cloud/securitycenter_v1 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/README.rst b/owl-bot-staging/google-cloud-securitycenter/v1/README.rst new file mode 100644 index 000000000000..f8c63f4cb48a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v1/docs/conf.py new file mode 100644 index 000000000000..8e92d2319721 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter 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-securitycenter" +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-securitycenter-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-securitycenter.tex", + u"google-cloud-securitycenter 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-securitycenter", + u"Google Cloud Securitycenter 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-securitycenter", + u"google-cloud-securitycenter Documentation", + author, + "google-cloud-securitycenter", + "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v1/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/index.rst new file mode 100644 index 000000000000..47fc2db7cc98 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + securitycenter_v1/services + securitycenter_v1/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst new file mode 100644 index 000000000000..bc6175c8b5cc --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst @@ -0,0 +1,10 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v1.services.security_center + :members: + :inherited-members: + +.. automodule:: google.cloud.securitycenter_v1.services.security_center.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst new file mode 100644 index 000000000000..295acede4385 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v1 API +=============================================== +.. toctree:: + :maxdepth: 2 + + security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst new file mode 100644 index 000000000000..f7497757d041 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Securitycenter v1 API +============================================ + +.. automodule:: google.cloud.securitycenter_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.py new file mode 100644 index 000000000000..7c15b78219eb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.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. +# +from google.cloud.securitycenter import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.securitycenter_v1.services.security_center.client import SecurityCenterClient +from google.cloud.securitycenter_v1.services.security_center.async_client import SecurityCenterAsyncClient + +from google.cloud.securitycenter_v1.types.access import Access +from google.cloud.securitycenter_v1.types.access import Geolocation +from google.cloud.securitycenter_v1.types.access import ServiceAccountDelegationInfo +from google.cloud.securitycenter_v1.types.application import Application +from google.cloud.securitycenter_v1.types.asset import Asset +from google.cloud.securitycenter_v1.types.attack_exposure import AttackExposure +from google.cloud.securitycenter_v1.types.attack_path import AttackPath +from google.cloud.securitycenter_v1.types.backup_disaster_recovery import BackupDisasterRecovery +from google.cloud.securitycenter_v1.types.bigquery_export import BigQueryExport +from google.cloud.securitycenter_v1.types.cloud_armor import AdaptiveProtection +from google.cloud.securitycenter_v1.types.cloud_armor import Attack +from google.cloud.securitycenter_v1.types.cloud_armor import CloudArmor +from google.cloud.securitycenter_v1.types.cloud_armor import Requests +from google.cloud.securitycenter_v1.types.cloud_armor import SecurityPolicy +from google.cloud.securitycenter_v1.types.cloud_dlp_data_profile import CloudDlpDataProfile +from google.cloud.securitycenter_v1.types.cloud_dlp_inspection import CloudDlpInspection +from google.cloud.securitycenter_v1.types.compliance import Compliance +from google.cloud.securitycenter_v1.types.connection import Connection +from google.cloud.securitycenter_v1.types.contact_details import Contact +from google.cloud.securitycenter_v1.types.contact_details import ContactDetails +from google.cloud.securitycenter_v1.types.container import Container +from google.cloud.securitycenter_v1.types.database import Database +from google.cloud.securitycenter_v1.types.effective_event_threat_detection_custom_module import EffectiveEventThreatDetectionCustomModule +from google.cloud.securitycenter_v1.types.effective_security_health_analytics_custom_module import EffectiveSecurityHealthAnalyticsCustomModule +from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module import EventThreatDetectionCustomModule +from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationError +from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationErrors +from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module_validation_errors import Position +from google.cloud.securitycenter_v1.types.exfiltration import ExfilResource +from google.cloud.securitycenter_v1.types.exfiltration import Exfiltration +from google.cloud.securitycenter_v1.types.external_system import ExternalSystem +from google.cloud.securitycenter_v1.types.file import File +from google.cloud.securitycenter_v1.types.finding import Finding +from google.cloud.securitycenter_v1.types.folder import Folder +from google.cloud.securitycenter_v1.types.group_membership import GroupMembership +from google.cloud.securitycenter_v1.types.iam_binding import IamBinding +from google.cloud.securitycenter_v1.types.indicator import Indicator +from google.cloud.securitycenter_v1.types.kernel_rootkit import KernelRootkit +from google.cloud.securitycenter_v1.types.kubernetes import Kubernetes +from google.cloud.securitycenter_v1.types.label import Label +from google.cloud.securitycenter_v1.types.load_balancer import LoadBalancer +from google.cloud.securitycenter_v1.types.log_entry import CloudLoggingEntry +from google.cloud.securitycenter_v1.types.log_entry import LogEntry +from google.cloud.securitycenter_v1.types.mitre_attack import MitreAttack +from google.cloud.securitycenter_v1.types.mute_config import MuteConfig +from google.cloud.securitycenter_v1.types.notebook import Notebook +from google.cloud.securitycenter_v1.types.notification_config import NotificationConfig +from google.cloud.securitycenter_v1.types.notification_message import NotificationMessage +from google.cloud.securitycenter_v1.types.org_policy import OrgPolicy +from google.cloud.securitycenter_v1.types.organization_settings import OrganizationSettings +from google.cloud.securitycenter_v1.types.process import EnvironmentVariable +from google.cloud.securitycenter_v1.types.process import Process +from google.cloud.securitycenter_v1.types.resource import AwsMetadata +from google.cloud.securitycenter_v1.types.resource import AzureMetadata +from google.cloud.securitycenter_v1.types.resource import Resource +from google.cloud.securitycenter_v1.types.resource import ResourcePath +from google.cloud.securitycenter_v1.types.resource import CloudProvider +from google.cloud.securitycenter_v1.types.resource_value_config import ResourceValueConfig +from google.cloud.securitycenter_v1.types.resource_value_config import ResourceValue +from google.cloud.securitycenter_v1.types.run_asset_discovery_response import RunAssetDiscoveryResponse +from google.cloud.securitycenter_v1.types.security_health_analytics_custom_config import CustomConfig +from google.cloud.securitycenter_v1.types.security_health_analytics_custom_module import SecurityHealthAnalyticsCustomModule +from google.cloud.securitycenter_v1.types.security_marks import SecurityMarks +from google.cloud.securitycenter_v1.types.security_posture import SecurityPosture +from google.cloud.securitycenter_v1.types.securitycenter_service import BatchCreateResourceValueConfigsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import BatchCreateResourceValueConfigsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import BulkMuteFindingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import BulkMuteFindingsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateBigQueryExportRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateEventThreatDetectionCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateFindingRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateMuteConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateNotificationConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateResourceValueConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateSecurityHealthAnalyticsCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateSourceRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteBigQueryExportRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteEventThreatDetectionCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteMuteConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteNotificationConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteResourceValueConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteSecurityHealthAnalyticsCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetBigQueryExportRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetEffectiveEventThreatDetectionCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetEffectiveSecurityHealthAnalyticsCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetEventThreatDetectionCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetMuteConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetNotificationConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetOrganizationSettingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetResourceValueConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetSecurityHealthAnalyticsCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetSimulationRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetSourceRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetValuedResourceRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupAssetsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupAssetsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupFindingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupFindingsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupResult +from google.cloud.securitycenter_v1.types.securitycenter_service import ListAssetsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListAssetsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListAttackPathsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListAttackPathsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListBigQueryExportsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListBigQueryExportsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListEventThreatDetectionCustomModulesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListEventThreatDetectionCustomModulesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListFindingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListFindingsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListMuteConfigsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListMuteConfigsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListNotificationConfigsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListNotificationConfigsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListResourceValueConfigsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListResourceValueConfigsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListSourcesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListSourcesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListValuedResourcesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListValuedResourcesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import RunAssetDiscoveryRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import SetFindingStateRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import SetMuteRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateBigQueryExportRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateEventThreatDetectionCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateExternalSystemRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateFindingRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateMuteConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateNotificationConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateOrganizationSettingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateResourceValueConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSecurityHealthAnalyticsCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSecurityMarksRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSourceRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ValidateEventThreatDetectionCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ValidateEventThreatDetectionCustomModuleResponse +from google.cloud.securitycenter_v1.types.simulation import Simulation +from google.cloud.securitycenter_v1.types.source import Source +from google.cloud.securitycenter_v1.types.toxic_combination import ToxicCombination +from google.cloud.securitycenter_v1.types.valued_resource import ResourceValueConfigMetadata +from google.cloud.securitycenter_v1.types.valued_resource import ValuedResource +from google.cloud.securitycenter_v1.types.vulnerability import Cve +from google.cloud.securitycenter_v1.types.vulnerability import Cvssv3 +from google.cloud.securitycenter_v1.types.vulnerability import Package +from google.cloud.securitycenter_v1.types.vulnerability import Reference +from google.cloud.securitycenter_v1.types.vulnerability import SecurityBulletin +from google.cloud.securitycenter_v1.types.vulnerability import Vulnerability + +__all__ = ('SecurityCenterClient', + 'SecurityCenterAsyncClient', + 'Access', + 'Geolocation', + 'ServiceAccountDelegationInfo', + 'Application', + 'Asset', + 'AttackExposure', + 'AttackPath', + 'BackupDisasterRecovery', + 'BigQueryExport', + 'AdaptiveProtection', + 'Attack', + 'CloudArmor', + 'Requests', + 'SecurityPolicy', + 'CloudDlpDataProfile', + 'CloudDlpInspection', + 'Compliance', + 'Connection', + 'Contact', + 'ContactDetails', + 'Container', + 'Database', + 'EffectiveEventThreatDetectionCustomModule', + 'EffectiveSecurityHealthAnalyticsCustomModule', + 'EventThreatDetectionCustomModule', + 'CustomModuleValidationError', + 'CustomModuleValidationErrors', + 'Position', + 'ExfilResource', + 'Exfiltration', + 'ExternalSystem', + 'File', + 'Finding', + 'Folder', + 'GroupMembership', + 'IamBinding', + 'Indicator', + 'KernelRootkit', + 'Kubernetes', + 'Label', + 'LoadBalancer', + 'CloudLoggingEntry', + 'LogEntry', + 'MitreAttack', + 'MuteConfig', + 'Notebook', + 'NotificationConfig', + 'NotificationMessage', + 'OrgPolicy', + 'OrganizationSettings', + 'EnvironmentVariable', + 'Process', + 'AwsMetadata', + 'AzureMetadata', + 'Resource', + 'ResourcePath', + 'CloudProvider', + 'ResourceValueConfig', + 'ResourceValue', + 'RunAssetDiscoveryResponse', + 'CustomConfig', + 'SecurityHealthAnalyticsCustomModule', + 'SecurityMarks', + 'SecurityPosture', + 'BatchCreateResourceValueConfigsRequest', + 'BatchCreateResourceValueConfigsResponse', + 'BulkMuteFindingsRequest', + 'BulkMuteFindingsResponse', + 'CreateBigQueryExportRequest', + 'CreateEventThreatDetectionCustomModuleRequest', + 'CreateFindingRequest', + 'CreateMuteConfigRequest', + 'CreateNotificationConfigRequest', + 'CreateResourceValueConfigRequest', + 'CreateSecurityHealthAnalyticsCustomModuleRequest', + 'CreateSourceRequest', + 'DeleteBigQueryExportRequest', + 'DeleteEventThreatDetectionCustomModuleRequest', + 'DeleteMuteConfigRequest', + 'DeleteNotificationConfigRequest', + 'DeleteResourceValueConfigRequest', + 'DeleteSecurityHealthAnalyticsCustomModuleRequest', + 'GetBigQueryExportRequest', + 'GetEffectiveEventThreatDetectionCustomModuleRequest', + 'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', + 'GetEventThreatDetectionCustomModuleRequest', + 'GetMuteConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetResourceValueConfigRequest', + 'GetSecurityHealthAnalyticsCustomModuleRequest', + 'GetSimulationRequest', + 'GetSourceRequest', + 'GetValuedResourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListAttackPathsRequest', + 'ListAttackPathsResponse', + 'ListBigQueryExportsRequest', + 'ListBigQueryExportsResponse', + 'ListDescendantEventThreatDetectionCustomModulesRequest', + 'ListDescendantEventThreatDetectionCustomModulesResponse', + 'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', + 'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', + 'ListEffectiveEventThreatDetectionCustomModulesRequest', + 'ListEffectiveEventThreatDetectionCustomModulesResponse', + 'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', + 'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', + 'ListEventThreatDetectionCustomModulesRequest', + 'ListEventThreatDetectionCustomModulesResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListMuteConfigsRequest', + 'ListMuteConfigsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListResourceValueConfigsRequest', + 'ListResourceValueConfigsResponse', + 'ListSecurityHealthAnalyticsCustomModulesRequest', + 'ListSecurityHealthAnalyticsCustomModulesResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListValuedResourcesRequest', + 'ListValuedResourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'SetMuteRequest', + 'SimulateSecurityHealthAnalyticsCustomModuleRequest', + 'SimulateSecurityHealthAnalyticsCustomModuleResponse', + 'UpdateBigQueryExportRequest', + 'UpdateEventThreatDetectionCustomModuleRequest', + 'UpdateExternalSystemRequest', + 'UpdateFindingRequest', + 'UpdateMuteConfigRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateResourceValueConfigRequest', + 'UpdateSecurityHealthAnalyticsCustomModuleRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'ValidateEventThreatDetectionCustomModuleRequest', + 'ValidateEventThreatDetectionCustomModuleResponse', + 'Simulation', + 'Source', + 'ToxicCombination', + 'ResourceValueConfigMetadata', + 'ValuedResource', + 'Cve', + 'Cvssv3', + 'Package', + 'Reference', + 'SecurityBulletin', + 'Vulnerability', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/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-securitycenter/v1/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.py new file mode 100644 index 000000000000..ac4fb60e1479 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.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. +# +from google.cloud.securitycenter_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + +from .types.access import Access +from .types.access import Geolocation +from .types.access import ServiceAccountDelegationInfo +from .types.application import Application +from .types.asset import Asset +from .types.attack_exposure import AttackExposure +from .types.attack_path import AttackPath +from .types.backup_disaster_recovery import BackupDisasterRecovery +from .types.bigquery_export import BigQueryExport +from .types.cloud_armor import AdaptiveProtection +from .types.cloud_armor import Attack +from .types.cloud_armor import CloudArmor +from .types.cloud_armor import Requests +from .types.cloud_armor import SecurityPolicy +from .types.cloud_dlp_data_profile import CloudDlpDataProfile +from .types.cloud_dlp_inspection import CloudDlpInspection +from .types.compliance import Compliance +from .types.connection import Connection +from .types.contact_details import Contact +from .types.contact_details import ContactDetails +from .types.container import Container +from .types.database import Database +from .types.effective_event_threat_detection_custom_module import EffectiveEventThreatDetectionCustomModule +from .types.effective_security_health_analytics_custom_module import EffectiveSecurityHealthAnalyticsCustomModule +from .types.event_threat_detection_custom_module import EventThreatDetectionCustomModule +from .types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationError +from .types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationErrors +from .types.event_threat_detection_custom_module_validation_errors import Position +from .types.exfiltration import ExfilResource +from .types.exfiltration import Exfiltration +from .types.external_system import ExternalSystem +from .types.file import File +from .types.finding import Finding +from .types.folder import Folder +from .types.group_membership import GroupMembership +from .types.iam_binding import IamBinding +from .types.indicator import Indicator +from .types.kernel_rootkit import KernelRootkit +from .types.kubernetes import Kubernetes +from .types.label import Label +from .types.load_balancer import LoadBalancer +from .types.log_entry import CloudLoggingEntry +from .types.log_entry import LogEntry +from .types.mitre_attack import MitreAttack +from .types.mute_config import MuteConfig +from .types.notebook import Notebook +from .types.notification_config import NotificationConfig +from .types.notification_message import NotificationMessage +from .types.org_policy import OrgPolicy +from .types.organization_settings import OrganizationSettings +from .types.process import EnvironmentVariable +from .types.process import Process +from .types.resource import AwsMetadata +from .types.resource import AzureMetadata +from .types.resource import Resource +from .types.resource import ResourcePath +from .types.resource import CloudProvider +from .types.resource_value_config import ResourceValueConfig +from .types.resource_value_config import ResourceValue +from .types.run_asset_discovery_response import RunAssetDiscoveryResponse +from .types.security_health_analytics_custom_config import CustomConfig +from .types.security_health_analytics_custom_module import SecurityHealthAnalyticsCustomModule +from .types.security_marks import SecurityMarks +from .types.security_posture import SecurityPosture +from .types.securitycenter_service import BatchCreateResourceValueConfigsRequest +from .types.securitycenter_service import BatchCreateResourceValueConfigsResponse +from .types.securitycenter_service import BulkMuteFindingsRequest +from .types.securitycenter_service import BulkMuteFindingsResponse +from .types.securitycenter_service import CreateBigQueryExportRequest +from .types.securitycenter_service import CreateEventThreatDetectionCustomModuleRequest +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateMuteConfigRequest +from .types.securitycenter_service import CreateNotificationConfigRequest +from .types.securitycenter_service import CreateResourceValueConfigRequest +from .types.securitycenter_service import CreateSecurityHealthAnalyticsCustomModuleRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import DeleteBigQueryExportRequest +from .types.securitycenter_service import DeleteEventThreatDetectionCustomModuleRequest +from .types.securitycenter_service import DeleteMuteConfigRequest +from .types.securitycenter_service import DeleteNotificationConfigRequest +from .types.securitycenter_service import DeleteResourceValueConfigRequest +from .types.securitycenter_service import DeleteSecurityHealthAnalyticsCustomModuleRequest +from .types.securitycenter_service import GetBigQueryExportRequest +from .types.securitycenter_service import GetEffectiveEventThreatDetectionCustomModuleRequest +from .types.securitycenter_service import GetEffectiveSecurityHealthAnalyticsCustomModuleRequest +from .types.securitycenter_service import GetEventThreatDetectionCustomModuleRequest +from .types.securitycenter_service import GetMuteConfigRequest +from .types.securitycenter_service import GetNotificationConfigRequest +from .types.securitycenter_service import GetOrganizationSettingsRequest +from .types.securitycenter_service import GetResourceValueConfigRequest +from .types.securitycenter_service import GetSecurityHealthAnalyticsCustomModuleRequest +from .types.securitycenter_service import GetSimulationRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GetValuedResourceRequest +from .types.securitycenter_service import GroupAssetsRequest +from .types.securitycenter_service import GroupAssetsResponse +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAssetsRequest +from .types.securitycenter_service import ListAssetsResponse +from .types.securitycenter_service import ListAttackPathsRequest +from .types.securitycenter_service import ListAttackPathsResponse +from .types.securitycenter_service import ListBigQueryExportsRequest +from .types.securitycenter_service import ListBigQueryExportsResponse +from .types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesRequest +from .types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesResponse +from .types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesRequest +from .types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesResponse +from .types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesRequest +from .types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesResponse +from .types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesRequest +from .types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesResponse +from .types.securitycenter_service import ListEventThreatDetectionCustomModulesRequest +from .types.securitycenter_service import ListEventThreatDetectionCustomModulesResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListMuteConfigsRequest +from .types.securitycenter_service import ListMuteConfigsResponse +from .types.securitycenter_service import ListNotificationConfigsRequest +from .types.securitycenter_service import ListNotificationConfigsResponse +from .types.securitycenter_service import ListResourceValueConfigsRequest +from .types.securitycenter_service import ListResourceValueConfigsResponse +from .types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesRequest +from .types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import ListValuedResourcesRequest +from .types.securitycenter_service import ListValuedResourcesResponse +from .types.securitycenter_service import RunAssetDiscoveryRequest +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import SetMuteRequest +from .types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleRequest +from .types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleResponse +from .types.securitycenter_service import UpdateBigQueryExportRequest +from .types.securitycenter_service import UpdateEventThreatDetectionCustomModuleRequest +from .types.securitycenter_service import UpdateExternalSystemRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateMuteConfigRequest +from .types.securitycenter_service import UpdateNotificationConfigRequest +from .types.securitycenter_service import UpdateOrganizationSettingsRequest +from .types.securitycenter_service import UpdateResourceValueConfigRequest +from .types.securitycenter_service import UpdateSecurityHealthAnalyticsCustomModuleRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.securitycenter_service import ValidateEventThreatDetectionCustomModuleRequest +from .types.securitycenter_service import ValidateEventThreatDetectionCustomModuleResponse +from .types.simulation import Simulation +from .types.source import Source +from .types.toxic_combination import ToxicCombination +from .types.valued_resource import ResourceValueConfigMetadata +from .types.valued_resource import ValuedResource +from .types.vulnerability import Cve +from .types.vulnerability import Cvssv3 +from .types.vulnerability import Package +from .types.vulnerability import Reference +from .types.vulnerability import SecurityBulletin +from .types.vulnerability import Vulnerability + +__all__ = ( + 'SecurityCenterAsyncClient', +'Access', +'AdaptiveProtection', +'Application', +'Asset', +'Attack', +'AttackExposure', +'AttackPath', +'AwsMetadata', +'AzureMetadata', +'BackupDisasterRecovery', +'BatchCreateResourceValueConfigsRequest', +'BatchCreateResourceValueConfigsResponse', +'BigQueryExport', +'BulkMuteFindingsRequest', +'BulkMuteFindingsResponse', +'CloudArmor', +'CloudDlpDataProfile', +'CloudDlpInspection', +'CloudLoggingEntry', +'CloudProvider', +'Compliance', +'Connection', +'Contact', +'ContactDetails', +'Container', +'CreateBigQueryExportRequest', +'CreateEventThreatDetectionCustomModuleRequest', +'CreateFindingRequest', +'CreateMuteConfigRequest', +'CreateNotificationConfigRequest', +'CreateResourceValueConfigRequest', +'CreateSecurityHealthAnalyticsCustomModuleRequest', +'CreateSourceRequest', +'CustomConfig', +'CustomModuleValidationError', +'CustomModuleValidationErrors', +'Cve', +'Cvssv3', +'Database', +'DeleteBigQueryExportRequest', +'DeleteEventThreatDetectionCustomModuleRequest', +'DeleteMuteConfigRequest', +'DeleteNotificationConfigRequest', +'DeleteResourceValueConfigRequest', +'DeleteSecurityHealthAnalyticsCustomModuleRequest', +'EffectiveEventThreatDetectionCustomModule', +'EffectiveSecurityHealthAnalyticsCustomModule', +'EnvironmentVariable', +'EventThreatDetectionCustomModule', +'ExfilResource', +'Exfiltration', +'ExternalSystem', +'File', +'Finding', +'Folder', +'Geolocation', +'GetBigQueryExportRequest', +'GetEffectiveEventThreatDetectionCustomModuleRequest', +'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', +'GetEventThreatDetectionCustomModuleRequest', +'GetMuteConfigRequest', +'GetNotificationConfigRequest', +'GetOrganizationSettingsRequest', +'GetResourceValueConfigRequest', +'GetSecurityHealthAnalyticsCustomModuleRequest', +'GetSimulationRequest', +'GetSourceRequest', +'GetValuedResourceRequest', +'GroupAssetsRequest', +'GroupAssetsResponse', +'GroupFindingsRequest', +'GroupFindingsResponse', +'GroupMembership', +'GroupResult', +'IamBinding', +'Indicator', +'KernelRootkit', +'Kubernetes', +'Label', +'ListAssetsRequest', +'ListAssetsResponse', +'ListAttackPathsRequest', +'ListAttackPathsResponse', +'ListBigQueryExportsRequest', +'ListBigQueryExportsResponse', +'ListDescendantEventThreatDetectionCustomModulesRequest', +'ListDescendantEventThreatDetectionCustomModulesResponse', +'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', +'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', +'ListEffectiveEventThreatDetectionCustomModulesRequest', +'ListEffectiveEventThreatDetectionCustomModulesResponse', +'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', +'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', +'ListEventThreatDetectionCustomModulesRequest', +'ListEventThreatDetectionCustomModulesResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListMuteConfigsRequest', +'ListMuteConfigsResponse', +'ListNotificationConfigsRequest', +'ListNotificationConfigsResponse', +'ListResourceValueConfigsRequest', +'ListResourceValueConfigsResponse', +'ListSecurityHealthAnalyticsCustomModulesRequest', +'ListSecurityHealthAnalyticsCustomModulesResponse', +'ListSourcesRequest', +'ListSourcesResponse', +'ListValuedResourcesRequest', +'ListValuedResourcesResponse', +'LoadBalancer', +'LogEntry', +'MitreAttack', +'MuteConfig', +'Notebook', +'NotificationConfig', +'NotificationMessage', +'OrgPolicy', +'OrganizationSettings', +'Package', +'Position', +'Process', +'Reference', +'Requests', +'Resource', +'ResourcePath', +'ResourceValue', +'ResourceValueConfig', +'ResourceValueConfigMetadata', +'RunAssetDiscoveryRequest', +'RunAssetDiscoveryResponse', +'SecurityBulletin', +'SecurityCenterClient', +'SecurityHealthAnalyticsCustomModule', +'SecurityMarks', +'SecurityPolicy', +'SecurityPosture', +'ServiceAccountDelegationInfo', +'SetFindingStateRequest', +'SetMuteRequest', +'SimulateSecurityHealthAnalyticsCustomModuleRequest', +'SimulateSecurityHealthAnalyticsCustomModuleResponse', +'Simulation', +'Source', +'ToxicCombination', +'UpdateBigQueryExportRequest', +'UpdateEventThreatDetectionCustomModuleRequest', +'UpdateExternalSystemRequest', +'UpdateFindingRequest', +'UpdateMuteConfigRequest', +'UpdateNotificationConfigRequest', +'UpdateOrganizationSettingsRequest', +'UpdateResourceValueConfigRequest', +'UpdateSecurityHealthAnalyticsCustomModuleRequest', +'UpdateSecurityMarksRequest', +'UpdateSourceRequest', +'ValidateEventThreatDetectionCustomModuleRequest', +'ValidateEventThreatDetectionCustomModuleResponse', +'ValuedResource', +'Vulnerability', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json new file mode 100644 index 000000000000..3bca8f8a0f67 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json @@ -0,0 +1,973 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v1", + "protoPackage": "google.cloud.securitycenter.v1", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateEventThreatDetectionCustomModule": { + "methods": [ + "create_event_threat_detection_custom_module" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "create_security_health_analytics_custom_module" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteEventThreatDetectionCustomModule": { + "methods": [ + "delete_event_threat_detection_custom_module" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "DeleteSecurityHealthAnalyticsCustomModule": { + "methods": [ + "delete_security_health_analytics_custom_module" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetEffectiveEventThreatDetectionCustomModule": { + "methods": [ + "get_effective_event_threat_detection_custom_module" + ] + }, + "GetEffectiveSecurityHealthAnalyticsCustomModule": { + "methods": [ + "get_effective_security_health_analytics_custom_module" + ] + }, + "GetEventThreatDetectionCustomModule": { + "methods": [ + "get_event_threat_detection_custom_module" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSecurityHealthAnalyticsCustomModule": { + "methods": [ + "get_security_health_analytics_custom_module" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListDescendantEventThreatDetectionCustomModules": { + "methods": [ + "list_descendant_event_threat_detection_custom_modules" + ] + }, + "ListDescendantSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_descendant_security_health_analytics_custom_modules" + ] + }, + "ListEffectiveEventThreatDetectionCustomModules": { + "methods": [ + "list_effective_event_threat_detection_custom_modules" + ] + }, + "ListEffectiveSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_effective_security_health_analytics_custom_modules" + ] + }, + "ListEventThreatDetectionCustomModules": { + "methods": [ + "list_event_threat_detection_custom_modules" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_security_health_analytics_custom_modules" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "SimulateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "simulate_security_health_analytics_custom_module" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateEventThreatDetectionCustomModule": { + "methods": [ + "update_event_threat_detection_custom_module" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "update_security_health_analytics_custom_module" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + }, + "ValidateEventThreatDetectionCustomModule": { + "methods": [ + "validate_event_threat_detection_custom_module" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateEventThreatDetectionCustomModule": { + "methods": [ + "create_event_threat_detection_custom_module" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "create_security_health_analytics_custom_module" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteEventThreatDetectionCustomModule": { + "methods": [ + "delete_event_threat_detection_custom_module" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "DeleteSecurityHealthAnalyticsCustomModule": { + "methods": [ + "delete_security_health_analytics_custom_module" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetEffectiveEventThreatDetectionCustomModule": { + "methods": [ + "get_effective_event_threat_detection_custom_module" + ] + }, + "GetEffectiveSecurityHealthAnalyticsCustomModule": { + "methods": [ + "get_effective_security_health_analytics_custom_module" + ] + }, + "GetEventThreatDetectionCustomModule": { + "methods": [ + "get_event_threat_detection_custom_module" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSecurityHealthAnalyticsCustomModule": { + "methods": [ + "get_security_health_analytics_custom_module" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListDescendantEventThreatDetectionCustomModules": { + "methods": [ + "list_descendant_event_threat_detection_custom_modules" + ] + }, + "ListDescendantSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_descendant_security_health_analytics_custom_modules" + ] + }, + "ListEffectiveEventThreatDetectionCustomModules": { + "methods": [ + "list_effective_event_threat_detection_custom_modules" + ] + }, + "ListEffectiveSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_effective_security_health_analytics_custom_modules" + ] + }, + "ListEventThreatDetectionCustomModules": { + "methods": [ + "list_event_threat_detection_custom_modules" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_security_health_analytics_custom_modules" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "SimulateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "simulate_security_health_analytics_custom_module" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateEventThreatDetectionCustomModule": { + "methods": [ + "update_event_threat_detection_custom_module" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "update_security_health_analytics_custom_module" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + }, + "ValidateEventThreatDetectionCustomModule": { + "methods": [ + "validate_event_threat_detection_custom_module" + ] + } + } + }, + "rest": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateEventThreatDetectionCustomModule": { + "methods": [ + "create_event_threat_detection_custom_module" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "create_security_health_analytics_custom_module" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteEventThreatDetectionCustomModule": { + "methods": [ + "delete_event_threat_detection_custom_module" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "DeleteSecurityHealthAnalyticsCustomModule": { + "methods": [ + "delete_security_health_analytics_custom_module" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetEffectiveEventThreatDetectionCustomModule": { + "methods": [ + "get_effective_event_threat_detection_custom_module" + ] + }, + "GetEffectiveSecurityHealthAnalyticsCustomModule": { + "methods": [ + "get_effective_security_health_analytics_custom_module" + ] + }, + "GetEventThreatDetectionCustomModule": { + "methods": [ + "get_event_threat_detection_custom_module" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSecurityHealthAnalyticsCustomModule": { + "methods": [ + "get_security_health_analytics_custom_module" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListDescendantEventThreatDetectionCustomModules": { + "methods": [ + "list_descendant_event_threat_detection_custom_modules" + ] + }, + "ListDescendantSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_descendant_security_health_analytics_custom_modules" + ] + }, + "ListEffectiveEventThreatDetectionCustomModules": { + "methods": [ + "list_effective_event_threat_detection_custom_modules" + ] + }, + "ListEffectiveSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_effective_security_health_analytics_custom_modules" + ] + }, + "ListEventThreatDetectionCustomModules": { + "methods": [ + "list_event_threat_detection_custom_modules" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_security_health_analytics_custom_modules" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "SimulateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "simulate_security_health_analytics_custom_module" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateEventThreatDetectionCustomModule": { + "methods": [ + "update_event_threat_detection_custom_module" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "update_security_health_analytics_custom_module" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + }, + "ValidateEventThreatDetectionCustomModule": { + "methods": [ + "validate_event_threat_detection_custom_module" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_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-securitycenter/v1/google/cloud/securitycenter_v1/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_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-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py new file mode 100644 index 000000000000..bffcff5da306 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + 'SecurityCenterClient', + 'SecurityCenterAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py new file mode 100644 index 000000000000..08b61bf6e289 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -0,0 +1,7965 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +import warnings + +from google.cloud.securitycenter_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.securitycenter_v1.services.security_center import pagers +from google.cloud.securitycenter_v1.types import access +from google.cloud.securitycenter_v1.types import application +from google.cloud.securitycenter_v1.types import attack_exposure +from google.cloud.securitycenter_v1.types import attack_path +from google.cloud.securitycenter_v1.types import backup_disaster_recovery +from google.cloud.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import cloud_armor +from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile +from google.cloud.securitycenter_v1.types import cloud_dlp_inspection +from google.cloud.securitycenter_v1.types import compliance +from google.cloud.securitycenter_v1.types import connection +from google.cloud.securitycenter_v1.types import container +from google.cloud.securitycenter_v1.types import database +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors +from google.cloud.securitycenter_v1.types import exfiltration +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import file +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import group_membership +from google.cloud.securitycenter_v1.types import iam_binding +from google.cloud.securitycenter_v1.types import indicator +from google.cloud.securitycenter_v1.types import kernel_rootkit +from google.cloud.securitycenter_v1.types import kubernetes +from google.cloud.securitycenter_v1.types import load_balancer +from google.cloud.securitycenter_v1.types import log_entry +from google.cloud.securitycenter_v1.types import mitre_attack +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notebook +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import org_policy +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import process +from google.cloud.securitycenter_v1.types import resource +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import security_posture +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import toxic_combination +from google.cloud.securitycenter_v1.types import valued_resource +from google.cloud.securitycenter_v1.types import vulnerability +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 empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V1 APIs for Security Center service.""" + + _client: SecurityCenterClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE + + asset_path = staticmethod(SecurityCenterClient.asset_path) + parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) + attack_path_path = staticmethod(SecurityCenterClient.attack_path_path) + parse_attack_path_path = staticmethod(SecurityCenterClient.parse_attack_path_path) + big_query_export_path = staticmethod(SecurityCenterClient.big_query_export_path) + parse_big_query_export_path = staticmethod(SecurityCenterClient.parse_big_query_export_path) + dlp_job_path = staticmethod(SecurityCenterClient.dlp_job_path) + parse_dlp_job_path = staticmethod(SecurityCenterClient.parse_dlp_job_path) + effective_event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.effective_event_threat_detection_custom_module_path) + parse_effective_event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.parse_effective_event_threat_detection_custom_module_path) + effective_security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.effective_security_health_analytics_custom_module_path) + parse_effective_security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.parse_effective_security_health_analytics_custom_module_path) + event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.event_threat_detection_custom_module_path) + parse_event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.parse_event_threat_detection_custom_module_path) + external_system_path = staticmethod(SecurityCenterClient.external_system_path) + parse_external_system_path = staticmethod(SecurityCenterClient.parse_external_system_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) + parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) + mute_config_path = staticmethod(SecurityCenterClient.mute_config_path) + parse_mute_config_path = staticmethod(SecurityCenterClient.parse_mute_config_path) + notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) + parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) + organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) + parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) + policy_path = staticmethod(SecurityCenterClient.policy_path) + parse_policy_path = staticmethod(SecurityCenterClient.parse_policy_path) + resource_value_config_path = staticmethod(SecurityCenterClient.resource_value_config_path) + parse_resource_value_config_path = staticmethod(SecurityCenterClient.parse_resource_value_config_path) + security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.security_health_analytics_custom_module_path) + parse_security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.parse_security_health_analytics_custom_module_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) + simulation_path = staticmethod(SecurityCenterClient.simulation_path) + parse_simulation_path = staticmethod(SecurityCenterClient.parse_simulation_path) + source_path = staticmethod(SecurityCenterClient.source_path) + parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) + table_data_profile_path = staticmethod(SecurityCenterClient.table_data_profile_path) + parse_table_data_profile_path = staticmethod(SecurityCenterClient.parse_table_data_profile_path) + topic_path = staticmethod(SecurityCenterClient.topic_path) + parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) + valued_resource_path = staticmethod(SecurityCenterClient.valued_resource_path) + parse_valued_resource_path = staticmethod(SecurityCenterClient.parse_valued_resource_path) + common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) + parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) + common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) + parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) + common_project_path = staticmethod(SecurityCenterClient.common_project_path) + parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) + common_location_path = staticmethod(SecurityCenterClient.common_location_path) + parse_common_location_path = staticmethod(SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def bulk_mute_findings(self, + request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off an LRO to bulk mute findings for a parent + based on a filter. The parent can be either an + organization, folder or project. The findings matched by + the filter will be muted after the LRO is done. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest, dict]]): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + parent (:class:`str`): + Required. The parent, at which bulk action needs to be + applied. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1.types.BulkMuteFindingsResponse` + The response to a BulkMute request. Contains the LRO + 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]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): + request = securitycenter_service.BulkMuteFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.bulk_mute_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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + securitycenter_service.BulkMuteFindingsResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def create_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Creates a resident + SecurityHealthAnalyticsCustomModule at the scope of the + given CRM parent, and also creates inherited + SecurityHealthAnalyticsCustomModules for all CRM + descendants of the given parent. These modules are + enabled by default. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_create_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]]): + The request object. Request message for creating Security + Health Analytics custom modules. + parent (:class:`str`): + Required. Resource name of the new custom module's + parent. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_health_analytics_custom_module (:class:`google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule`): + Required. SecurityHealthAnalytics + custom module to create. The provided + name is ignored and reset with provided + parent information and server-generated + ID. + + This corresponds to the ``security_health_analytics_custom_module`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, security_health_analytics_custom_module]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_health_analytics_custom_module is not None: + request.security_health_analytics_custom_module = security_health_analytics_custom_module + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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 create_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v1 + + async def sample_create_source(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateSourceRequest, dict]]): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be ``organizations/[organization_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`google.cloud.securitycenter_v1.types.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = 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_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding_id: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_create_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateFindingRequest, dict]]): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + ``organizations/[organization_id]/sources/[source_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`google.cloud.securitycenter_v1.types.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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 create_mute_config(self, + request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + mute_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Creates a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_create_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = await client.create_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateMuteConfigRequest, dict]]): + The request object. Request message for creating a mute + config. + parent (:class:`str`): + Required. Resource name of the new mute configs's + parent. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config (:class:`google.cloud.securitycenter_v1.types.MuteConfig`): + Required. The mute config being + created. + + This corresponds to the ``mute_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``mute_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.cloud.securitycenter_v1.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): + request = securitycenter_service.CreateMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mute_config is not None: + request.mute_config = mute_config + if mute_config_id is not None: + request.mute_config_id = mute_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_mute_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 create_notification_config(self, + request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + config_id: Optional[str] = None, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_create_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest, dict]]): + The request object. Request message for creating a + notification config. + parent (:class:`str`): + Required. Resource name of the new notification config's + parent. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (:class:`str`): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters and contain + alphanumeric characters, underscores, or + hyphens only. + + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_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.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_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_notification_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_mute_config(self, + request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_delete_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_mute_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest, dict]]): + The request object. Request message for deleting a mute + config. + name (:class:`str`): + Required. Name of the mute config to delete. Its format + is + ``organizations/{organization}/muteConfigs/{config_id}``, + ``folders/{folder}/muteConfigs/{config_id}``, + ``projects/{project}/muteConfigs/{config_id}``, + ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, + ``folders/{folder}/locations/global/muteConfigs/{config_id}``, + or + ``projects/{project}/locations/global/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): + request = securitycenter_service.DeleteMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_mute_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 delete_notification_config(self, + request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest, dict]]): + The request object. Request message for deleting a + notification config. + name (:class:`str`): + Required. Name of the notification config to delete. Its + format is + ``organizations/[organization_id]/notificationConfigs/[config_id]``, + ``folders/[folder_id]/notificationConfigs/[config_id]``, + or + ``projects/[project_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 delete_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]] = 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 + SecurityHealthAnalyticsCustomModule and all of its + descendants in the CRM hierarchy. This method is only + supported for resident custom modules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_delete_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + await client.delete_security_health_analytics_custom_module(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]]): + The request object. Request message for deleting Security + Health Analytics custom modules. + name (:class:`str`): + Required. Name of the custom module to delete. Its + format is + ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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, securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_simulation(self, + request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> simulation.Simulation: + r"""Get the simulation by name or the latest simulation + for the given organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_simulation(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_simulation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetSimulationRequest, dict]]): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + name (:class:`str`): + Required. The organization name or simulation name of + this simulation + + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Simulation: + Attack path simulation + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSimulationRequest): + request = securitycenter_service.GetSimulationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_simulation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_valued_resource(self, + request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> valued_resource.ValuedResource: + r"""Get the valued resource by 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 import securitycenter_v1 + + async def sample_get_valued_resource(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_valued_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetValuedResourceRequest, dict]]): + The request object. Request message for getting a valued + resource. + name (:class:`str`): + Required. The name of this valued resource + + Valid format: + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v1.types.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetValuedResourceRequest): + request = securitycenter_service.GetValuedResourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_valued_resource] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_big_query_export(self, + request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Gets a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetBigQueryExportRequest, dict]]): + The request object. Request message for retrieving a + BigQuery export. + name (:class:`str`): + Required. Name of the BigQuery export to retrieve. Its + format is + ``organizations/{organization}/bigQueryExports/{export_id}``, + ``folders/{folder}/bigQueryExports/{export_id}``, or + ``projects/{project}/bigQueryExports/{export_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.cloud.securitycenter_v1.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): + request = securitycenter_service.GetBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 get_mute_config(self, + request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> mute_config.MuteConfig: + r"""Gets a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetMuteConfigRequest, dict]]): + The request object. Request message for retrieving a mute + config. + name (:class:`str`): + Required. Name of the mute config to retrieve. Its + format is + ``organizations/{organization}/muteConfigs/{config_id}``, + ``folders/{folder}/muteConfigs/{config_id}``, + ``projects/{project}/muteConfigs/{config_id}``, + ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, + ``folders/{folder}/locations/global/muteConfigs/{config_id}``, + or + ``projects/{project}/locations/global/muteConfigs/{config_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.cloud.securitycenter_v1.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetMuteConfigRequest): + request = securitycenter_service.GetMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_mute_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 get_notification_config(self, + request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetNotificationConfigRequest, dict]]): + The request object. Request message for getting a + notification config. + name (:class:`str`): + Required. Name of the notification config to get. Its + format is + ``organizations/[organization_id]/notificationConfigs/[config_id]``, + ``folders/[folder_id]/notificationConfigs/[config_id]``, + or + ``projects/[project_id]/notificationConfigs/[config_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.cloud.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 get_organization_settings(self, + request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest, dict]]): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + ``organizations/[organization_id]/organizationSettings``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_organization_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 get_effective_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: + r"""Retrieves an + EffectiveSecurityHealthAnalyticsCustomModule. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_effective_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_effective_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]]): + The request object. Request message for getting effective + Security Health Analytics custom + modules. + name (:class:`str`): + Required. Name of the effective custom module to get. + Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule: + An EffectiveSecurityHealthAnalyticsCustomModule is the representation of + a Security Health Analytics custom module at a + specified level of the resource hierarchy: + organization, folder, or project. If a custom module + is inherited from a parent organization or folder, + the value of the enablementState property in + EffectiveSecurityHealthAnalyticsCustomModule is set + to the value that is effective in the parent, instead + of INHERITED. For example, if the module is enabled + in a parent organization or folder, the effective + enablement_state for the module in all child folders + or projects is also enabled. + EffectiveSecurityHealthAnalyticsCustomModule is + read-only. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_effective_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Retrieves a SecurityHealthAnalyticsCustomModule. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest, dict]]): + The request object. Request message for getting Security + Health Analytics custom modules. + name (:class:`str`): + Required. Name of the custom module to get. Its format + is + ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v1 + + async def sample_get_source(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetSourceRequest, dict]]): + The request object. Request message for getting a source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 group_assets(self, + request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsAsyncPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_group_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GroupAssetsRequest, dict]]): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsAsyncPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + warnings.warn("SecurityCenterAsyncClient.group_assets is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.GroupAssetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_group_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GroupFindingsRequest, dict]]): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + ``organizations/[organization_id]/sources/[source_id]``, + ``folders/[folder_id]/sources/[source_id]``, or + ``projects/[project_id]/sources/[source_id]``. To + groupBy across all sources provide a source_id of ``-``. + For example: + ``organizations/{organization_id}/sources/-, folders/{folder_id}/sources/-``, + or ``projects/{project_id}/sources/-`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported when compare_duration + is set: + + - state_change + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets(self, + request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists an organization's assets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListAssetsRequest, dict]]): + The request object. Request message for listing assets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsAsyncPager: + Response message for listing assets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + warnings.warn("SecurityCenterAsyncClient.list_assets is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(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_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListAssetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_descendant_security_health_analytics_custom_modules(self, + request: Optional[Union[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, 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.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: + r"""Returns a list of all resident + SecurityHealthAnalyticsCustomModules under the given CRM + parent and all of the parent’s CRM descendants. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_descendant_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, dict]]): + The request object. Request message for listing + descendant Security Health Analytics + custom modules. + parent (:class:`str`): + Required. Name of parent to list descendant custom + modules. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + 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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: + Response message for listing + descendant Security Health Analytics + custom modules. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_descendant_security_health_analytics_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings(self, + request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListFindingsRequest( + parent="parent_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.securitycenter_v1.types.ListFindingsRequest, dict]]): + The request object. Request message for listing findings. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.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_mute_configs(self, + request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsAsyncPager: + r"""Lists mute configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_mute_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListMuteConfigsRequest, dict]]): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or project. + parent (:class:`str`): + Required. The parent, which owns the collection of mute + configs. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + + 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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsAsyncPager: + Response message for listing mute + configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): + request = securitycenter_service.ListMuteConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_mute_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.ListMuteConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_notification_configs(self, + request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsAsyncPager: + r"""Lists notification configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest, dict]]): + The request object. Request message for listing + notification configs. + parent (:class:`str`): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]", + "folders/[folder_id]", or "projects/[project_id]". + + 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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsAsyncPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListNotificationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_effective_security_health_analytics_custom_modules(self, + request: Optional[Union[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, 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.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: + r"""Returns a list of all + EffectiveSecurityHealthAnalyticsCustomModules for the + given parent. This includes resident modules defined at + the scope of the parent, and inherited modules, + inherited from CRM ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_effective_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_security_health_analytics_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, dict]]): + The request object. Request message for listing effective + Security Health Analytics custom + modules. + parent (:class:`str`): + Required. Name of parent to list effective custom + modules. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + 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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: + Response message for listing + effective Security Health Analytics + custom modules. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_effective_security_health_analytics_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_security_health_analytics_custom_modules(self, + request: Optional[Union[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, 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.ListSecurityHealthAnalyticsCustomModulesAsyncPager: + r"""Returns a list of all + SecurityHealthAnalyticsCustomModules for the given + parent. This includes resident modules defined at the + scope of the parent, and inherited modules, inherited + from CRM ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_health_analytics_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest, dict]]): + The request object. Request message for listing Security + Health Analytics custom modules. + parent (:class:`str`): + Required. Name of parent to list custom modules. Its + format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + 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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager: + Response message for listing Security + Health Analytics custom modules. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_security_health_analytics_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListSecurityHealthAnalyticsCustomModulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_sources(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListSourcesRequest, dict]]): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + 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.securitycenter_v1.services.security_center.pagers.ListSourcesAsyncPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_asset_discovery(self, + request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS 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 securitycenter_v1 + + async def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest, dict]]): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + ``organizations/[organization_id]``. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` + Response of asset discovery run + + """ + warnings.warn("SecurityCenterAsyncClient.run_asset_discovery is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.run_asset_discovery] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + start_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of 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 securitycenter_v1 + + async def sample_set_finding_state(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.SetFindingStateRequest, dict]]): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The `relative resource + name `__ + of the finding. Example: + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, + ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`google.cloud.securitycenter_v1.types.Finding.State`): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_mute(self, + request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, + *, + name: Optional[str] = None, + mute: Optional[finding.Finding.Mute] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the mute state of 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 securitycenter_v1 + + async def sample_set_mute(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = await client.set_mute(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.SetMuteRequest, dict]]): + The request object. Request message for updating a + finding's mute status. + name (:class:`str`): + Required. The `relative resource + name `__ + of the finding. Example: + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, + ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute (:class:`google.cloud.securitycenter_v1.types.Finding.Mute`): + Required. The desired state of the + Mute. + + This corresponds to the ``mute`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, mute]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetMuteRequest): + request = securitycenter_service.SetMuteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if mute is not None: + request.mute = mute + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.set_mute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 simulate_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_config: Optional[security_health_analytics_custom_config.CustomConfig] = None, + resource: Optional[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: + r"""Simulates a given SecurityHealthAnalyticsCustomModule + and Resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_simulate_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + resource = securitycenter_v1.SimulatedResource() + resource.resource_type = "resource_type_value" + + request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + resource=resource, + ) + + # Make the request + response = await client.simulate_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]]): + The request object. Request message to simulate a + CustomConfig against a given test + resource. Maximum size of the request is + 4 MB by default. + parent (:class:`str`): + Required. The relative resource name of the + organization, project, or folder. For more information + about relative resource names, see `Relative Resource + Name `__ + Example: ``organizations/{organization_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_config (:class:`google.cloud.securitycenter_v1.types.CustomConfig`): + Required. The custom configuration + that you need to test. + + This corresponds to the ``custom_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (:class:`google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource`): + Required. Resource data to simulate + custom module against. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse: + Response message for simulating a SecurityHealthAnalyticsCustomModule + against a given 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, custom_config, resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_config is not None: + request.custom_config = custom_config + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.simulate_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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_external_system(self, + request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, + *, + external_system: Optional[gcs_external_system.ExternalSystem] = None, + update_mask: 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]] = (), + ) -> gcs_external_system.ExternalSystem: + r"""Updates external system. This is for a given 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 securitycenter_v1 + + async def sample_update_external_system(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateExternalSystemRequest( + ) + + # Make the request + response = await client.update_external_system(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest, dict]]): + The request object. Request message for updating a + ExternalSystem resource. + external_system (:class:`google.cloud.securitycenter_v1.types.ExternalSystem`): + Required. The external system + resource to update. + + This corresponds to the ``external_system`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the external system resource. + If empty all mutable fields 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.cloud.securitycenter_v1.types.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): + request = securitycenter_service.UpdateExternalSystemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if external_system is not None: + request.external_system = external_system + 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_external_system] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("external_system.name", request.external_system.name), + )), + ) + + # Validate the universe domain. + self._client._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_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateFindingRequest, dict]]): + The request object. Request message for updating or + creating a finding. + finding (:class:`google.cloud.securitycenter_v1.types.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe domain. + self._client._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_mute_config(self, + request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, + *, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + update_mask: 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]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Updates a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = await client.update_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest, dict]]): + The request object. Request message for updating a mute + config. + mute_config (:class:`google.cloud.securitycenter_v1.types.MuteConfig`): + Required. The mute config being + updated. + + This corresponds to the ``mute_config`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): + request = securitycenter_service.UpdateMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mute_config is not None: + request.mute_config = mute_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_mute_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("mute_config.name", request.mute_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 update_notification_config(self, + request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, + *, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + update_mask: 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest, dict]]): + The request object. Request message for updating a + notification config. + notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the notification config. + If empty all mutable fields 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.cloud.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_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 update_organization_settings(self, + request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, + *, + organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = await client.update_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest, dict]]): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`google.cloud.securitycenter_v1.types.OrganizationSettings`): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_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 update_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, + update_mask: 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]] = (), + ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Updates the SecurityHealthAnalyticsCustomModule under + the given name based on the given update mask. Updating + the enablement state is supported on both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name and custom config of a module is supported + on resident modules only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( + ) + + # Make the request + response = await client.update_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]]): + The request object. Request message for updating Security + Health Analytics custom modules. + security_health_analytics_custom_module (:class:`google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule`): + Required. The SecurityHealthAnalytics + custom module to update. + + This corresponds to the ``security_health_analytics_custom_module`` 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 only fields that + can be updated are ``enablement_state`` and + ``custom_config``. If empty or set to the wildcard value + ``*``, both ``enablement_state`` and ``custom_config`` + are 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.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_health_analytics_custom_module, 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, securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_health_analytics_custom_module is not None: + request.security_health_analytics_custom_module = security_health_analytics_custom_module + 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_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_health_analytics_custom_module.name", request.security_health_analytics_custom_module.name), + )), + ) + + # Validate the universe domain. + self._client._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_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v1 + + async def sample_update_source(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateSourceRequest, dict]]): + The request object. Request message for updating a + source. + source (:class:`google.cloud.securitycenter_v1.types.Source`): + Required. The source resource to + update. + + This corresponds to the ``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.cloud.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_security_marks(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest, dict]]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`google.cloud.securitycenter_v1.types.SecurityMarks`): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe domain. + self._client._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_big_query_export(self, + request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, + *, + parent: Optional[str] = None, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + big_query_export_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Creates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_create_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = await client.create_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest, dict]]): + The request object. Request message for creating a + BigQuery export. + parent (:class:`str`): + Required. The name of the parent resource of the new + BigQuery export. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export (:class:`google.cloud.securitycenter_v1.types.BigQueryExport`): + Required. The BigQuery export being + created. + + This corresponds to the ``big_query_export`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``big_query_export_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.cloud.securitycenter_v1.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): + request = securitycenter_service.CreateBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if big_query_export is not None: + request.big_query_export = big_query_export + if big_query_export_id is not None: + request.big_query_export_id = big_query_export_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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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_big_query_export(self, + request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + await client.delete_big_query_export(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest, dict]]): + The request object. Request message for deleting a + BigQuery export. + name (:class:`str`): + Required. The name of the BigQuery export to delete. Its + format is + ``organizations/{organization}/bigQueryExports/{export_id}``, + ``folders/{folder}/bigQueryExports/{export_id}``, or + ``projects/{project}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): + request = securitycenter_service.DeleteBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_big_query_export(self, + request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, + *, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + update_mask: 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]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Updates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateBigQueryExportRequest( + ) + + # Make the request + response = await client.update_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest, dict]]): + The request object. Request message for updating a + BigQuery export. + big_query_export (:class:`google.cloud.securitycenter_v1.types.BigQueryExport`): + Required. The BigQuery export being + updated. + + This corresponds to the ``big_query_export`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): + request = securitycenter_service.UpdateBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if big_query_export is not None: + request.big_query_export = big_query_export + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("big_query_export.name", request.big_query_export.name), + )), + ) + + # Validate the universe domain. + self._client._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_big_query_exports(self, + request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsAsyncPager: + r"""Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are 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 securitycenter_v1 + + async def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest, dict]]): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or project. + parent (:class:`str`): + Required. The parent, which owns the collection of + BigQuery exports. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + + 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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsAsyncPager: + Response message for listing BigQuery + exports. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): + request = securitycenter_service.ListBigQueryExportsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_big_query_exports] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListBigQueryExportsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Creates a resident Event Threat Detection custom + module at the scope of the given Resource Manager + parent, and also creates inherited custom modules for + all descendants of the given parent. These modules are + enabled by default. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_create_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest, dict]]): + The request object. Request to create an Event Threat + Detection custom module. + parent (:class:`str`): + Required. The new custom module's parent. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_threat_detection_custom_module (:class:`google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule`): + Required. The module to create. The + event_threat_detection_custom_module.name will be + ignored and server generated. + + This corresponds to the ``event_threat_detection_custom_module`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, event_threat_detection_custom_module]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if event_threat_detection_custom_module is not None: + request.event_threat_detection_custom_module = event_threat_detection_custom_module + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, dict]] = 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 Event Threat Detection custom + module and all of its descendants in the Resource + Manager hierarchy. This method is only supported for + resident custom modules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_delete_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + await client.delete_event_threat_detection_custom_module(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest, dict]]): + The request object. Request to delete an Event Threat + Detection custom module. + name (:class:`str`): + Required. Name of the custom module to delete. + + Its format is: + + - "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}". + - "folders/{folder}/eventThreatDetectionSettings/customModules/{module}". + - "projects/{project}/eventThreatDetectionSettings/customModules/{module}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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, securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.GetEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Gets an Event Threat Detection custom module. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest, dict]]): + The request object. Request to get an Event Threat + Detection custom module. + name (:class:`str`): + Required. Name of the custom module to get. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_descendant_event_threat_detection_custom_modules(self, + request: Optional[Union[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, 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.ListDescendantEventThreatDetectionCustomModulesAsyncPager: + r"""Lists all resident Event Threat Detection custom + modules under the given Resource Manager parent and its + descendants. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_descendant_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest, dict]]): + The request object. Request to list current and + descendant resident Event Threat + Detection custom modules. + parent (:class:`str`): + Required. Name of the parent to list custom modules + under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + 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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager: + Response for listing current and + descendant resident Event Threat + Detection custom modules. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_descendant_event_threat_detection_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListDescendantEventThreatDetectionCustomModulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_event_threat_detection_custom_modules(self, + request: Optional[Union[securitycenter_service.ListEventThreatDetectionCustomModulesRequest, 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.ListEventThreatDetectionCustomModulesAsyncPager: + r"""Lists all Event Threat Detection custom modules for + the given Resource Manager parent. This includes + resident modules defined at the scope of the parent + along with modules inherited from ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_event_threat_detection_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest, dict]]): + The request object. Request to list Event Threat + Detection custom modules. + parent (:class:`str`): + Required. Name of the parent to list custom modules + under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + 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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesAsyncPager: + Response for listing Event Threat + Detection custom modules. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListEventThreatDetectionCustomModulesRequest): + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_event_threat_detection_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListEventThreatDetectionCustomModulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, + update_mask: 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]] = (), + ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Updates the Event Threat Detection custom module with + the given name based on the given update mask. Updating + the enablement state is supported for both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name or configuration of a module is supported + for resident modules only. The type of a module cannot + be changed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( + ) + + # Make the request + response = await client.update_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest, dict]]): + The request object. Request to update an Event Threat + Detection custom module. + event_threat_detection_custom_module (:class:`google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule`): + Required. The module being updated. + This corresponds to the ``event_threat_detection_custom_module`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([event_threat_detection_custom_module, 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, securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if event_threat_detection_custom_module is not None: + request.event_threat_detection_custom_module = event_threat_detection_custom_module + 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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("event_threat_detection_custom_module.name", request.event_threat_detection_custom_module.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def validate_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: + r"""Validates the given Event Threat Detection custom + module. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_validate_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + raw_text="raw_text_value", + type_="type__value", + ) + + # Make the request + response = await client.validate_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest, dict]]): + The request object. Request to validate an Event Threat + Detection custom module. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse: + Response to validating an Event + Threat Detection custom module. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest(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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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_effective_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: + r"""Gets an effective Event Threat Detection custom + module at the given level. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_effective_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_effective_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]]): + The request object. Request to get an + EffectiveEventThreatDetectionCustomModule. + name (:class:`str`): + Required. The resource name of the effective Event + Threat Detection custom module. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule: + An EffectiveEventThreatDetectionCustomModule is the representation of + an Event Threat Detection custom module at a + specified level of the resource hierarchy: + organization, folder, or project. If a custom module + is inherited from a parent organization or folder, + the value of the enablement_state property in + EffectiveEventThreatDetectionCustomModule is set to + the value that is effective in the parent, instead of + INHERITED. For example, if the module is enabled in a + parent organization or folder, the effective + enablement_state for the module in all child folders + or projects is also enabled. + EffectiveEventThreatDetectionCustomModule is + read-only. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_effective_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_effective_event_threat_detection_custom_modules(self, + request: Optional[Union[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, 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.ListEffectiveEventThreatDetectionCustomModulesAsyncPager: + r"""Lists all effective Event Threat Detection custom + modules for the given parent. This includes resident + modules defined at the scope of the parent along with + modules inherited from its ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_effective_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_event_threat_detection_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest, dict]]): + The request object. Request to list effective Event + Threat Detection custom modules. + parent (:class:`str`): + Required. Name of the parent to list custom modules for. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + 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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesAsyncPager: + Response for listing + EffectiveEventThreatDetectionCustomModules. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_effective_event_threat_detection_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListEffectiveEventThreatDetectionCustomModulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_create_resource_value_configs(self, + request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + requests = securitycenter_v1.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + requests.resource_value_config.resource_value = "NONE" + requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest, dict]]): + The request object. Request message to create multiple + resource value configs + parent (:class:`str`): + Required. Resource name of the new + ResourceValueConfig's parent. The parent + field in the + CreateResourceValueConfigRequest + messages must either be empty or match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (:class:`MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]`): + Required. The resource value configs + to be created. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, requests]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): + request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests: + request.requests.extend(requests) + + # 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_resource_value_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, + ) + + # Done; return the response. + return response + + async def delete_resource_value_config(self, + request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_resource_value_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest, dict]]): + The request object. Request message to delete resource + value config + name (:class:`str`): + Required. Name of the + ResourceValueConfig 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. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): + request = securitycenter_service.DeleteResourceValueConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_resource_value_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_resource_value_config(self, + request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource_value_config.ResourceValueConfig: + r"""Gets a ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest, dict]]): + The request object. Request message to get resource value + config + name (:class:`str`): + Required. Name of the resource value config to retrieve. + Its format is + ``organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v1.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): + request = securitycenter_service.GetResourceValueConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_resource_value_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_resource_value_configs(self, + request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsAsyncPager: + r"""Lists all ResourceValueConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest, dict]]): + The request object. Request message to list resource + value configs of a parent + parent (:class:`str`): + Required. The parent, which owns the collection of + resource value configs. Its format is + ``organizations/[organization_id]`` + + 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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsAsyncPager: + Response message to list resource + value configs + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): + request = securitycenter_service.ListResourceValueConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_resource_value_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.ListResourceValueConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_resource_value_config(self, + request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, + *, + resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, + update_mask: 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]] = (), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Updates an existing ResourceValueConfigs with new + rules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + resource_value_config = securitycenter_v1.ResourceValueConfig() + resource_value_config.resource_value = "NONE" + resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.UpdateResourceValueConfigRequest( + resource_value_config=resource_value_config, + ) + + # Make the request + response = await client.update_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest, dict]]): + The request object. Request message to update resource + value config + resource_value_config (:class:`google.cloud.securitycenter_v1.types.ResourceValueConfig`): + Required. The resource value config + being updated. + + This corresponds to the ``resource_value_config`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): + request = securitycenter_service.UpdateResourceValueConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if resource_value_config is not None: + request.resource_value_config = resource_value_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_resource_value_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource_value_config.name", request.resource_value_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 list_valued_resources(self, + request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesAsyncPager: + r"""Lists the valued resources for a set of simulation + results and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_valued_resources(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListValuedResourcesRequest, dict]]): + The request object. Request message for listing the + valued resources for a given simulation. + parent (:class:`str`): + Required. Name of parent to list valued resources. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + + 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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesAsyncPager: + Response message for listing the + valued resources for a given simulation. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): + request = securitycenter_service.ListValuedResourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_valued_resources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListValuedResourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_attack_paths(self, + request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsAsyncPager: + r"""Lists the attack paths for a set of simulation + results or valued resources and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_attack_paths(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListAttackPathsRequest, dict]]): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + parent (:class:`str`): + Required. Name of parent to list attack paths. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + + 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.securitycenter_v1.services.security_center.pagers.ListAttackPathsAsyncPager: + Response message for listing the + attack paths for a given simulation or + valued resource. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): + request = securitycenter_service.ListAttackPathsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_attack_paths] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListAttackPathsAsyncPager( + method=rpc, + request=request, + response=response, + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "SecurityCenterAsyncClient": + 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__ = ( + "SecurityCenterAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py new file mode 100644 index 000000000000..2b23b6e3a02c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py @@ -0,0 +1,8455 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_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.securitycenter_v1.services.security_center import pagers +from google.cloud.securitycenter_v1.types import access +from google.cloud.securitycenter_v1.types import application +from google.cloud.securitycenter_v1.types import attack_exposure +from google.cloud.securitycenter_v1.types import attack_path +from google.cloud.securitycenter_v1.types import backup_disaster_recovery +from google.cloud.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import cloud_armor +from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile +from google.cloud.securitycenter_v1.types import cloud_dlp_inspection +from google.cloud.securitycenter_v1.types import compliance +from google.cloud.securitycenter_v1.types import connection +from google.cloud.securitycenter_v1.types import container +from google.cloud.securitycenter_v1.types import database +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors +from google.cloud.securitycenter_v1.types import exfiltration +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import file +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import group_membership +from google.cloud.securitycenter_v1.types import iam_binding +from google.cloud.securitycenter_v1.types import indicator +from google.cloud.securitycenter_v1.types import kernel_rootkit +from google.cloud.securitycenter_v1.types import kubernetes +from google.cloud.securitycenter_v1.types import load_balancer +from google.cloud.securitycenter_v1.types import log_entry +from google.cloud.securitycenter_v1.types import mitre_attack +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notebook +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import org_policy +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import process +from google.cloud.securitycenter_v1.types import resource +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import security_posture +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import toxic_combination +from google.cloud.securitycenter_v1.types import valued_resource +from google.cloud.securitycenter_v1.types import vulnerability +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 empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .transports.rest import SecurityCenterRestTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + _transport_registry["rest"] = SecurityCenterRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SecurityCenterTransport]: + """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V1 APIs for Security Center 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 = "securitycenter.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: + SecurityCenterClient: 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: + SecurityCenterClient: 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) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def asset_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified asset string.""" + return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_asset_path(path: str) -> Dict[str,str]: + """Parses a asset path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def attack_path_path(organization: str,simulation: str,valued_resource: str,attack_path: str,) -> str: + """Returns a fully-qualified attack_path string.""" + return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) + + @staticmethod + def parse_attack_path_path(path: str) -> Dict[str,str]: + """Parses a attack_path path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?P.+?)/attackPaths/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def big_query_export_path(organization: str,export: str,) -> str: + """Returns a fully-qualified big_query_export string.""" + return "organizations/{organization}/bigQueryExports/{export}".format(organization=organization, export=export, ) + + @staticmethod + def parse_big_query_export_path(path: str) -> Dict[str,str]: + """Parses a big_query_export path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/bigQueryExports/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def dlp_job_path(project: str,dlp_job: str,) -> str: + """Returns a fully-qualified dlp_job string.""" + return "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) + + @staticmethod + def parse_dlp_job_path(path: str) -> Dict[str,str]: + """Parses a dlp_job path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/dlpJobs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def effective_event_threat_detection_custom_module_path(organization: str,module: str,) -> str: + """Returns a fully-qualified effective_event_threat_detection_custom_module string.""" + return "organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}".format(organization=organization, module=module, ) + + @staticmethod + def parse_effective_event_threat_detection_custom_module_path(path: str) -> Dict[str,str]: + """Parses a effective_event_threat_detection_custom_module path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/eventThreatDetectionSettings/effectiveCustomModules/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def effective_security_health_analytics_custom_module_path(organization: str,effective_custom_module: str,) -> str: + """Returns a fully-qualified effective_security_health_analytics_custom_module string.""" + return "organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{effective_custom_module}".format(organization=organization, effective_custom_module=effective_custom_module, ) + + @staticmethod + def parse_effective_security_health_analytics_custom_module_path(path: str) -> Dict[str,str]: + """Parses a effective_security_health_analytics_custom_module path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/securityHealthAnalyticsSettings/effectiveCustomModules/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def event_threat_detection_custom_module_path(organization: str,module: str,) -> str: + """Returns a fully-qualified event_threat_detection_custom_module string.""" + return "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}".format(organization=organization, module=module, ) + + @staticmethod + def parse_event_threat_detection_custom_module_path(path: str) -> Dict[str,str]: + """Parses a event_threat_detection_custom_module path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/eventThreatDetectionSettings/customModules/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def external_system_path(organization: str,source: str,finding: str,externalsystem: str,) -> str: + """Returns a fully-qualified external_system string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) + + @staticmethod + def parse_external_system_path(path: str) -> Dict[str,str]: + """Parses a external_system path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)/externalSystems/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def finding_path(organization: str,source: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def mute_config_path(organization: str,mute_config: str,) -> str: + """Returns a fully-qualified mute_config string.""" + return "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) + + @staticmethod + def parse_mute_config_path(path: str) -> Dict[str,str]: + """Parses a mute_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/muteConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def notification_config_path(organization: str,notification_config: str,) -> str: + """Returns a fully-qualified notification_config string.""" + return "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) + + @staticmethod + def parse_notification_config_path(path: str) -> Dict[str,str]: + """Parses a notification_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def organization_settings_path(organization: str,) -> str: + """Returns a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format(organization=organization, ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str,str]: + """Parses a organization_settings path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def policy_path(organization: str,constraint_name: str,) -> str: + """Returns a fully-qualified policy string.""" + return "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) + + @staticmethod + def parse_policy_path(path: str) -> Dict[str,str]: + """Parses a policy path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/policies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def resource_value_config_path(organization: str,resource_value_config: str,) -> str: + """Returns a fully-qualified resource_value_config string.""" + return "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) + + @staticmethod + def parse_resource_value_config_path(path: str) -> Dict[str,str]: + """Parses a resource_value_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/resourceValueConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_health_analytics_custom_module_path(organization: str,custom_module: str,) -> str: + """Returns a fully-qualified security_health_analytics_custom_module string.""" + return "organizations/{organization}/securityHealthAnalyticsSettings/customModules/{custom_module}".format(organization=organization, custom_module=custom_module, ) + + @staticmethod + def parse_security_health_analytics_custom_module_path(path: str) -> Dict[str,str]: + """Parses a security_health_analytics_custom_module path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/securityHealthAnalyticsSettings/customModules/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str,str]: + """Parses a security_marks path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) + return m.groupdict() if m else {} + + @staticmethod + def simulation_path(organization: str,simulation: str,) -> str: + """Returns a fully-qualified simulation string.""" + return "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) + + @staticmethod + def parse_simulation_path(path: str) -> Dict[str,str]: + """Parses a simulation path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str,source: str,) -> str: + """Returns a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str,str]: + """Parses a source path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def table_data_profile_path(project: str,table_profile: str,) -> str: + """Returns a fully-qualified table_data_profile string.""" + return "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) + + @staticmethod + def parse_table_data_profile_path(path: str) -> Dict[str,str]: + """Parses a table_data_profile path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/tableProfiles/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def topic_path(project: str,topic: str,) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str,str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def valued_resource_path(organization: str,simulation: str,valued_resource: str,) -> str: + """Returns a fully-qualified valued_resource string.""" + return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) + + @staticmethod + def parse_valued_resource_path(path: str) -> Dict[str,str]: + """Parses a valued_resource path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 + SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient._read_environment_variables() + self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) + if transport_provided: + # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SecurityCenterTransport], 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 bulk_mute_findings(self, + request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), + ) -> operation.Operation: + r"""Kicks off an LRO to bulk mute findings for a parent + based on a filter. The parent can be either an + organization, folder or project. The findings matched by + the filter will be muted after the LRO is done. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest, dict]): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + parent (str): + Required. The parent, at which bulk action needs to be + applied. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1.types.BulkMuteFindingsResponse` + The response to a BulkMute request. Contains the LRO + 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): + request = securitycenter_service.BulkMuteFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.bulk_mute_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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + securitycenter_service.BulkMuteFindingsResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def create_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Creates a resident + SecurityHealthAnalyticsCustomModule at the scope of the + given CRM parent, and also creates inherited + SecurityHealthAnalyticsCustomModules for all CRM + descendants of the given parent. These modules are + enabled by default. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_create_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]): + The request object. Request message for creating Security + Health Analytics custom modules. + parent (str): + Required. Resource name of the new custom module's + parent. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): + Required. SecurityHealthAnalytics + custom module to create. The provided + name is ignored and reset with provided + parent information and server-generated + ID. + + This corresponds to the ``security_health_analytics_custom_module`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, security_health_analytics_custom_module]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_health_analytics_custom_module is not None: + request.security_health_analytics_custom_module = security_health_analytics_custom_module + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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 create_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v1 + + def sample_create_source(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateSourceRequest, dict]): + The request object. Request message for creating a + source. + parent (str): + Required. Resource name of the new source's parent. Its + format should be ``organizations/[organization_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (google.cloud.securitycenter_v1.types.Source): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding_id: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_create_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateFindingRequest, dict]): + The request object. Request message for creating a + finding. + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + ``organizations/[organization_id]/sources/[source_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (google.cloud.securitycenter_v1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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 create_mute_config(self, + request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + mute_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Creates a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_create_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = client.create_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateMuteConfigRequest, dict]): + The request object. Request message for creating a mute + config. + parent (str): + Required. Resource name of the new mute configs's + parent. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config (google.cloud.securitycenter_v1.types.MuteConfig): + Required. The mute config being + created. + + This corresponds to the ``mute_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``mute_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.cloud.securitycenter_v1.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): + request = securitycenter_service.CreateMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mute_config is not None: + request.mute_config = mute_config + if mute_config_id is not None: + request.mute_config_id = mute_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_mute_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 create_notification_config(self, + request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + config_id: Optional[str] = None, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_create_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest, dict]): + The request object. Request message for creating a + notification config. + parent (str): + Required. Resource name of the new notification config's + parent. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (str): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters and contain + alphanumeric characters, underscores, or + hyphens only. + + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_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.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_notification_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_mute_config(self, + request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_delete_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_mute_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest, dict]): + The request object. Request message for deleting a mute + config. + name (str): + Required. Name of the mute config to delete. Its format + is + ``organizations/{organization}/muteConfigs/{config_id}``, + ``folders/{folder}/muteConfigs/{config_id}``, + ``projects/{project}/muteConfigs/{config_id}``, + ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, + ``folders/{folder}/locations/global/muteConfigs/{config_id}``, + or + ``projects/{project}/locations/global/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): + request = securitycenter_service.DeleteMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_mute_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 delete_notification_config(self, + request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest, dict]): + The request object. Request message for deleting a + notification config. + name (str): + Required. Name of the notification config to delete. Its + format is + ``organizations/[organization_id]/notificationConfigs/[config_id]``, + ``folders/[folder_id]/notificationConfigs/[config_id]``, + or + ``projects/[project_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 delete_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]] = 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 + SecurityHealthAnalyticsCustomModule and all of its + descendants in the CRM hierarchy. This method is only + supported for resident custom modules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_delete_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + client.delete_security_health_analytics_custom_module(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]): + The request object. Request message for deleting Security + Health Analytics custom modules. + name (str): + Required. Name of the custom module to delete. Its + format is + ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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, securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + 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_simulation(self, + request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> simulation.Simulation: + r"""Get the simulation by name or the latest simulation + for the given organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_simulation(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = client.get_simulation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetSimulationRequest, dict]): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + name (str): + Required. The organization name or simulation name of + this simulation + + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Simulation: + Attack path simulation + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSimulationRequest): + request = securitycenter_service.GetSimulationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_simulation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_valued_resource(self, + request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> valued_resource.ValuedResource: + r"""Get the valued resource by 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 import securitycenter_v1 + + def sample_get_valued_resource(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_valued_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetValuedResourceRequest, dict]): + The request object. Request message for getting a valued + resource. + name (str): + Required. The name of this valued resource + + Valid format: + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v1.types.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetValuedResourceRequest): + request = securitycenter_service.GetValuedResourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_valued_resource] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_big_query_export(self, + request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Gets a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = client.get_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetBigQueryExportRequest, dict]): + The request object. Request message for retrieving a + BigQuery export. + name (str): + Required. Name of the BigQuery export to retrieve. Its + format is + ``organizations/{organization}/bigQueryExports/{export_id}``, + ``folders/{folder}/bigQueryExports/{export_id}``, or + ``projects/{project}/bigQueryExports/{export_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.cloud.securitycenter_v1.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): + request = securitycenter_service.GetBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 get_mute_config(self, + request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> mute_config.MuteConfig: + r"""Gets a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetMuteConfigRequest, dict]): + The request object. Request message for retrieving a mute + config. + name (str): + Required. Name of the mute config to retrieve. Its + format is + ``organizations/{organization}/muteConfigs/{config_id}``, + ``folders/{folder}/muteConfigs/{config_id}``, + ``projects/{project}/muteConfigs/{config_id}``, + ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, + ``folders/{folder}/locations/global/muteConfigs/{config_id}``, + or + ``projects/{project}/locations/global/muteConfigs/{config_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.cloud.securitycenter_v1.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetMuteConfigRequest): + request = securitycenter_service.GetMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_mute_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 get_notification_config(self, + request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetNotificationConfigRequest, dict]): + The request object. Request message for getting a + notification config. + name (str): + Required. Name of the notification config to get. Its + format is + ``organizations/[organization_id]/notificationConfigs/[config_id]``, + ``folders/[folder_id]/notificationConfigs/[config_id]``, + or + ``projects/[project_id]/notificationConfigs/[config_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.cloud.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 get_organization_settings(self, + request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest, dict]): + The request object. Request message for getting + organization settings. + name (str): + Required. Name of the organization to get organization + settings for. Its format is + ``organizations/[organization_id]/organizationSettings``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_organization_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 get_effective_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: + r"""Retrieves an + EffectiveSecurityHealthAnalyticsCustomModule. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_effective_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_effective_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]): + The request object. Request message for getting effective + Security Health Analytics custom + modules. + name (str): + Required. Name of the effective custom module to get. + Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule: + An EffectiveSecurityHealthAnalyticsCustomModule is the representation of + a Security Health Analytics custom module at a + specified level of the resource hierarchy: + organization, folder, or project. If a custom module + is inherited from a parent organization or folder, + the value of the enablementState property in + EffectiveSecurityHealthAnalyticsCustomModule is set + to the value that is effective in the parent, instead + of INHERITED. For example, if the module is enabled + in a parent organization or folder, the effective + enablement_state for the module in all child folders + or projects is also enabled. + EffectiveSecurityHealthAnalyticsCustomModule is + read-only. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_effective_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Retrieves a SecurityHealthAnalyticsCustomModule. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest, dict]): + The request object. Request message for getting Security + Health Analytics custom modules. + name (str): + Required. Name of the custom module to get. Its format + is + ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v1 + + def sample_get_source(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetSourceRequest, dict]): + The request object. Request message for getting a source. + name (str): + Required. Relative resource name of the source. Its + format is + ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 group_assets(self, + request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_group_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GroupAssetsRequest, dict]): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + warnings.warn("SecurityCenterClient.group_assets is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.GroupAssetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_group_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GroupFindingsRequest, dict]): + The request object. Request message for grouping by + findings. + parent (str): + Required. Name of the source to groupBy. Its format is + ``organizations/[organization_id]/sources/[source_id]``, + ``folders/[folder_id]/sources/[source_id]``, or + ``projects/[project_id]/sources/[source_id]``. To + groupBy across all sources provide a source_id of ``-``. + For example: + ``organizations/{organization_id}/sources/-, folders/{folder_id}/sources/-``, + or ``projects/{project_id}/sources/-`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (str): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported when compare_duration + is set: + + - state_change + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets(self, + request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists an organization's assets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListAssetsRequest, dict]): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsPager: + Response message for listing assets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + warnings.warn("SecurityCenterClient.list_assets is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListAssetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_descendant_security_health_analytics_custom_modules(self, + request: Optional[Union[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, 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.ListDescendantSecurityHealthAnalyticsCustomModulesPager: + r"""Returns a list of all resident + SecurityHealthAnalyticsCustomModules under the given CRM + parent and all of the parent’s CRM descendants. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_descendant_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, dict]): + The request object. Request message for listing + descendant Security Health Analytics + custom modules. + parent (str): + Required. Name of parent to list descendant custom + modules. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + 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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager: + Response message for listing + descendant Security Health Analytics + custom modules. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_descendant_security_health_analytics_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListDescendantSecurityHealthAnalyticsCustomModulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings(self, + request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListFindingsRequest( + parent="parent_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.securitycenter_v1.types.ListFindingsRequest, dict]): + The request object. Request message for listing findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.ListFindingsPager: + Response message for listing + findings. + 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.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_mute_configs(self, + request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsPager: + r"""Lists mute configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_mute_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListMuteConfigsRequest, dict]): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or project. + parent (str): + Required. The parent, which owns the collection of mute + configs. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + + 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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsPager: + Response message for listing mute + configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): + request = securitycenter_service.ListMuteConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_mute_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.ListMuteConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_notification_configs(self, + request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsPager: + r"""Lists notification configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest, dict]): + The request object. Request message for listing + notification configs. + parent (str): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]", + "folders/[folder_id]", or "projects/[project_id]". + + 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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListNotificationConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_effective_security_health_analytics_custom_modules(self, + request: Optional[Union[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, 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.ListEffectiveSecurityHealthAnalyticsCustomModulesPager: + r"""Returns a list of all + EffectiveSecurityHealthAnalyticsCustomModules for the + given parent. This includes resident modules defined at + the scope of the parent, and inherited modules, + inherited from CRM ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_effective_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_security_health_analytics_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, dict]): + The request object. Request message for listing effective + Security Health Analytics custom + modules. + parent (str): + Required. Name of parent to list effective custom + modules. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + 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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager: + Response message for listing + effective Security Health Analytics + custom modules. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_effective_security_health_analytics_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListEffectiveSecurityHealthAnalyticsCustomModulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_security_health_analytics_custom_modules(self, + request: Optional[Union[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, 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.ListSecurityHealthAnalyticsCustomModulesPager: + r"""Returns a list of all + SecurityHealthAnalyticsCustomModules for the given + parent. This includes resident modules defined at the + scope of the parent, and inherited modules, inherited + from CRM ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_health_analytics_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest, dict]): + The request object. Request message for listing Security + Health Analytics custom modules. + parent (str): + Required. Name of parent to list custom modules. Its + format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + 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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesPager: + Response message for listing Security + Health Analytics custom modules. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_security_health_analytics_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListSecurityHealthAnalyticsCustomModulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_sources(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListSourcesRequest, dict]): + The request object. Request message for listing sources. + parent (str): + Required. Resource name of the parent of sources to + list. Its format should be + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + 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.securitycenter_v1.services.security_center.pagers.ListSourcesPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_asset_discovery(self, + request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), + ) -> operation.Operation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS 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 securitycenter_v1 + + def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest, dict]): + The request object. Request message for running asset + discovery for an organization. + parent (str): + Required. Name of the organization to run asset + discovery for. Its format is + ``organizations/[organization_id]``. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` + Response of asset discovery run + + """ + warnings.warn("SecurityCenterClient.run_asset_discovery is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.run_asset_discovery] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + start_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of 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 securitycenter_v1 + + def sample_set_finding_state(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.SetFindingStateRequest, dict]): + The request object. Request message for updating a + finding's state. + name (str): + Required. The `relative resource + name `__ + of the finding. Example: + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, + ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (google.cloud.securitycenter_v1.types.Finding.State): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_mute(self, + request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, + *, + name: Optional[str] = None, + mute: Optional[finding.Finding.Mute] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the mute state of 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 securitycenter_v1 + + def sample_set_mute(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = client.set_mute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.SetMuteRequest, dict]): + The request object. Request message for updating a + finding's mute status. + name (str): + Required. The `relative resource + name `__ + of the finding. Example: + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, + ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute (google.cloud.securitycenter_v1.types.Finding.Mute): + Required. The desired state of the + Mute. + + This corresponds to the ``mute`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, mute]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetMuteRequest): + request = securitycenter_service.SetMuteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if mute is not None: + request.mute = mute + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_mute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # 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 + + def simulate_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_config: Optional[security_health_analytics_custom_config.CustomConfig] = None, + resource: Optional[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: + r"""Simulates a given SecurityHealthAnalyticsCustomModule + and Resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_simulate_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + resource = securitycenter_v1.SimulatedResource() + resource.resource_type = "resource_type_value" + + request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + resource=resource, + ) + + # Make the request + response = client.simulate_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]): + The request object. Request message to simulate a + CustomConfig against a given test + resource. Maximum size of the request is + 4 MB by default. + parent (str): + Required. The relative resource name of the + organization, project, or folder. For more information + about relative resource names, see `Relative Resource + Name `__ + Example: ``organizations/{organization_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_config (google.cloud.securitycenter_v1.types.CustomConfig): + Required. The custom configuration + that you need to test. + + This corresponds to the ``custom_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource): + Required. Resource data to simulate + custom module against. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse: + Response message for simulating a SecurityHealthAnalyticsCustomModule + against a given 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, custom_config, resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_config is not None: + request.custom_config = custom_config + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.simulate_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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_external_system(self, + request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, + *, + external_system: Optional[gcs_external_system.ExternalSystem] = None, + update_mask: 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]] = (), + ) -> gcs_external_system.ExternalSystem: + r"""Updates external system. This is for a given 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 securitycenter_v1 + + def sample_update_external_system(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateExternalSystemRequest( + ) + + # Make the request + response = client.update_external_system(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest, dict]): + The request object. Request message for updating a + ExternalSystem resource. + external_system (google.cloud.securitycenter_v1.types.ExternalSystem): + Required. The external system + resource to update. + + This corresponds to the ``external_system`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the external system resource. + If empty all mutable fields 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.cloud.securitycenter_v1.types.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): + request = securitycenter_service.UpdateExternalSystemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if external_system is not None: + request.external_system = external_system + 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_external_system] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("external_system.name", request.external_system.name), + )), + ) + + # Validate the universe 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_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateFindingRequest, dict]): + The request object. Request message for updating or + creating a finding. + finding (google.cloud.securitycenter_v1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe 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_mute_config(self, + request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, + *, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + update_mask: 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]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Updates a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = client.update_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest, dict]): + The request object. Request message for updating a mute + config. + mute_config (google.cloud.securitycenter_v1.types.MuteConfig): + Required. The mute config being + updated. + + This corresponds to the ``mute_config`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): + request = securitycenter_service.UpdateMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mute_config is not None: + request.mute_config = mute_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_mute_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("mute_config.name", request.mute_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 update_notification_config(self, + request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, + *, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + update_mask: 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest, dict]): + The request object. Request message for updating a + notification config. + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the notification config. + If empty all mutable fields 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.cloud.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_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 update_organization_settings(self, + request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, + *, + organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = client.update_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest, dict]): + The request object. Request message for updating an + organization's settings. + organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_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 update_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, + update_mask: 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]] = (), + ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Updates the SecurityHealthAnalyticsCustomModule under + the given name based on the given update mask. Updating + the enablement state is supported on both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name and custom config of a module is supported + on resident modules only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( + ) + + # Make the request + response = client.update_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]): + The request object. Request message for updating Security + Health Analytics custom modules. + security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): + Required. The SecurityHealthAnalytics + custom module to update. + + This corresponds to the ``security_health_analytics_custom_module`` 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 only fields that + can be updated are ``enablement_state`` and + ``custom_config``. If empty or set to the wildcard value + ``*``, both ``enablement_state`` and ``custom_config`` + are 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.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_health_analytics_custom_module, 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, securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_health_analytics_custom_module is not None: + request.security_health_analytics_custom_module = security_health_analytics_custom_module + 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_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_health_analytics_custom_module.name", request.security_health_analytics_custom_module.name), + )), + ) + + # Validate the universe 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_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v1 + + def sample_update_source(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateSourceRequest, dict]): + The request object. Request message for updating a + source. + source (google.cloud.securitycenter_v1.types.Source): + Required. The source resource to + update. + + This corresponds to the ``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.cloud.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_security_marks(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest, dict]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe 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_big_query_export(self, + request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, + *, + parent: Optional[str] = None, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + big_query_export_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Creates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_create_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = client.create_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest, dict]): + The request object. Request message for creating a + BigQuery export. + parent (str): + Required. The name of the parent resource of the new + BigQuery export. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): + Required. The BigQuery export being + created. + + This corresponds to the ``big_query_export`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``big_query_export_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.cloud.securitycenter_v1.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): + request = securitycenter_service.CreateBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if big_query_export is not None: + request.big_query_export = big_query_export + if big_query_export_id is not None: + request.big_query_export_id = big_query_export_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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_big_query_export(self, + request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + client.delete_big_query_export(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest, dict]): + The request object. Request message for deleting a + BigQuery export. + name (str): + Required. The name of the BigQuery export to delete. Its + format is + ``organizations/{organization}/bigQueryExports/{export_id}``, + ``folders/{folder}/bigQueryExports/{export_id}``, or + ``projects/{project}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): + request = securitycenter_service.DeleteBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + 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_big_query_export(self, + request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, + *, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + update_mask: 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]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Updates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateBigQueryExportRequest( + ) + + # Make the request + response = client.update_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest, dict]): + The request object. Request message for updating a + BigQuery export. + big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): + Required. The BigQuery export being + updated. + + This corresponds to the ``big_query_export`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): + request = securitycenter_service.UpdateBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if big_query_export is not None: + request.big_query_export = big_query_export + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("big_query_export.name", request.big_query_export.name), + )), + ) + + # Validate the universe 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_big_query_exports(self, + request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsPager: + r"""Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are 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 securitycenter_v1 + + def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest, dict]): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or project. + parent (str): + Required. The parent, which owns the collection of + BigQuery exports. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + + 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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsPager: + Response message for listing BigQuery + exports. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): + request = securitycenter_service.ListBigQueryExportsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_big_query_exports] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListBigQueryExportsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Creates a resident Event Threat Detection custom + module at the scope of the given Resource Manager + parent, and also creates inherited custom modules for + all descendants of the given parent. These modules are + enabled by default. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_create_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest, dict]): + The request object. Request to create an Event Threat + Detection custom module. + parent (str): + Required. The new custom module's parent. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): + Required. The module to create. The + event_threat_detection_custom_module.name will be + ignored and server generated. + + This corresponds to the ``event_threat_detection_custom_module`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, event_threat_detection_custom_module]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if event_threat_detection_custom_module is not None: + request.event_threat_detection_custom_module = event_threat_detection_custom_module + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, dict]] = 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 Event Threat Detection custom + module and all of its descendants in the Resource + Manager hierarchy. This method is only supported for + resident custom modules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_delete_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + client.delete_event_threat_detection_custom_module(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest, dict]): + The request object. Request to delete an Event Threat + Detection custom module. + name (str): + Required. Name of the custom module to delete. + + Its format is: + + - "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}". + - "folders/{folder}/eventThreatDetectionSettings/customModules/{module}". + - "projects/{project}/eventThreatDetectionSettings/customModules/{module}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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, securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + 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_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.GetEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Gets an Event Threat Detection custom module. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest, dict]): + The request object. Request to get an Event Threat + Detection custom module. + name (str): + Required. Name of the custom module to get. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_descendant_event_threat_detection_custom_modules(self, + request: Optional[Union[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, 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.ListDescendantEventThreatDetectionCustomModulesPager: + r"""Lists all resident Event Threat Detection custom + modules under the given Resource Manager parent and its + descendants. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_descendant_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest, dict]): + The request object. Request to list current and + descendant resident Event Threat + Detection custom modules. + parent (str): + Required. Name of the parent to list custom modules + under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + 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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesPager: + Response for listing current and + descendant resident Event Threat + Detection custom modules. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_descendant_event_threat_detection_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListDescendantEventThreatDetectionCustomModulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_event_threat_detection_custom_modules(self, + request: Optional[Union[securitycenter_service.ListEventThreatDetectionCustomModulesRequest, 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.ListEventThreatDetectionCustomModulesPager: + r"""Lists all Event Threat Detection custom modules for + the given Resource Manager parent. This includes + resident modules defined at the scope of the parent + along with modules inherited from ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_event_threat_detection_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest, dict]): + The request object. Request to list Event Threat + Detection custom modules. + parent (str): + Required. Name of the parent to list custom modules + under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + 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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesPager: + Response for listing Event Threat + Detection custom modules. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListEventThreatDetectionCustomModulesRequest): + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_event_threat_detection_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListEventThreatDetectionCustomModulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, + update_mask: 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]] = (), + ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Updates the Event Threat Detection custom module with + the given name based on the given update mask. Updating + the enablement state is supported for both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name or configuration of a module is supported + for resident modules only. The type of a module cannot + be changed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( + ) + + # Make the request + response = client.update_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest, dict]): + The request object. Request to update an Event Threat + Detection custom module. + event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): + Required. The module being updated. + This corresponds to the ``event_threat_detection_custom_module`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([event_threat_detection_custom_module, 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, securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if event_threat_detection_custom_module is not None: + request.event_threat_detection_custom_module = event_threat_detection_custom_module + 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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("event_threat_detection_custom_module.name", request.event_threat_detection_custom_module.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def validate_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: + r"""Validates the given Event Threat Detection custom + module. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_validate_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + raw_text="raw_text_value", + type_="type__value", + ) + + # Make the request + response = client.validate_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest, dict]): + The request object. Request to validate an Event Threat + Detection custom module. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse: + Response to validating an Event + Threat Detection custom module. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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_effective_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: + r"""Gets an effective Event Threat Detection custom + module at the given level. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_effective_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_effective_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]): + The request object. Request to get an + EffectiveEventThreatDetectionCustomModule. + name (str): + Required. The resource name of the effective Event + Threat Detection custom module. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule: + An EffectiveEventThreatDetectionCustomModule is the representation of + an Event Threat Detection custom module at a + specified level of the resource hierarchy: + organization, folder, or project. If a custom module + is inherited from a parent organization or folder, + the value of the enablement_state property in + EffectiveEventThreatDetectionCustomModule is set to + the value that is effective in the parent, instead of + INHERITED. For example, if the module is enabled in a + parent organization or folder, the effective + enablement_state for the module in all child folders + or projects is also enabled. + EffectiveEventThreatDetectionCustomModule is + read-only. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_effective_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_effective_event_threat_detection_custom_modules(self, + request: Optional[Union[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, 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.ListEffectiveEventThreatDetectionCustomModulesPager: + r"""Lists all effective Event Threat Detection custom + modules for the given parent. This includes resident + modules defined at the scope of the parent along with + modules inherited from its ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_effective_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_event_threat_detection_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest, dict]): + The request object. Request to list effective Event + Threat Detection custom modules. + parent (str): + Required. Name of the parent to list custom modules for. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + 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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesPager: + Response for listing + EffectiveEventThreatDetectionCustomModules. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_effective_event_threat_detection_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListEffectiveEventThreatDetectionCustomModulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_create_resource_value_configs(self, + request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + requests = securitycenter_v1.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + requests.resource_value_config.resource_value = "NONE" + requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest, dict]): + The request object. Request message to create multiple + resource value configs + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. The parent + field in the + CreateResourceValueConfigRequest + messages must either be empty or match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]): + Required. The resource value configs + to be created. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, requests]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): + request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_resource_value_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, + ) + + # Done; return the response. + return response + + def delete_resource_value_config(self, + request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_resource_value_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest, dict]): + The request object. Request message to delete resource + value config + name (str): + Required. Name of the + ResourceValueConfig 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. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): + request = securitycenter_service.DeleteResourceValueConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_resource_value_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_resource_value_config(self, + request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource_value_config.ResourceValueConfig: + r"""Gets a ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest, dict]): + The request object. Request message to get resource value + config + name (str): + Required. Name of the resource value config to retrieve. + Its format is + ``organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v1.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): + request = securitycenter_service.GetResourceValueConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_resource_value_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_resource_value_configs(self, + request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsPager: + r"""Lists all ResourceValueConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest, dict]): + The request object. Request message to list resource + value configs of a parent + parent (str): + Required. The parent, which owns the collection of + resource value configs. Its format is + ``organizations/[organization_id]`` + + 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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsPager: + Response message to list resource + value configs + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): + request = securitycenter_service.ListResourceValueConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_resource_value_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.ListResourceValueConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_resource_value_config(self, + request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, + *, + resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, + update_mask: 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]] = (), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Updates an existing ResourceValueConfigs with new + rules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + resource_value_config = securitycenter_v1.ResourceValueConfig() + resource_value_config.resource_value = "NONE" + resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.UpdateResourceValueConfigRequest( + resource_value_config=resource_value_config, + ) + + # Make the request + response = client.update_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest, dict]): + The request object. Request message to update resource + value config + resource_value_config (google.cloud.securitycenter_v1.types.ResourceValueConfig): + Required. The resource value config + being updated. + + This corresponds to the ``resource_value_config`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): + request = securitycenter_service.UpdateResourceValueConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if resource_value_config is not None: + request.resource_value_config = resource_value_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_resource_value_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource_value_config.name", request.resource_value_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 list_valued_resources(self, + request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesPager: + r"""Lists the valued resources for a set of simulation + results and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_valued_resources(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListValuedResourcesRequest, dict]): + The request object. Request message for listing the + valued resources for a given simulation. + parent (str): + Required. Name of parent to list valued resources. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + + 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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesPager: + Response message for listing the + valued resources for a given simulation. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): + request = securitycenter_service.ListValuedResourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_valued_resources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListValuedResourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_attack_paths(self, + request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsPager: + r"""Lists the attack paths for a set of simulation + results or valued resources and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_attack_paths(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListAttackPathsRequest, dict]): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + parent (str): + Required. Name of parent to list attack paths. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + + 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.securitycenter_v1.services.security_center.pagers.ListAttackPathsPager: + Response message for listing the + attack paths for a given simulation or + valued resource. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): + request = securitycenter_service.ListAttackPathsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_attack_paths] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListAttackPathsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SecurityCenterClient": + 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 = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + 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 = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SecurityCenterClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py new file mode 100644 index 000000000000..6fb1704f990d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py @@ -0,0 +1,2333 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.securitycenter_v1.types import attack_path +from google.cloud.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import valued_resource + + +class GroupAssetsPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupAssetsResponse], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + 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[securitycenter_service.GroupAssetsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupAssetsAsyncPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` + attributes are available on the 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[securitycenter_service.GroupAssetsResponse]], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + 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[securitycenter_service.GroupAssetsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` + attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListAssetsResponse], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + 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[securitycenter_service.ListAssetsResponse]: + 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + for page in self.pages: + yield from page.list_assets_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` + attributes are available on the 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[securitycenter_service.ListAssetsResponse]], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + 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[securitycenter_service.ListAssetsResponse]: + 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_assets_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDescendantSecurityHealthAnalyticsCustomModulesPager: + """A pager for iterating through ``list_descendant_security_health_analytics_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``security_health_analytics_custom_modules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDescendantSecurityHealthAnalyticsCustomModules`` requests and continue to iterate + through the ``security_health_analytics_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse], + request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, + response: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse): + 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 = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) + 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[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: + 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + for page in self.pages: + yield from page.security_health_analytics_custom_modules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: + """A pager for iterating through ``list_descendant_security_health_analytics_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``security_health_analytics_custom_modules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDescendantSecurityHealthAnalyticsCustomModules`` requests and continue to iterate + through the ``security_health_analytics_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` + attributes are available on the 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[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]], + request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, + response: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse): + 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 = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) + 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[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: + 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + async def async_generator(): + async for page in self.pages: + for response in page.security_health_analytics_custom_modules: + 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.securitycenter_v1.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_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[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + for page in self.pages: + yield from page.list_findings_results + + 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.securitycenter_v1.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_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[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_findings_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMuteConfigsPager: + """A pager for iterating through ``list_mute_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``mute_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMuteConfigs`` requests and continue to iterate + through the ``mute_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListMuteConfigsResponse], + request: securitycenter_service.ListMuteConfigsRequest, + response: securitycenter_service.ListMuteConfigsResponse, + *, + 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.securitycenter_v1.types.ListMuteConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListMuteConfigsResponse): + 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 = securitycenter_service.ListMuteConfigsRequest(request) + 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[securitycenter_service.ListMuteConfigsResponse]: + 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[mute_config.MuteConfig]: + for page in self.pages: + yield from page.mute_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMuteConfigsAsyncPager: + """A pager for iterating through ``list_mute_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``mute_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMuteConfigs`` requests and continue to iterate + through the ``mute_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` + attributes are available on the 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[securitycenter_service.ListMuteConfigsResponse]], + request: securitycenter_service.ListMuteConfigsRequest, + response: securitycenter_service.ListMuteConfigsResponse, + *, + 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.securitycenter_v1.types.ListMuteConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListMuteConfigsResponse): + 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 = securitycenter_service.ListMuteConfigsRequest(request) + 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[securitycenter_service.ListMuteConfigsResponse]: + 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[mute_config.MuteConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.mute_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v1.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + 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[securitycenter_service.ListNotificationConfigsResponse]: + 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[notification_config.NotificationConfig]: + for page in self.pages: + yield from page.notification_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsAsyncPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` + attributes are available on the 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[securitycenter_service.ListNotificationConfigsResponse]], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v1.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + 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[securitycenter_service.ListNotificationConfigsResponse]: + 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[notification_config.NotificationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.notification_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEffectiveSecurityHealthAnalyticsCustomModulesPager: + """A pager for iterating through ``list_effective_security_health_analytics_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``effective_security_health_analytics_custom_modules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEffectiveSecurityHealthAnalyticsCustomModules`` requests and continue to iterate + through the ``effective_security_health_analytics_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse], + request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, + response: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse): + 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 = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) + 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[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: + 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[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: + for page in self.pages: + yield from page.effective_security_health_analytics_custom_modules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: + """A pager for iterating through ``list_effective_security_health_analytics_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``effective_security_health_analytics_custom_modules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEffectiveSecurityHealthAnalyticsCustomModules`` requests and continue to iterate + through the ``effective_security_health_analytics_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` + attributes are available on the 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[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]], + request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, + response: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse): + 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 = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) + 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[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: + 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[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: + async def async_generator(): + async for page in self.pages: + for response in page.effective_security_health_analytics_custom_modules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSecurityHealthAnalyticsCustomModulesPager: + """A pager for iterating through ``list_security_health_analytics_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``security_health_analytics_custom_modules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSecurityHealthAnalyticsCustomModules`` requests and continue to iterate + through the ``security_health_analytics_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse], + request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, + response: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse): + 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 = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) + 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[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: + 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + for page in self.pages: + yield from page.security_health_analytics_custom_modules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSecurityHealthAnalyticsCustomModulesAsyncPager: + """A pager for iterating through ``list_security_health_analytics_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``security_health_analytics_custom_modules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSecurityHealthAnalyticsCustomModules`` requests and continue to iterate + through the ``security_health_analytics_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` + attributes are available on the 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[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]], + request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, + response: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse): + 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 = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) + 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[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: + 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + async def async_generator(): + async for page in self.pages: + for response in page.security_health_analytics_custom_modules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` + attributes are available on the 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[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.sources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBigQueryExportsPager: + """A pager for iterating through ``list_big_query_exports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``big_query_exports`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBigQueryExports`` requests and continue to iterate + through the ``big_query_exports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListBigQueryExportsResponse], + request: securitycenter_service.ListBigQueryExportsRequest, + response: securitycenter_service.ListBigQueryExportsResponse, + *, + 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.securitycenter_v1.types.ListBigQueryExportsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse): + 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 = securitycenter_service.ListBigQueryExportsRequest(request) + 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[securitycenter_service.ListBigQueryExportsResponse]: + 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[bigquery_export.BigQueryExport]: + for page in self.pages: + yield from page.big_query_exports + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBigQueryExportsAsyncPager: + """A pager for iterating through ``list_big_query_exports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``big_query_exports`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBigQueryExports`` requests and continue to iterate + through the ``big_query_exports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` + attributes are available on the 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[securitycenter_service.ListBigQueryExportsResponse]], + request: securitycenter_service.ListBigQueryExportsRequest, + response: securitycenter_service.ListBigQueryExportsResponse, + *, + 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.securitycenter_v1.types.ListBigQueryExportsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse): + 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 = securitycenter_service.ListBigQueryExportsRequest(request) + 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[securitycenter_service.ListBigQueryExportsResponse]: + 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[bigquery_export.BigQueryExport]: + async def async_generator(): + async for page in self.pages: + for response in page.big_query_exports: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDescendantEventThreatDetectionCustomModulesPager: + """A pager for iterating through ``list_descendant_event_threat_detection_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``event_threat_detection_custom_modules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDescendantEventThreatDetectionCustomModules`` requests and continue to iterate + through the ``event_threat_detection_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse], + request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, + response: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse): + 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 = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) + 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[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: + 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + for page in self.pages: + yield from page.event_threat_detection_custom_modules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDescendantEventThreatDetectionCustomModulesAsyncPager: + """A pager for iterating through ``list_descendant_event_threat_detection_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``event_threat_detection_custom_modules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDescendantEventThreatDetectionCustomModules`` requests and continue to iterate + through the ``event_threat_detection_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` + attributes are available on the 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[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]], + request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, + response: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse): + 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 = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) + 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[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: + 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + async def async_generator(): + async for page in self.pages: + for response in page.event_threat_detection_custom_modules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEventThreatDetectionCustomModulesPager: + """A pager for iterating through ``list_event_threat_detection_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``event_threat_detection_custom_modules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEventThreatDetectionCustomModules`` requests and continue to iterate + through the ``event_threat_detection_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListEventThreatDetectionCustomModulesResponse], + request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, + response: securitycenter_service.ListEventThreatDetectionCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse): + 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 = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) + 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[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: + 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + for page in self.pages: + yield from page.event_threat_detection_custom_modules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEventThreatDetectionCustomModulesAsyncPager: + """A pager for iterating through ``list_event_threat_detection_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``event_threat_detection_custom_modules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEventThreatDetectionCustomModules`` requests and continue to iterate + through the ``event_threat_detection_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` + attributes are available on the 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[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]], + request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, + response: securitycenter_service.ListEventThreatDetectionCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse): + 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 = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) + 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[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: + 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + async def async_generator(): + async for page in self.pages: + for response in page.event_threat_detection_custom_modules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEffectiveEventThreatDetectionCustomModulesPager: + """A pager for iterating through ``list_effective_event_threat_detection_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``effective_event_threat_detection_custom_modules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEffectiveEventThreatDetectionCustomModules`` requests and continue to iterate + through the ``effective_event_threat_detection_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse], + request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, + response: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse): + 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 = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) + 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[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: + 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[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: + for page in self.pages: + yield from page.effective_event_threat_detection_custom_modules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEffectiveEventThreatDetectionCustomModulesAsyncPager: + """A pager for iterating through ``list_effective_event_threat_detection_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``effective_event_threat_detection_custom_modules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEffectiveEventThreatDetectionCustomModules`` requests and continue to iterate + through the ``effective_event_threat_detection_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` + attributes are available on the 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[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]], + request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, + response: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse): + 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 = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) + 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[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: + 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[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: + async def async_generator(): + async for page in self.pages: + for response in page.effective_event_threat_detection_custom_modules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourceValueConfigsPager: + """A pager for iterating through ``list_resource_value_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resource_value_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListResourceValueConfigs`` requests and continue to iterate + through the ``resource_value_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListResourceValueConfigsResponse], + request: securitycenter_service.ListResourceValueConfigsRequest, + response: securitycenter_service.ListResourceValueConfigsResponse, + *, + 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.securitycenter_v1.types.ListResourceValueConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse): + 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 = securitycenter_service.ListResourceValueConfigsRequest(request) + 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[securitycenter_service.ListResourceValueConfigsResponse]: + 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[resource_value_config.ResourceValueConfig]: + for page in self.pages: + yield from page.resource_value_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourceValueConfigsAsyncPager: + """A pager for iterating through ``list_resource_value_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resource_value_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListResourceValueConfigs`` requests and continue to iterate + through the ``resource_value_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` + attributes are available on the 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[securitycenter_service.ListResourceValueConfigsResponse]], + request: securitycenter_service.ListResourceValueConfigsRequest, + response: securitycenter_service.ListResourceValueConfigsResponse, + *, + 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.securitycenter_v1.types.ListResourceValueConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse): + 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 = securitycenter_service.ListResourceValueConfigsRequest(request) + 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[securitycenter_service.ListResourceValueConfigsResponse]: + 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[resource_value_config.ResourceValueConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.resource_value_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListValuedResourcesPager: + """A pager for iterating through ``list_valued_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``valued_resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListValuedResources`` requests and continue to iterate + through the ``valued_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListValuedResourcesResponse], + request: securitycenter_service.ListValuedResourcesRequest, + response: securitycenter_service.ListValuedResourcesResponse, + *, + 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.securitycenter_v1.types.ListValuedResourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListValuedResourcesResponse): + 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 = securitycenter_service.ListValuedResourcesRequest(request) + 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[securitycenter_service.ListValuedResourcesResponse]: + 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[valued_resource.ValuedResource]: + for page in self.pages: + yield from page.valued_resources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListValuedResourcesAsyncPager: + """A pager for iterating through ``list_valued_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``valued_resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListValuedResources`` requests and continue to iterate + through the ``valued_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` + attributes are available on the 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[securitycenter_service.ListValuedResourcesResponse]], + request: securitycenter_service.ListValuedResourcesRequest, + response: securitycenter_service.ListValuedResourcesResponse, + *, + 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.securitycenter_v1.types.ListValuedResourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListValuedResourcesResponse): + 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 = securitycenter_service.ListValuedResourcesRequest(request) + 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[securitycenter_service.ListValuedResourcesResponse]: + 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[valued_resource.ValuedResource]: + async def async_generator(): + async for page in self.pages: + for response in page.valued_resources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAttackPathsPager: + """A pager for iterating through ``list_attack_paths`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``attack_paths`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAttackPaths`` requests and continue to iterate + through the ``attack_paths`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListAttackPathsResponse], + request: securitycenter_service.ListAttackPathsRequest, + response: securitycenter_service.ListAttackPathsResponse, + *, + 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.securitycenter_v1.types.ListAttackPathsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListAttackPathsResponse): + 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 = securitycenter_service.ListAttackPathsRequest(request) + 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[securitycenter_service.ListAttackPathsResponse]: + 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[attack_path.AttackPath]: + for page in self.pages: + yield from page.attack_paths + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAttackPathsAsyncPager: + """A pager for iterating through ``list_attack_paths`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``attack_paths`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAttackPaths`` requests and continue to iterate + through the ``attack_paths`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` + attributes are available on the 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[securitycenter_service.ListAttackPathsResponse]], + request: securitycenter_service.ListAttackPathsRequest, + response: securitycenter_service.ListAttackPathsResponse, + *, + 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.securitycenter_v1.types.ListAttackPathsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListAttackPathsResponse): + 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 = securitycenter_service.ListAttackPathsRequest(request) + 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[securitycenter_service.ListAttackPathsResponse]: + 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[attack_path.AttackPath]: + async def async_generator(): + async for page in self.pages: + for response in page.attack_paths: + 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-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py new file mode 100644 index 000000000000..9d36139c1a9b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/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 SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .rest import SecurityCenterRestTransport +from .rest import SecurityCenterRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry['grpc'] = SecurityCenterGrpcTransport +_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport +_transport_registry['rest'] = SecurityCenterRestTransport + +__all__ = ( + 'SecurityCenterTransport', + 'SecurityCenterGrpcTransport', + 'SecurityCenterGrpcAsyncIOTransport', + 'SecurityCenterRestTransport', + 'SecurityCenterRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py new file mode 100644 index 000000000000..0e98676ba56d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py @@ -0,0 +1,1251 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.securitycenter_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.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import valued_resource +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 empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'securitycenter.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.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: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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.bulk_mute_findings: gapic_v1.method.wrap_method( + self.bulk_mute_findings, + default_timeout=None, + client_info=client_info, + ), + self.create_security_health_analytics_custom_module: gapic_v1.method.wrap_method( + self.create_security_health_analytics_custom_module, + default_timeout=60.0, + client_info=client_info, + ), + self.create_source: gapic_v1.method.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.create_mute_config: gapic_v1.method.wrap_method( + self.create_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method.wrap_method( + self.create_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_mute_config: gapic_v1.method.wrap_method( + self.delete_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method.wrap_method( + self.delete_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_security_health_analytics_custom_module: gapic_v1.method.wrap_method( + self.delete_security_health_analytics_custom_module, + default_timeout=60.0, + client_info=client_info, + ), + self.get_simulation: gapic_v1.method.wrap_method( + self.get_simulation, + default_timeout=None, + client_info=client_info, + ), + self.get_valued_resource: gapic_v1.method.wrap_method( + self.get_valued_resource, + default_timeout=None, + client_info=client_info, + ), + self.get_big_query_export: gapic_v1.method.wrap_method( + self.get_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_mute_config: gapic_v1.method.wrap_method( + self.get_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.get_notification_config: gapic_v1.method.wrap_method( + self.get_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_settings: gapic_v1.method.wrap_method( + self.get_organization_settings, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_effective_security_health_analytics_custom_module: gapic_v1.method.wrap_method( + self.get_effective_security_health_analytics_custom_module, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_security_health_analytics_custom_module: gapic_v1.method.wrap_method( + self.get_security_health_analytics_custom_module, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_source: gapic_v1.method.wrap_method( + self.get_source, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.group_assets: gapic_v1.method.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_descendant_security_health_analytics_custom_modules: gapic_v1.method.wrap_method( + self.list_descendant_security_health_analytics_custom_modules, + 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=60.0, + ), + default_timeout=60.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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_mute_configs: gapic_v1.method.wrap_method( + self.list_mute_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method.wrap_method( + self.list_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_effective_security_health_analytics_custom_modules: gapic_v1.method.wrap_method( + self.list_effective_security_health_analytics_custom_modules, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_security_health_analytics_custom_modules: gapic_v1.method.wrap_method( + self.list_security_health_analytics_custom_modules, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_sources: gapic_v1.method.wrap_method( + self.list_sources, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.run_asset_discovery: gapic_v1.method.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_mute: gapic_v1.method.wrap_method( + self.set_mute, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.simulate_security_health_analytics_custom_module: gapic_v1.method.wrap_method( + self.simulate_security_health_analytics_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.update_external_system: gapic_v1.method.wrap_method( + self.update_external_system, + default_timeout=None, + client_info=client_info, + ), + self.update_finding: gapic_v1.method.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_mute_config: gapic_v1.method.wrap_method( + self.update_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method.wrap_method( + self.update_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_health_analytics_custom_module: gapic_v1.method.wrap_method( + self.update_security_health_analytics_custom_module, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=client_info, + ), + self.create_big_query_export: gapic_v1.method.wrap_method( + self.create_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.delete_big_query_export: gapic_v1.method.wrap_method( + self.delete_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.update_big_query_export: gapic_v1.method.wrap_method( + self.update_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.list_big_query_exports: gapic_v1.method.wrap_method( + self.list_big_query_exports, + default_timeout=None, + client_info=client_info, + ), + self.create_event_threat_detection_custom_module: gapic_v1.method.wrap_method( + self.create_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.delete_event_threat_detection_custom_module: gapic_v1.method.wrap_method( + self.delete_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.get_event_threat_detection_custom_module: gapic_v1.method.wrap_method( + self.get_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.list_descendant_event_threat_detection_custom_modules: gapic_v1.method.wrap_method( + self.list_descendant_event_threat_detection_custom_modules, + default_timeout=None, + client_info=client_info, + ), + self.list_event_threat_detection_custom_modules: gapic_v1.method.wrap_method( + self.list_event_threat_detection_custom_modules, + default_timeout=None, + client_info=client_info, + ), + self.update_event_threat_detection_custom_module: gapic_v1.method.wrap_method( + self.update_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.validate_event_threat_detection_custom_module: gapic_v1.method.wrap_method( + self.validate_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.get_effective_event_threat_detection_custom_module: gapic_v1.method.wrap_method( + self.get_effective_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.list_effective_event_threat_detection_custom_modules: gapic_v1.method.wrap_method( + self.list_effective_event_threat_detection_custom_modules, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_resource_value_configs: gapic_v1.method.wrap_method( + self.batch_create_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.delete_resource_value_config: gapic_v1.method.wrap_method( + self.delete_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_resource_value_config: gapic_v1.method.wrap_method( + self.get_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.list_resource_value_configs: gapic_v1.method.wrap_method( + self.list_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_resource_value_config: gapic_v1.method.wrap_method( + self.update_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.list_valued_resources: gapic_v1.method.wrap_method( + self.list_valued_resources, + default_timeout=None, + client_info=client_info, + ), + self.list_attack_paths: gapic_v1.method.wrap_method( + self.list_attack_paths, + 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 bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], + Union[ + gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] + ]]: + raise NotImplementedError() + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + Union[ + gcs_mute_config.MuteConfig, + Awaitable[gcs_mute_config.MuteConfig] + ]]: + raise NotImplementedError() + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def delete_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + Union[ + simulation.Simulation, + Awaitable[simulation.Simulation] + ]]: + raise NotImplementedError() + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + Union[ + valued_resource.ValuedResource, + Awaitable[valued_resource.ValuedResource] + ]]: + raise NotImplementedError() + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, + Awaitable[bigquery_export.BigQueryExport] + ]]: + 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 get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + Union[ + mute_config.MuteConfig, + Awaitable[mute_config.MuteConfig] + ]]: + raise NotImplementedError() + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Union[ + notification_config.NotificationConfig, + Awaitable[notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Union[ + organization_settings.OrganizationSettings, + Awaitable[organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def get_effective_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], + Union[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule, + Awaitable[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule] + ]]: + raise NotImplementedError() + + @property + def get_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], + Union[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + Awaitable[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] + ]]: + raise NotImplementedError() + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Union[ + source.Source, + Awaitable[source.Source] + ]]: + raise NotImplementedError() + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Union[ + securitycenter_service.GroupAssetsResponse, + Awaitable[securitycenter_service.GroupAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Union[ + securitycenter_service.GroupFindingsResponse, + Awaitable[securitycenter_service.GroupFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Union[ + securitycenter_service.ListAssetsResponse, + Awaitable[securitycenter_service.ListAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], + Union[ + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse, + Awaitable[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Union[ + securitycenter_service.ListFindingsResponse, + Awaitable[securitycenter_service.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + Union[ + securitycenter_service.ListMuteConfigsResponse, + Awaitable[securitycenter_service.ListMuteConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Union[ + securitycenter_service.ListNotificationConfigsResponse, + Awaitable[securitycenter_service.ListNotificationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_effective_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], + Union[ + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, + Awaitable[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse] + ]]: + raise NotImplementedError() + + @property + def list_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], + Union[ + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse, + Awaitable[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse] + ]]: + raise NotImplementedError() + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Union[ + securitycenter_service.ListSourcesResponse, + Awaitable[securitycenter_service.ListSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + raise NotImplementedError() + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + 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 test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + @property + def simulate_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], + Union[ + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse, + Awaitable[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse] + ]]: + raise NotImplementedError() + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + Union[ + gcs_external_system.ExternalSystem, + Awaitable[gcs_external_system.ExternalSystem] + ]]: + raise NotImplementedError() + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + Union[ + gcs_mute_config.MuteConfig, + Awaitable[gcs_mute_config.MuteConfig] + ]]: + raise NotImplementedError() + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Union[ + gcs_organization_settings.OrganizationSettings, + Awaitable[gcs_organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def update_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], + Union[ + gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] + ]]: + raise NotImplementedError() + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Union[ + gcs_security_marks.SecurityMarks, + Awaitable[gcs_security_marks.SecurityMarks] + ]]: + raise NotImplementedError() + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, + Awaitable[bigquery_export.BigQueryExport] + ]]: + raise NotImplementedError() + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, + Awaitable[bigquery_export.BigQueryExport] + ]]: + raise NotImplementedError() + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + Union[ + securitycenter_service.ListBigQueryExportsResponse, + Awaitable[securitycenter_service.ListBigQueryExportsResponse] + ]]: + raise NotImplementedError() + + @property + def create_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], + Union[ + gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, + Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] + ]]: + raise NotImplementedError() + + @property + def delete_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], + Union[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule, + Awaitable[event_threat_detection_custom_module.EventThreatDetectionCustomModule] + ]]: + raise NotImplementedError() + + @property + def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], + Union[ + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse, + Awaitable[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse] + ]]: + raise NotImplementedError() + + @property + def list_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], + Union[ + securitycenter_service.ListEventThreatDetectionCustomModulesResponse, + Awaitable[securitycenter_service.ListEventThreatDetectionCustomModulesResponse] + ]]: + raise NotImplementedError() + + @property + def update_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], + Union[ + gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, + Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] + ]]: + raise NotImplementedError() + + @property + def validate_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], + Union[ + securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse, + Awaitable[securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse] + ]]: + raise NotImplementedError() + + @property + def get_effective_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], + Union[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule, + Awaitable[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule] + ]]: + raise NotImplementedError() + + @property + def list_effective_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], + Union[ + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse, + Awaitable[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse] + ]]: + raise NotImplementedError() + + @property + def batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + Union[ + securitycenter_service.BatchCreateResourceValueConfigsResponse, + Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + Union[ + resource_value_config.ResourceValueConfig, + Awaitable[resource_value_config.ResourceValueConfig] + ]]: + raise NotImplementedError() + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + Union[ + securitycenter_service.ListResourceValueConfigsResponse, + Awaitable[securitycenter_service.ListResourceValueConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + Union[ + gcs_resource_value_config.ResourceValueConfig, + Awaitable[gcs_resource_value_config.ResourceValueConfig] + ]]: + raise NotImplementedError() + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + Union[ + securitycenter_service.ListValuedResourcesResponse, + Awaitable[securitycenter_service.ListValuedResourcesResponse] + ]]: + raise NotImplementedError() + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + Union[ + securitycenter_service.ListAttackPathsResponse, + Awaitable[securitycenter_service.ListAttackPathsResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SecurityCenterTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py new file mode 100644 index 000000000000..a8d1ee71ce17 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py @@ -0,0 +1,2103 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import valued_resource +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 empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V1 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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 bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + operations_pb2.Operation]: + r"""Return a callable for the bulk mute findings method over gRPC. + + Kicks off an LRO to bulk mute findings for a parent + based on a filter. The parent can be either an + organization, folder or project. The findings matched by + the filter will be muted after the LRO is done. + + Returns: + Callable[[~.BulkMuteFindingsRequest], + ~.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 'bulk_mute_findings' not in self._stubs: + self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/BulkMuteFindings', + request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['bulk_mute_findings'] + + @property + def create_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], + gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + r"""Return a callable for the create security health + analytics custom module method over gRPC. + + Creates a resident + SecurityHealthAnalyticsCustomModule at the scope of the + given CRM parent, and also creates inherited + SecurityHealthAnalyticsCustomModules for all CRM + descendants of the given parent. These modules are + enabled by default. + + Returns: + Callable[[~.CreateSecurityHealthAnalyticsCustomModuleRequest], + ~.SecurityHealthAnalyticsCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: + self._stubs['create_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['create_security_health_analytics_custom_module'] + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + r"""Return a callable for the create mute config method over gRPC. + + Creates a mute config. + + Returns: + Callable[[~.CreateMuteConfigRequest], + ~.MuteConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateMuteConfig', + request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['create_mute_config'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete mute config method over gRPC. + + Deletes an existing mute config. + + Returns: + Callable[[~.DeleteMuteConfigRequest], + ~.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_mute_config' not in self._stubs: + self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteMuteConfig', + request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_mute_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + ~.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_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @property + def delete_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete security health + analytics custom module method over gRPC. + + Deletes the specified + SecurityHealthAnalyticsCustomModule and all of its + descendants in the CRM hierarchy. This method is only + supported for resident custom modules. + + Returns: + Callable[[~.DeleteSecurityHealthAnalyticsCustomModuleRequest], + ~.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_security_health_analytics_custom_module' not in self._stubs: + self._stubs['delete_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_security_health_analytics_custom_module'] + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + simulation.Simulation]: + r"""Return a callable for the get simulation method over gRPC. + + Get the simulation by name or the latest simulation + for the given organization. + + Returns: + Callable[[~.GetSimulationRequest], + ~.Simulation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_simulation' not in self._stubs: + self._stubs['get_simulation'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSimulation', + request_serializer=securitycenter_service.GetSimulationRequest.serialize, + response_deserializer=simulation.Simulation.deserialize, + ) + return self._stubs['get_simulation'] + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + valued_resource.ValuedResource]: + r"""Return a callable for the get valued resource method over gRPC. + + Get the valued resource by name + + Returns: + Callable[[~.GetValuedResourceRequest], + ~.ValuedResource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_valued_resource' not in self._stubs: + self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetValuedResource', + request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, + response_deserializer=valued_resource.ValuedResource.deserialize, + ) + return self._stubs['get_valued_resource'] + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + bigquery_export.BigQueryExport]: + r"""Return a callable for the get big query export method over gRPC. + + Gets a BigQuery export. + + Returns: + Callable[[~.GetBigQueryExportRequest], + ~.BigQueryExport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_big_query_export' not in self._stubs: + self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetBigQueryExport', + request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['get_big_query_export'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + mute_config.MuteConfig]: + r"""Return a callable for the get mute config method over gRPC. + + Gets a mute config. + + Returns: + Callable[[~.GetMuteConfigRequest], + ~.MuteConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_mute_config' not in self._stubs: + self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetMuteConfig', + request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, + response_deserializer=mute_config.MuteConfig.deserialize, + ) + return self._stubs['get_mute_config'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_effective_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: + r"""Return a callable for the get effective security health + analytics custom module method over gRPC. + + Retrieves an + EffectiveSecurityHealthAnalyticsCustomModule. + + Returns: + Callable[[~.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], + ~.EffectiveSecurityHealthAnalyticsCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_effective_security_health_analytics_custom_module' not in self._stubs: + self._stubs['get_effective_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['get_effective_security_health_analytics_custom_module'] + + @property + def get_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + r"""Return a callable for the get security health analytics + custom module method over gRPC. + + Retrieves a SecurityHealthAnalyticsCustomModule. + + Returns: + Callable[[~.GetSecurityHealthAnalyticsCustomModuleRequest], + ~.SecurityHealthAnalyticsCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_security_health_analytics_custom_module' not in self._stubs: + self._stubs['get_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['get_security_health_analytics_custom_module'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + ~.GroupAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: + r"""Return a callable for the list descendant security + health analytics custom modules method over gRPC. + + Returns a list of all resident + SecurityHealthAnalyticsCustomModules under the given CRM + parent and all of the parent’s CRM descendants. + + Returns: + Callable[[~.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], + ~.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_descendant_security_health_analytics_custom_modules' not in self._stubs: + self._stubs['list_descendant_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantSecurityHealthAnalyticsCustomModules', + request_serializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.deserialize, + ) + return self._stubs['list_descendant_security_health_analytics_custom_modules'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + 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.securitycenter.v1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + securitycenter_service.ListMuteConfigsResponse]: + r"""Return a callable for the list mute configs method over gRPC. + + Lists mute configs. + + Returns: + Callable[[~.ListMuteConfigsRequest], + ~.ListMuteConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_mute_configs' not in self._stubs: + self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListMuteConfigs', + request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, + ) + return self._stubs['list_mute_configs'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + ~.ListNotificationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_effective_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: + r"""Return a callable for the list effective security health + analytics custom modules method over gRPC. + + Returns a list of all + EffectiveSecurityHealthAnalyticsCustomModules for the + given parent. This includes resident modules defined at + the scope of the parent, and inherited modules, + inherited from CRM ancestors. + + Returns: + Callable[[~.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], + ~.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_effective_security_health_analytics_custom_modules' not in self._stubs: + self._stubs['list_effective_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveSecurityHealthAnalyticsCustomModules', + request_serializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.deserialize, + ) + return self._stubs['list_effective_security_health_analytics_custom_modules'] + + @property + def list_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: + r"""Return a callable for the list security health analytics + custom modules method over gRPC. + + Returns a list of all + SecurityHealthAnalyticsCustomModules for the given + parent. This includes resident modules defined at the + scope of the parent, and inherited modules, inherited + from CRM ancestors. + + Returns: + Callable[[~.ListSecurityHealthAnalyticsCustomModulesRequest], + ~.ListSecurityHealthAnalyticsCustomModulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_security_health_analytics_custom_modules' not in self._stubs: + self._stubs['list_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListSecurityHealthAnalyticsCustomModules', + request_serializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.deserialize, + ) + return self._stubs['list_security_health_analytics_custom_modules'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + operations_pb2.Operation]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + ~.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 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + ~.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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + finding.Finding]: + r"""Return a callable for the set mute method over gRPC. + + Updates the mute state of a finding. + + Returns: + Callable[[~.SetMuteRequest], + ~.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 'set_mute' not in self._stubs: + self._stubs['set_mute'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SetMute', + request_serializer=securitycenter_service.SetMuteRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_mute'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def simulate_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse]: + r"""Return a callable for the simulate security health + analytics custom module method over gRPC. + + Simulates a given SecurityHealthAnalyticsCustomModule + and Resource. + + Returns: + Callable[[~.SimulateSecurityHealthAnalyticsCustomModuleRequest], + ~.SimulateSecurityHealthAnalyticsCustomModuleResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'simulate_security_health_analytics_custom_module' not in self._stubs: + self._stubs['simulate_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SimulateSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.deserialize, + ) + return self._stubs['simulate_security_health_analytics_custom_module'] + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + gcs_external_system.ExternalSystem]: + r"""Return a callable for the update external system method over gRPC. + + Updates external system. This is for a given finding. + + Returns: + Callable[[~.UpdateExternalSystemRequest], + ~.ExternalSystem]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_external_system' not in self._stubs: + self._stubs['update_external_system'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateExternalSystem', + request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, + response_deserializer=gcs_external_system.ExternalSystem.deserialize, + ) + return self._stubs['update_external_system'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + r"""Return a callable for the update mute config method over gRPC. + + Updates a mute config. + + Returns: + Callable[[~.UpdateMuteConfigRequest], + ~.MuteConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateMuteConfig', + request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['update_mute_config'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], + gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + r"""Return a callable for the update security health + analytics custom module method over gRPC. + + Updates the SecurityHealthAnalyticsCustomModule under + the given name based on the given update mask. Updating + the enablement state is supported on both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name and custom config of a module is supported + on resident modules only. + + Returns: + Callable[[~.UpdateSecurityHealthAnalyticsCustomModuleRequest], + ~.SecurityHealthAnalyticsCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: + self._stubs['update_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['update_security_health_analytics_custom_module'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + r"""Return a callable for the create big query export method over gRPC. + + Creates a BigQuery export. + + Returns: + Callable[[~.CreateBigQueryExportRequest], + ~.BigQueryExport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateBigQueryExport', + request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['create_big_query_export'] + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete big query export method over gRPC. + + Deletes an existing BigQuery export. + + Returns: + Callable[[~.DeleteBigQueryExportRequest], + ~.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_big_query_export' not in self._stubs: + self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteBigQueryExport', + request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_big_query_export'] + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + r"""Return a callable for the update big query export method over gRPC. + + Updates a BigQuery export. + + Returns: + Callable[[~.UpdateBigQueryExportRequest], + ~.BigQueryExport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateBigQueryExport', + request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['update_big_query_export'] + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + securitycenter_service.ListBigQueryExportsResponse]: + r"""Return a callable for the list big query exports method over gRPC. + + Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are returned. + + Returns: + Callable[[~.ListBigQueryExportsRequest], + ~.ListBigQueryExportsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_big_query_exports' not in self._stubs: + self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListBigQueryExports', + request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, + response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, + ) + return self._stubs['list_big_query_exports'] + + @property + def create_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], + gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + r"""Return a callable for the create event threat detection + custom module method over gRPC. + + Creates a resident Event Threat Detection custom + module at the scope of the given Resource Manager + parent, and also creates inherited custom modules for + all descendants of the given parent. These modules are + enabled by default. + + Returns: + Callable[[~.CreateEventThreatDetectionCustomModuleRequest], + ~.EventThreatDetectionCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['create_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['create_event_threat_detection_custom_module'] + + @property + def delete_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete event threat detection + custom module method over gRPC. + + Deletes the specified Event Threat Detection custom + module and all of its descendants in the Resource + Manager hierarchy. This method is only supported for + resident custom modules. + + Returns: + Callable[[~.DeleteEventThreatDetectionCustomModuleRequest], + ~.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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['delete_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_event_threat_detection_custom_module'] + + @property + def get_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], + event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + r"""Return a callable for the get event threat detection + custom module method over gRPC. + + Gets an Event Threat Detection custom module. + + Returns: + Callable[[~.GetEventThreatDetectionCustomModuleRequest], + ~.EventThreatDetectionCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_event_threat_detection_custom_module' not in self._stubs: + self._stubs['get_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.GetEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['get_event_threat_detection_custom_module'] + + @property + def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: + r"""Return a callable for the list descendant event threat + detection custom modules method over gRPC. + + Lists all resident Event Threat Detection custom + modules under the given Resource Manager parent and its + descendants. + + Returns: + Callable[[~.ListDescendantEventThreatDetectionCustomModulesRequest], + ~.ListDescendantEventThreatDetectionCustomModulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_descendant_event_threat_detection_custom_modules' not in self._stubs: + self._stubs['list_descendant_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantEventThreatDetectionCustomModules', + request_serializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.deserialize, + ) + return self._stubs['list_descendant_event_threat_detection_custom_modules'] + + @property + def list_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], + securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: + r"""Return a callable for the list event threat detection + custom modules method over gRPC. + + Lists all Event Threat Detection custom modules for + the given Resource Manager parent. This includes + resident modules defined at the scope of the parent + along with modules inherited from ancestors. + + Returns: + Callable[[~.ListEventThreatDetectionCustomModulesRequest], + ~.ListEventThreatDetectionCustomModulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_event_threat_detection_custom_modules' not in self._stubs: + self._stubs['list_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListEventThreatDetectionCustomModules', + request_serializer=securitycenter_service.ListEventThreatDetectionCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListEventThreatDetectionCustomModulesResponse.deserialize, + ) + return self._stubs['list_event_threat_detection_custom_modules'] + + @property + def update_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], + gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + r"""Return a callable for the update event threat detection + custom module method over gRPC. + + Updates the Event Threat Detection custom module with + the given name based on the given update mask. Updating + the enablement state is supported for both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name or configuration of a module is supported + for resident modules only. The type of a module cannot + be changed. + + Returns: + Callable[[~.UpdateEventThreatDetectionCustomModuleRequest], + ~.EventThreatDetectionCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['update_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['update_event_threat_detection_custom_module'] + + @property + def validate_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], + securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse]: + r"""Return a callable for the validate event threat + detection custom module method over gRPC. + + Validates the given Event Threat Detection custom + module. + + Returns: + Callable[[~.ValidateEventThreatDetectionCustomModuleRequest], + ~.ValidateEventThreatDetectionCustomModuleResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['validate_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ValidateEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.deserialize, + ) + return self._stubs['validate_event_threat_detection_custom_module'] + + @property + def get_effective_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: + r"""Return a callable for the get effective event threat + detection custom module method over gRPC. + + Gets an effective Event Threat Detection custom + module at the given level. + + Returns: + Callable[[~.GetEffectiveEventThreatDetectionCustomModuleRequest], + ~.EffectiveEventThreatDetectionCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_effective_event_threat_detection_custom_module' not in self._stubs: + self._stubs['get_effective_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['get_effective_event_threat_detection_custom_module'] + + @property + def list_effective_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: + r"""Return a callable for the list effective event threat + detection custom modules method over gRPC. + + Lists all effective Event Threat Detection custom + modules for the given parent. This includes resident + modules defined at the scope of the parent along with + modules inherited from its ancestors. + + Returns: + Callable[[~.ListEffectiveEventThreatDetectionCustomModulesRequest], + ~.ListEffectiveEventThreatDetectionCustomModulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_effective_event_threat_detection_custom_modules' not in self._stubs: + self._stubs['list_effective_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveEventThreatDetectionCustomModules', + request_serializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.deserialize, + ) + return self._stubs['list_effective_event_threat_detection_custom_modules'] + + @property + def batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + securitycenter_service.BatchCreateResourceValueConfigsResponse]: + r"""Return a callable for the batch create resource value + configs method over gRPC. + + Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + Returns: + Callable[[~.BatchCreateResourceValueConfigsRequest], + ~.BatchCreateResourceValueConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: + self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/BatchCreateResourceValueConfigs', + request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, + ) + return self._stubs['batch_create_resource_value_configs'] + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete resource value config method over gRPC. + + Deletes a ResourceValueConfig. + + Returns: + Callable[[~.DeleteResourceValueConfigRequest], + ~.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_resource_value_config' not in self._stubs: + self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteResourceValueConfig', + request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_resource_value_config'] + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + resource_value_config.ResourceValueConfig]: + r"""Return a callable for the get resource value config method over gRPC. + + Gets a ResourceValueConfig. + + Returns: + Callable[[~.GetResourceValueConfigRequest], + ~.ResourceValueConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_resource_value_config' not in self._stubs: + self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetResourceValueConfig', + request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, + response_deserializer=resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['get_resource_value_config'] + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + securitycenter_service.ListResourceValueConfigsResponse]: + r"""Return a callable for the list resource value configs method over gRPC. + + Lists all ResourceValueConfigs. + + Returns: + Callable[[~.ListResourceValueConfigsRequest], + ~.ListResourceValueConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_resource_value_configs' not in self._stubs: + self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListResourceValueConfigs', + request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, + ) + return self._stubs['list_resource_value_configs'] + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + gcs_resource_value_config.ResourceValueConfig]: + r"""Return a callable for the update resource value config method over gRPC. + + Updates an existing ResourceValueConfigs with new + rules. + + Returns: + Callable[[~.UpdateResourceValueConfigRequest], + ~.ResourceValueConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: + self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateResourceValueConfig', + request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, + response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['update_resource_value_config'] + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + securitycenter_service.ListValuedResourcesResponse]: + r"""Return a callable for the list valued resources method over gRPC. + + Lists the valued resources for a set of simulation + results and filter. + + Returns: + Callable[[~.ListValuedResourcesRequest], + ~.ListValuedResourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_valued_resources' not in self._stubs: + self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListValuedResources', + request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, + response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, + ) + return self._stubs['list_valued_resources'] + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + securitycenter_service.ListAttackPathsResponse]: + r"""Return a callable for the list attack paths method over gRPC. + + Lists the attack paths for a set of simulation + results or valued resources and filter. + + Returns: + Callable[[~.ListAttackPathsRequest], + ~.ListAttackPathsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_attack_paths' not in self._stubs: + self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListAttackPaths', + request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, + response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, + ) + return self._stubs['list_attack_paths'] + + 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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SecurityCenterGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 000000000000..9e0a84336159 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,2583 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import valued_resource +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 empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V1 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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._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 bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the bulk mute findings method over gRPC. + + Kicks off an LRO to bulk mute findings for a parent + based on a filter. The parent can be either an + organization, folder or project. The findings matched by + the filter will be muted after the LRO is done. + + Returns: + Callable[[~.BulkMuteFindingsRequest], + 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 'bulk_mute_findings' not in self._stubs: + self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/BulkMuteFindings', + request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['bulk_mute_findings'] + + @property + def create_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]]: + r"""Return a callable for the create security health + analytics custom module method over gRPC. + + Creates a resident + SecurityHealthAnalyticsCustomModule at the scope of the + given CRM parent, and also creates inherited + SecurityHealthAnalyticsCustomModules for all CRM + descendants of the given parent. These modules are + enabled by default. + + Returns: + Callable[[~.CreateSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[~.SecurityHealthAnalyticsCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: + self._stubs['create_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['create_security_health_analytics_custom_module'] + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + 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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + Awaitable[gcs_mute_config.MuteConfig]]: + r"""Return a callable for the create mute config method over gRPC. + + Creates a mute config. + + Returns: + Callable[[~.CreateMuteConfigRequest], + Awaitable[~.MuteConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateMuteConfig', + request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['create_mute_config'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete mute config method over gRPC. + + Deletes an existing mute config. + + Returns: + Callable[[~.DeleteMuteConfigRequest], + 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_mute_config' not in self._stubs: + self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteMuteConfig', + request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_mute_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + 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_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @property + def delete_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete security health + analytics custom module method over gRPC. + + Deletes the specified + SecurityHealthAnalyticsCustomModule and all of its + descendants in the CRM hierarchy. This method is only + supported for resident custom modules. + + Returns: + Callable[[~.DeleteSecurityHealthAnalyticsCustomModuleRequest], + 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_security_health_analytics_custom_module' not in self._stubs: + self._stubs['delete_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_security_health_analytics_custom_module'] + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + Awaitable[simulation.Simulation]]: + r"""Return a callable for the get simulation method over gRPC. + + Get the simulation by name or the latest simulation + for the given organization. + + Returns: + Callable[[~.GetSimulationRequest], + Awaitable[~.Simulation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_simulation' not in self._stubs: + self._stubs['get_simulation'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSimulation', + request_serializer=securitycenter_service.GetSimulationRequest.serialize, + response_deserializer=simulation.Simulation.deserialize, + ) + return self._stubs['get_simulation'] + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + Awaitable[valued_resource.ValuedResource]]: + r"""Return a callable for the get valued resource method over gRPC. + + Get the valued resource by name + + Returns: + Callable[[~.GetValuedResourceRequest], + Awaitable[~.ValuedResource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_valued_resource' not in self._stubs: + self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetValuedResource', + request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, + response_deserializer=valued_resource.ValuedResource.deserialize, + ) + return self._stubs['get_valued_resource'] + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport]]: + r"""Return a callable for the get big query export method over gRPC. + + Gets a BigQuery export. + + Returns: + Callable[[~.GetBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_big_query_export' not in self._stubs: + self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetBigQueryExport', + request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['get_big_query_export'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + Awaitable[mute_config.MuteConfig]]: + r"""Return a callable for the get mute config method over gRPC. + + Gets a mute config. + + Returns: + Callable[[~.GetMuteConfigRequest], + Awaitable[~.MuteConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_mute_config' not in self._stubs: + self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetMuteConfig', + request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, + response_deserializer=mute_config.MuteConfig.deserialize, + ) + return self._stubs['get_mute_config'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Awaitable[notification_config.NotificationConfig]]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Awaitable[organization_settings.OrganizationSettings]]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_effective_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]]: + r"""Return a callable for the get effective security health + analytics custom module method over gRPC. + + Retrieves an + EffectiveSecurityHealthAnalyticsCustomModule. + + Returns: + Callable[[~.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[~.EffectiveSecurityHealthAnalyticsCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_effective_security_health_analytics_custom_module' not in self._stubs: + self._stubs['get_effective_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['get_effective_security_health_analytics_custom_module'] + + @property + def get_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]]: + r"""Return a callable for the get security health analytics + custom module method over gRPC. + + Retrieves a SecurityHealthAnalyticsCustomModule. + + Returns: + Callable[[~.GetSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[~.SecurityHealthAnalyticsCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_security_health_analytics_custom_module' not in self._stubs: + self._stubs['get_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['get_security_health_analytics_custom_module'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Awaitable[securitycenter_service.GroupAssetsResponse]]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + Awaitable[~.GroupAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse]]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Awaitable[securitycenter_service.ListAssetsResponse]]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], + Awaitable[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]]: + r"""Return a callable for the list descendant security + health analytics custom modules method over gRPC. + + Returns a list of all resident + SecurityHealthAnalyticsCustomModules under the given CRM + parent and all of the parent’s CRM descendants. + + Returns: + Callable[[~.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], + Awaitable[~.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_descendant_security_health_analytics_custom_modules' not in self._stubs: + self._stubs['list_descendant_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantSecurityHealthAnalyticsCustomModules', + request_serializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.deserialize, + ) + return self._stubs['list_descendant_security_health_analytics_custom_modules'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + 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.securitycenter.v1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + Awaitable[securitycenter_service.ListMuteConfigsResponse]]: + r"""Return a callable for the list mute configs method over gRPC. + + Lists mute configs. + + Returns: + Callable[[~.ListMuteConfigsRequest], + Awaitable[~.ListMuteConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_mute_configs' not in self._stubs: + self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListMuteConfigs', + request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, + ) + return self._stubs['list_mute_configs'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + Awaitable[~.ListNotificationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_effective_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], + Awaitable[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]]: + r"""Return a callable for the list effective security health + analytics custom modules method over gRPC. + + Returns a list of all + EffectiveSecurityHealthAnalyticsCustomModules for the + given parent. This includes resident modules defined at + the scope of the parent, and inherited modules, + inherited from CRM ancestors. + + Returns: + Callable[[~.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], + Awaitable[~.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_effective_security_health_analytics_custom_modules' not in self._stubs: + self._stubs['list_effective_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveSecurityHealthAnalyticsCustomModules', + request_serializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.deserialize, + ) + return self._stubs['list_effective_security_health_analytics_custom_modules'] + + @property + def list_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], + Awaitable[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]]: + r"""Return a callable for the list security health analytics + custom modules method over gRPC. + + Returns a list of all + SecurityHealthAnalyticsCustomModules for the given + parent. This includes resident modules defined at the + scope of the parent, and inherited modules, inherited + from CRM ancestors. + + Returns: + Callable[[~.ListSecurityHealthAnalyticsCustomModulesRequest], + Awaitable[~.ListSecurityHealthAnalyticsCustomModulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_security_health_analytics_custom_modules' not in self._stubs: + self._stubs['list_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListSecurityHealthAnalyticsCustomModules', + request_serializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.deserialize, + ) + return self._stubs['list_security_health_analytics_custom_modules'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse]]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + 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 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + 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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set mute method over gRPC. + + Updates the mute state of a finding. + + Returns: + Callable[[~.SetMuteRequest], + 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 'set_mute' not in self._stubs: + self._stubs['set_mute'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SetMute', + request_serializer=securitycenter_service.SetMuteRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_mute'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.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.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def simulate_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse]]: + r"""Return a callable for the simulate security health + analytics custom module method over gRPC. + + Simulates a given SecurityHealthAnalyticsCustomModule + and Resource. + + Returns: + Callable[[~.SimulateSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[~.SimulateSecurityHealthAnalyticsCustomModuleResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'simulate_security_health_analytics_custom_module' not in self._stubs: + self._stubs['simulate_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SimulateSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.deserialize, + ) + return self._stubs['simulate_security_health_analytics_custom_module'] + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + Awaitable[gcs_external_system.ExternalSystem]]: + r"""Return a callable for the update external system method over gRPC. + + Updates external system. This is for a given finding. + + Returns: + Callable[[~.UpdateExternalSystemRequest], + Awaitable[~.ExternalSystem]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_external_system' not in self._stubs: + self._stubs['update_external_system'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateExternalSystem', + request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, + response_deserializer=gcs_external_system.ExternalSystem.deserialize, + ) + return self._stubs['update_external_system'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + 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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + Awaitable[gcs_mute_config.MuteConfig]]: + r"""Return a callable for the update mute config method over gRPC. + + Updates a mute config. + + Returns: + Callable[[~.UpdateMuteConfigRequest], + Awaitable[~.MuteConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateMuteConfig', + request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['update_mute_config'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Awaitable[gcs_organization_settings.OrganizationSettings]]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]]: + r"""Return a callable for the update security health + analytics custom module method over gRPC. + + Updates the SecurityHealthAnalyticsCustomModule under + the given name based on the given update mask. Updating + the enablement state is supported on both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name and custom config of a module is supported + on resident modules only. + + Returns: + Callable[[~.UpdateSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[~.SecurityHealthAnalyticsCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: + self._stubs['update_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['update_security_health_analytics_custom_module'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks]]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport]]: + r"""Return a callable for the create big query export method over gRPC. + + Creates a BigQuery export. + + Returns: + Callable[[~.CreateBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateBigQueryExport', + request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['create_big_query_export'] + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete big query export method over gRPC. + + Deletes an existing BigQuery export. + + Returns: + Callable[[~.DeleteBigQueryExportRequest], + 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_big_query_export' not in self._stubs: + self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteBigQueryExport', + request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_big_query_export'] + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport]]: + r"""Return a callable for the update big query export method over gRPC. + + Updates a BigQuery export. + + Returns: + Callable[[~.UpdateBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateBigQueryExport', + request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['update_big_query_export'] + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + Awaitable[securitycenter_service.ListBigQueryExportsResponse]]: + r"""Return a callable for the list big query exports method over gRPC. + + Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are returned. + + Returns: + Callable[[~.ListBigQueryExportsRequest], + Awaitable[~.ListBigQueryExportsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_big_query_exports' not in self._stubs: + self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListBigQueryExports', + request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, + response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, + ) + return self._stubs['list_big_query_exports'] + + @property + def create_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], + Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]]: + r"""Return a callable for the create event threat detection + custom module method over gRPC. + + Creates a resident Event Threat Detection custom + module at the scope of the given Resource Manager + parent, and also creates inherited custom modules for + all descendants of the given parent. These modules are + enabled by default. + + Returns: + Callable[[~.CreateEventThreatDetectionCustomModuleRequest], + Awaitable[~.EventThreatDetectionCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['create_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['create_event_threat_detection_custom_module'] + + @property + def delete_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete event threat detection + custom module method over gRPC. + + Deletes the specified Event Threat Detection custom + module and all of its descendants in the Resource + Manager hierarchy. This method is only supported for + resident custom modules. + + Returns: + Callable[[~.DeleteEventThreatDetectionCustomModuleRequest], + 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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['delete_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_event_threat_detection_custom_module'] + + @property + def get_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], + Awaitable[event_threat_detection_custom_module.EventThreatDetectionCustomModule]]: + r"""Return a callable for the get event threat detection + custom module method over gRPC. + + Gets an Event Threat Detection custom module. + + Returns: + Callable[[~.GetEventThreatDetectionCustomModuleRequest], + Awaitable[~.EventThreatDetectionCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_event_threat_detection_custom_module' not in self._stubs: + self._stubs['get_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.GetEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['get_event_threat_detection_custom_module'] + + @property + def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], + Awaitable[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]]: + r"""Return a callable for the list descendant event threat + detection custom modules method over gRPC. + + Lists all resident Event Threat Detection custom + modules under the given Resource Manager parent and its + descendants. + + Returns: + Callable[[~.ListDescendantEventThreatDetectionCustomModulesRequest], + Awaitable[~.ListDescendantEventThreatDetectionCustomModulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_descendant_event_threat_detection_custom_modules' not in self._stubs: + self._stubs['list_descendant_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantEventThreatDetectionCustomModules', + request_serializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.deserialize, + ) + return self._stubs['list_descendant_event_threat_detection_custom_modules'] + + @property + def list_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], + Awaitable[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]]: + r"""Return a callable for the list event threat detection + custom modules method over gRPC. + + Lists all Event Threat Detection custom modules for + the given Resource Manager parent. This includes + resident modules defined at the scope of the parent + along with modules inherited from ancestors. + + Returns: + Callable[[~.ListEventThreatDetectionCustomModulesRequest], + Awaitable[~.ListEventThreatDetectionCustomModulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_event_threat_detection_custom_modules' not in self._stubs: + self._stubs['list_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListEventThreatDetectionCustomModules', + request_serializer=securitycenter_service.ListEventThreatDetectionCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListEventThreatDetectionCustomModulesResponse.deserialize, + ) + return self._stubs['list_event_threat_detection_custom_modules'] + + @property + def update_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], + Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]]: + r"""Return a callable for the update event threat detection + custom module method over gRPC. + + Updates the Event Threat Detection custom module with + the given name based on the given update mask. Updating + the enablement state is supported for both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name or configuration of a module is supported + for resident modules only. The type of a module cannot + be changed. + + Returns: + Callable[[~.UpdateEventThreatDetectionCustomModuleRequest], + Awaitable[~.EventThreatDetectionCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['update_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['update_event_threat_detection_custom_module'] + + @property + def validate_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], + Awaitable[securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse]]: + r"""Return a callable for the validate event threat + detection custom module method over gRPC. + + Validates the given Event Threat Detection custom + module. + + Returns: + Callable[[~.ValidateEventThreatDetectionCustomModuleRequest], + Awaitable[~.ValidateEventThreatDetectionCustomModuleResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['validate_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ValidateEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.deserialize, + ) + return self._stubs['validate_event_threat_detection_custom_module'] + + @property + def get_effective_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], + Awaitable[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]]: + r"""Return a callable for the get effective event threat + detection custom module method over gRPC. + + Gets an effective Event Threat Detection custom + module at the given level. + + Returns: + Callable[[~.GetEffectiveEventThreatDetectionCustomModuleRequest], + Awaitable[~.EffectiveEventThreatDetectionCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_effective_event_threat_detection_custom_module' not in self._stubs: + self._stubs['get_effective_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['get_effective_event_threat_detection_custom_module'] + + @property + def list_effective_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], + Awaitable[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]]: + r"""Return a callable for the list effective event threat + detection custom modules method over gRPC. + + Lists all effective Event Threat Detection custom + modules for the given parent. This includes resident + modules defined at the scope of the parent along with + modules inherited from its ancestors. + + Returns: + Callable[[~.ListEffectiveEventThreatDetectionCustomModulesRequest], + Awaitable[~.ListEffectiveEventThreatDetectionCustomModulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_effective_event_threat_detection_custom_modules' not in self._stubs: + self._stubs['list_effective_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveEventThreatDetectionCustomModules', + request_serializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.deserialize, + ) + return self._stubs['list_effective_event_threat_detection_custom_modules'] + + @property + def batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse]]: + r"""Return a callable for the batch create resource value + configs method over gRPC. + + Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + Returns: + Callable[[~.BatchCreateResourceValueConfigsRequest], + Awaitable[~.BatchCreateResourceValueConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: + self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/BatchCreateResourceValueConfigs', + request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, + ) + return self._stubs['batch_create_resource_value_configs'] + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete resource value config method over gRPC. + + Deletes a ResourceValueConfig. + + Returns: + Callable[[~.DeleteResourceValueConfigRequest], + 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_resource_value_config' not in self._stubs: + self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteResourceValueConfig', + request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_resource_value_config'] + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + Awaitable[resource_value_config.ResourceValueConfig]]: + r"""Return a callable for the get resource value config method over gRPC. + + Gets a ResourceValueConfig. + + Returns: + Callable[[~.GetResourceValueConfigRequest], + Awaitable[~.ResourceValueConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_resource_value_config' not in self._stubs: + self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetResourceValueConfig', + request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, + response_deserializer=resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['get_resource_value_config'] + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + Awaitable[securitycenter_service.ListResourceValueConfigsResponse]]: + r"""Return a callable for the list resource value configs method over gRPC. + + Lists all ResourceValueConfigs. + + Returns: + Callable[[~.ListResourceValueConfigsRequest], + Awaitable[~.ListResourceValueConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_resource_value_configs' not in self._stubs: + self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListResourceValueConfigs', + request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, + ) + return self._stubs['list_resource_value_configs'] + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + Awaitable[gcs_resource_value_config.ResourceValueConfig]]: + r"""Return a callable for the update resource value config method over gRPC. + + Updates an existing ResourceValueConfigs with new + rules. + + Returns: + Callable[[~.UpdateResourceValueConfigRequest], + Awaitable[~.ResourceValueConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: + self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateResourceValueConfig', + request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, + response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['update_resource_value_config'] + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + Awaitable[securitycenter_service.ListValuedResourcesResponse]]: + r"""Return a callable for the list valued resources method over gRPC. + + Lists the valued resources for a set of simulation + results and filter. + + Returns: + Callable[[~.ListValuedResourcesRequest], + Awaitable[~.ListValuedResourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_valued_resources' not in self._stubs: + self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListValuedResources', + request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, + response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, + ) + return self._stubs['list_valued_resources'] + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + Awaitable[securitycenter_service.ListAttackPathsResponse]]: + r"""Return a callable for the list attack paths method over gRPC. + + Lists the attack paths for a set of simulation + results or valued resources and filter. + + Returns: + Callable[[~.ListAttackPathsRequest], + Awaitable[~.ListAttackPathsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_attack_paths' not in self._stubs: + self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListAttackPaths', + request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, + response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, + ) + return self._stubs['list_attack_paths'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.bulk_mute_findings: gapic_v1.method_async.wrap_method( + self.bulk_mute_findings, + default_timeout=None, + client_info=client_info, + ), + self.create_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( + self.create_security_health_analytics_custom_module, + default_timeout=60.0, + client_info=client_info, + ), + self.create_source: gapic_v1.method_async.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method_async.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.create_mute_config: gapic_v1.method_async.wrap_method( + self.create_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method_async.wrap_method( + self.create_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_mute_config: gapic_v1.method_async.wrap_method( + self.delete_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method_async.wrap_method( + self.delete_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( + self.delete_security_health_analytics_custom_module, + default_timeout=60.0, + client_info=client_info, + ), + self.get_simulation: gapic_v1.method_async.wrap_method( + self.get_simulation, + default_timeout=None, + client_info=client_info, + ), + self.get_valued_resource: gapic_v1.method_async.wrap_method( + self.get_valued_resource, + default_timeout=None, + client_info=client_info, + ), + self.get_big_query_export: gapic_v1.method_async.wrap_method( + self.get_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_mute_config: gapic_v1.method_async.wrap_method( + self.get_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.get_notification_config: gapic_v1.method_async.wrap_method( + self.get_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_settings: gapic_v1.method_async.wrap_method( + self.get_organization_settings, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_effective_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( + self.get_effective_security_health_analytics_custom_module, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( + self.get_security_health_analytics_custom_module, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_source: gapic_v1.method_async.wrap_method( + self.get_source, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.group_assets: gapic_v1.method_async.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method_async.wrap_method( + self.group_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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method_async.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_descendant_security_health_analytics_custom_modules: gapic_v1.method_async.wrap_method( + self.list_descendant_security_health_analytics_custom_modules, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method_async.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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_mute_configs: gapic_v1.method_async.wrap_method( + self.list_mute_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method_async.wrap_method( + self.list_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_effective_security_health_analytics_custom_modules: gapic_v1.method_async.wrap_method( + self.list_effective_security_health_analytics_custom_modules, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_security_health_analytics_custom_modules: gapic_v1.method_async.wrap_method( + self.list_security_health_analytics_custom_modules, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_sources: gapic_v1.method_async.wrap_method( + self.list_sources, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.run_asset_discovery: gapic_v1.method_async.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method_async.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_mute: gapic_v1.method_async.wrap_method( + self.set_mute, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.simulate_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( + self.simulate_security_health_analytics_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.update_external_system: gapic_v1.method_async.wrap_method( + self.update_external_system, + default_timeout=None, + client_info=client_info, + ), + self.update_finding: gapic_v1.method_async.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_mute_config: gapic_v1.method_async.wrap_method( + self.update_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method_async.wrap_method( + self.update_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method_async.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( + self.update_security_health_analytics_custom_module, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method_async.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method_async.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=client_info, + ), + self.create_big_query_export: gapic_v1.method_async.wrap_method( + self.create_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.delete_big_query_export: gapic_v1.method_async.wrap_method( + self.delete_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.update_big_query_export: gapic_v1.method_async.wrap_method( + self.update_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.list_big_query_exports: gapic_v1.method_async.wrap_method( + self.list_big_query_exports, + default_timeout=None, + client_info=client_info, + ), + self.create_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( + self.create_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.delete_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( + self.delete_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.get_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( + self.get_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.list_descendant_event_threat_detection_custom_modules: gapic_v1.method_async.wrap_method( + self.list_descendant_event_threat_detection_custom_modules, + default_timeout=None, + client_info=client_info, + ), + self.list_event_threat_detection_custom_modules: gapic_v1.method_async.wrap_method( + self.list_event_threat_detection_custom_modules, + default_timeout=None, + client_info=client_info, + ), + self.update_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( + self.update_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.validate_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( + self.validate_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.get_effective_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( + self.get_effective_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.list_effective_event_threat_detection_custom_modules: gapic_v1.method_async.wrap_method( + self.list_effective_event_threat_detection_custom_modules, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_resource_value_configs: gapic_v1.method_async.wrap_method( + self.batch_create_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.delete_resource_value_config: gapic_v1.method_async.wrap_method( + self.delete_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_resource_value_config: gapic_v1.method_async.wrap_method( + self.get_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.list_resource_value_configs: gapic_v1.method_async.wrap_method( + self.list_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_resource_value_config: gapic_v1.method_async.wrap_method( + self.update_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.list_valued_resources: gapic_v1.method_async.wrap_method( + self.list_valued_resources, + default_timeout=None, + client_info=client_info, + ), + self.list_attack_paths: gapic_v1.method_async.wrap_method( + self.list_attack_paths, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return 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"] + + +__all__ = ( + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py new file mode 100644 index 000000000000..cafbd10f6efa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py @@ -0,0 +1,8529 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # 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 path_template +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 +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import valued_resource +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SecurityCenterRestInterceptor: + """Interceptor for SecurityCenter. + + 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 SecurityCenterRestTransport. + + .. code-block:: python + class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): + def pre_batch_create_resource_value_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_resource_value_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_bulk_mute_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_bulk_mute_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_event_threat_detection_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_event_threat_detection_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_security_health_analytics_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_security_health_analytics_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_event_threat_detection_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_security_health_analytics_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_effective_event_threat_detection_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_effective_event_threat_detection_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_effective_security_health_analytics_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_effective_security_health_analytics_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_event_threat_detection_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_event_threat_detection_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_organization_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_organization_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_resource_value_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_security_health_analytics_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_security_health_analytics_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_simulation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_simulation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_valued_resource(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_valued_resource(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_attack_paths(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_attack_paths(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_big_query_exports(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_big_query_exports(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_descendant_event_threat_detection_custom_modules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_descendant_event_threat_detection_custom_modules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_descendant_security_health_analytics_custom_modules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_descendant_security_health_analytics_custom_modules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_effective_event_threat_detection_custom_modules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_effective_event_threat_detection_custom_modules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_effective_security_health_analytics_custom_modules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_effective_security_health_analytics_custom_modules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_event_threat_detection_custom_modules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_event_threat_detection_custom_modules(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_mute_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_mute_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_notification_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_notification_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_resource_value_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_resource_value_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_security_health_analytics_custom_modules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_security_health_analytics_custom_modules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_valued_resources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_valued_resources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_run_asset_discovery(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_asset_discovery(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_finding_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_finding_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_mute(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_mute(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_simulate_security_health_analytics_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_simulate_security_health_analytics_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_event_threat_detection_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_event_threat_detection_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_external_system(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_external_system(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_organization_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_organization_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_resource_value_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_security_health_analytics_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_security_health_analytics_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_security_marks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_security_marks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_validate_event_threat_detection_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_validate_event_threat_detection_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) + client = SecurityCenterClient(transport=transport) + + + """ + def pre_batch_create_resource_value_configs(self, request: securitycenter_service.BatchCreateResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BatchCreateResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_create_resource_value_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_batch_create_resource_value_configs(self, response: securitycenter_service.BatchCreateResourceValueConfigsResponse) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + """Post-rpc interceptor for batch_create_resource_value_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_bulk_mute_findings(self, request: securitycenter_service.BulkMuteFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BulkMuteFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for bulk_mute_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_bulk_mute_findings(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for bulk_mute_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_big_query_export(self, request: securitycenter_service.CreateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for create_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_event_threat_detection_custom_module(self, request: securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_event_threat_detection_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_event_threat_detection_custom_module(self, response: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + """Post-rpc interceptor for create_event_threat_detection_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for create_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_mute_config(self, request: securitycenter_service.CreateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: + """Post-rpc interceptor for create_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_notification_config(self, request: securitycenter_service.CreateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_security_health_analytics_custom_module(self, request: securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_security_health_analytics_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_security_health_analytics_custom_module(self, response: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + """Post-rpc interceptor for create_security_health_analytics_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for create_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_delete_big_query_export(self, request: securitycenter_service.DeleteBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_event_threat_detection_custom_module(self, request: securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_event_threat_detection_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_mute_config(self, request: securitycenter_service.DeleteMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_notification_config(self, request: securitycenter_service.DeleteNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_resource_value_config(self, request: securitycenter_service.DeleteResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteResourceValueConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_security_health_analytics_custom_module(self, request: securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_security_health_analytics_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_get_big_query_export(self, request: securitycenter_service.GetBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for get_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_effective_event_threat_detection_custom_module(self, request: securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_effective_event_threat_detection_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_effective_event_threat_detection_custom_module(self, response: effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: + """Post-rpc interceptor for get_effective_event_threat_detection_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_effective_security_health_analytics_custom_module(self, request: securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_effective_security_health_analytics_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_effective_security_health_analytics_custom_module(self, response: effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: + """Post-rpc interceptor for get_effective_security_health_analytics_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_event_threat_detection_custom_module(self, request: securitycenter_service.GetEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_event_threat_detection_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_event_threat_detection_custom_module(self, response: event_threat_detection_custom_module.EventThreatDetectionCustomModule) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: + """Post-rpc interceptor for get_event_threat_detection_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_mute_config(self, request: securitycenter_service.GetMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_mute_config(self, response: mute_config.MuteConfig) -> mute_config.MuteConfig: + """Post-rpc interceptor for get_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_notification_config(self, request: securitycenter_service.GetNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_notification_config(self, response: notification_config.NotificationConfig) -> notification_config.NotificationConfig: + """Post-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_organization_settings(self, request: securitycenter_service.GetOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_organization_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_organization_settings(self, response: organization_settings.OrganizationSettings) -> organization_settings.OrganizationSettings: + """Post-rpc interceptor for get_organization_settings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_resource_value_config(self, request: securitycenter_service.GetResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetResourceValueConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_resource_value_config(self, response: resource_value_config.ResourceValueConfig) -> resource_value_config.ResourceValueConfig: + """Post-rpc interceptor for get_resource_value_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_security_health_analytics_custom_module(self, request: securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_security_health_analytics_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_security_health_analytics_custom_module(self, response: security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + """Post-rpc interceptor for get_security_health_analytics_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_simulation(self, request: securitycenter_service.GetSimulationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSimulationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_simulation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_simulation(self, response: simulation.Simulation) -> simulation.Simulation: + """Post-rpc interceptor for get_simulation + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_source(self, response: source.Source) -> source.Source: + """Post-rpc interceptor for get_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_valued_resource(self, request: securitycenter_service.GetValuedResourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetValuedResourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_valued_resource + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_valued_resource(self, response: valued_resource.ValuedResource) -> valued_resource.ValuedResource: + """Post-rpc interceptor for get_valued_resource + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_assets(self, request: securitycenter_service.GroupAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_assets(self, response: securitycenter_service.GroupAssetsResponse) -> securitycenter_service.GroupAssetsResponse: + """Post-rpc interceptor for group_assets + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: + """Post-rpc interceptor for group_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_assets(self, request: securitycenter_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_assets(self, response: securitycenter_service.ListAssetsResponse) -> securitycenter_service.ListAssetsResponse: + """Post-rpc interceptor for list_assets + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_attack_paths(self, request: securitycenter_service.ListAttackPathsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAttackPathsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_attack_paths + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_attack_paths(self, response: securitycenter_service.ListAttackPathsResponse) -> securitycenter_service.ListAttackPathsResponse: + """Post-rpc interceptor for list_attack_paths + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_big_query_exports(self, request: securitycenter_service.ListBigQueryExportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListBigQueryExportsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_big_query_exports + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_big_query_exports(self, response: securitycenter_service.ListBigQueryExportsResponse) -> securitycenter_service.ListBigQueryExportsResponse: + """Post-rpc interceptor for list_big_query_exports + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_descendant_event_threat_detection_custom_modules(self, request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_descendant_event_threat_detection_custom_modules + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_descendant_event_threat_detection_custom_modules(self, response: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse) -> securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse: + """Post-rpc interceptor for list_descendant_event_threat_detection_custom_modules + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_descendant_security_health_analytics_custom_modules(self, request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_descendant_security_health_analytics_custom_modules + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_descendant_security_health_analytics_custom_modules(self, response: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse) -> securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse: + """Post-rpc interceptor for list_descendant_security_health_analytics_custom_modules + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_effective_event_threat_detection_custom_modules(self, request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_effective_event_threat_detection_custom_modules + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_effective_event_threat_detection_custom_modules(self, response: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse) -> securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse: + """Post-rpc interceptor for list_effective_event_threat_detection_custom_modules + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_effective_security_health_analytics_custom_modules(self, request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_effective_security_health_analytics_custom_modules + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_effective_security_health_analytics_custom_modules(self, response: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse) -> securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse: + """Post-rpc interceptor for list_effective_security_health_analytics_custom_modules + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_event_threat_detection_custom_modules(self, request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListEventThreatDetectionCustomModulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_event_threat_detection_custom_modules + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_event_threat_detection_custom_modules(self, response: securitycenter_service.ListEventThreatDetectionCustomModulesResponse) -> securitycenter_service.ListEventThreatDetectionCustomModulesResponse: + """Post-rpc interceptor for list_event_threat_detection_custom_modules + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. + """ + return request, metadata + + def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_mute_configs(self, request: securitycenter_service.ListMuteConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListMuteConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_mute_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_mute_configs(self, response: securitycenter_service.ListMuteConfigsResponse) -> securitycenter_service.ListMuteConfigsResponse: + """Post-rpc interceptor for list_mute_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_notification_configs(self, request: securitycenter_service.ListNotificationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListNotificationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_notification_configs(self, response: securitycenter_service.ListNotificationConfigsResponse) -> securitycenter_service.ListNotificationConfigsResponse: + """Post-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_resource_value_configs(self, request: securitycenter_service.ListResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_resource_value_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_resource_value_configs(self, response: securitycenter_service.ListResourceValueConfigsResponse) -> securitycenter_service.ListResourceValueConfigsResponse: + """Post-rpc interceptor for list_resource_value_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_security_health_analytics_custom_modules(self, request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_security_health_analytics_custom_modules + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_security_health_analytics_custom_modules(self, response: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse) -> securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse: + """Post-rpc interceptor for list_security_health_analytics_custom_modules + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_sources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: + """Post-rpc interceptor for list_sources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_valued_resources(self, request: securitycenter_service.ListValuedResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListValuedResourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_valued_resources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_valued_resources(self, response: securitycenter_service.ListValuedResourcesResponse) -> securitycenter_service.ListValuedResourcesResponse: + """Post-rpc interceptor for list_valued_resources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_run_asset_discovery(self, request: securitycenter_service.RunAssetDiscoveryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.RunAssetDiscoveryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for run_asset_discovery + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_run_asset_discovery(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for run_asset_discovery + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_set_mute(self, request: securitycenter_service.SetMuteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetMuteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_mute + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_mute(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_mute + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_simulate_security_health_analytics_custom_module(self, request: securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for simulate_security_health_analytics_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_simulate_security_health_analytics_custom_module(self, response: securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: + """Post-rpc interceptor for simulate_security_health_analytics_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_big_query_export(self, request: securitycenter_service.UpdateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for update_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_event_threat_detection_custom_module(self, request: securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_event_threat_detection_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_event_threat_detection_custom_module(self, response: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + """Post-rpc interceptor for update_event_threat_detection_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_external_system(self, request: securitycenter_service.UpdateExternalSystemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateExternalSystemRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_external_system + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_external_system(self, response: gcs_external_system.ExternalSystem) -> gcs_external_system.ExternalSystem: + """Post-rpc interceptor for update_external_system + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for update_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_mute_config(self, request: securitycenter_service.UpdateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: + """Post-rpc interceptor for update_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_notification_config(self, request: securitycenter_service.UpdateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_organization_settings(self, request: securitycenter_service.UpdateOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_organization_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_organization_settings(self, response: gcs_organization_settings.OrganizationSettings) -> gcs_organization_settings.OrganizationSettings: + """Post-rpc interceptor for update_organization_settings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_resource_value_config(self, request: securitycenter_service.UpdateResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateResourceValueConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_resource_value_config(self, response: gcs_resource_value_config.ResourceValueConfig) -> gcs_resource_value_config.ResourceValueConfig: + """Post-rpc interceptor for update_resource_value_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_security_health_analytics_custom_module(self, request: securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_security_health_analytics_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_security_health_analytics_custom_module(self, response: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + """Post-rpc interceptor for update_security_health_analytics_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: + """Post-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for update_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_validate_event_threat_detection_custom_module(self, request: securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for validate_event_threat_detection_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_validate_event_threat_detection_custom_module(self, response: securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: + """Post-rpc interceptor for validate_event_threat_detection_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SecurityCenterRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SecurityCenterRestInterceptor + + +class SecurityCenterRestTransport(SecurityCenterTransport): + """REST backend transport for SecurityCenter. + + V1 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[SecurityCenterRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 + 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 + ) + 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 SecurityCenterRestInterceptor() + 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=organizations/*/operations/*}:cancel', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/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 _BatchCreateResourceValueConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("BatchCreateResourceValueConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.BatchCreateResourceValueConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Call the batch create resource + value configs method over HTTP. + + Args: + request (~.securitycenter_service.BatchCreateResourceValueConfigsRequest): + The request object. Request message to create multiple + resource value configs + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/resourceValueConfigs:batchCreate', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_batch_create_resource_value_configs(request, metadata) + pb_request = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.BatchCreateResourceValueConfigsResponse() + pb_resp = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_create_resource_value_configs(resp) + return resp + + class _BulkMuteFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("BulkMuteFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.BulkMuteFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the bulk mute findings method over HTTP. + + Args: + request (~.securitycenter_service.BulkMuteFindingsRequest): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/findings:bulkMute', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_bulk_mute_findings(request, metadata) + pb_request = securitycenter_service.BulkMuteFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_bulk_mute_findings(resp) + return resp + + class _CreateBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "bigQueryExportId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> bigquery_export.BigQueryExport: + r"""Call the create big query export method over HTTP. + + Args: + request (~.securitycenter_service.CreateBigQueryExportRequest): + The request object. Request message for creating a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/bigQueryExports', + 'body': 'big_query_export', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*}/bigQueryExports', + 'body': 'big_query_export', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/bigQueryExports', + 'body': 'big_query_export', + }, + ] + request, metadata = self._interceptor.pre_create_big_query_export(request, metadata) + pb_request = securitycenter_service.CreateBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_big_query_export(resp) + return resp + + class _CreateEventThreatDetectionCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateEventThreatDetectionCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Call the create event threat + detection custom module method over HTTP. + + Args: + request (~.securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): + The request object. Request to create an Event Threat + Detection custom module. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/customModules', + 'body': 'event_threat_detection_custom_module', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/customModules', + 'body': 'event_threat_detection_custom_module', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/customModules', + 'body': 'event_threat_detection_custom_module', + }, + ] + request, metadata = self._interceptor.pre_create_event_threat_detection_custom_module(request, metadata) + pb_request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + pb_resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_event_threat_detection_custom_module(resp) + return resp + + class _CreateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "findingId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the create finding method over HTTP. + + Args: + request (~.securitycenter_service.CreateFindingRequest): + The request object. Request message for creating a + finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/sources/*}/findings', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_create_finding(request, metadata) + pb_request = securitycenter_service.CreateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_finding(resp) + return resp + + class _CreateMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "muteConfigId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_mute_config.MuteConfig: + r"""Call the create mute config method over HTTP. + + Args: + request (~.securitycenter_service.CreateMuteConfigRequest): + The request object. Request message for creating a mute + config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/locations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*/locations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/muteConfigs', + 'body': 'mute_config', + }, + ] + request, metadata = self._interceptor.pre_create_mute_config(request, metadata) + pb_request = securitycenter_service.CreateMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_mute_config.MuteConfig() + pb_resp = gcs_mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_mute_config(resp) + return resp + + class _CreateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "configId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the create notification + config method over HTTP. + + Args: + request (~.securitycenter_service.CreateNotificationConfigRequest): + The request object. Request message for creating a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/notificationConfigs', + 'body': 'notification_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*}/notificationConfigs', + 'body': 'notification_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/notificationConfigs', + 'body': 'notification_config', + }, + ] + request, metadata = self._interceptor.pre_create_notification_config(request, metadata) + pb_request = securitycenter_service.CreateNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_notification_config(resp) + return resp + + class _CreateSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateSecurityHealthAnalyticsCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Call the create security health + analytics custom module method over HTTP. + + Args: + request (~.securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): + The request object. Request message for creating Security + Health Analytics custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules', + 'body': 'security_health_analytics_custom_module', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules', + 'body': 'security_health_analytics_custom_module', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules', + 'body': 'security_health_analytics_custom_module', + }, + ] + request, metadata = self._interceptor.pre_create_security_health_analytics_custom_module(request, metadata) + pb_request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + pb_resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_security_health_analytics_custom_module(resp) + return resp + + class _CreateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the create source method over HTTP. + + Args: + request (~.securitycenter_service.CreateSourceRequest): + The request object. Request message for creating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/sources', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_create_source(request, metadata) + pb_request = securitycenter_service.CreateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_source(resp) + return resp + + class _DeleteBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete big query export method over HTTP. + + Args: + request (~.securitycenter_service.DeleteBigQueryExportRequest): + The request object. Request message for deleting a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/bigQueryExports/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=folders/*/bigQueryExports/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/bigQueryExports/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_big_query_export(request, metadata) + pb_request = securitycenter_service.DeleteBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteEventThreatDetectionCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteEventThreatDetectionCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete event threat + detection custom module method over HTTP. + + Args: + request (~.securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): + The request object. Request to delete an Event Threat + Detection custom module. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/eventThreatDetectionSettings/customModules/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=folders/*/eventThreatDetectionSettings/customModules/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/eventThreatDetectionSettings/customModules/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_event_threat_detection_custom_module(request, metadata) + pb_request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete mute config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteMuteConfigRequest): + The request object. Request message for deleting a mute + config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=folders/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=folders/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/muteConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_mute_config(request, metadata) + pb_request = securitycenter_service.DeleteMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete notification + config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteNotificationConfigRequest): + The request object. Request message for deleting a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/notificationConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=folders/*/notificationConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/notificationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_notification_config(request, metadata) + pb_request = securitycenter_service.DeleteNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteResourceValueConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteResourceValueConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete resource value + config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteResourceValueConfigRequest): + The request object. Request message to delete resource + value config + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/resourceValueConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_resource_value_config(request, metadata) + pb_request = securitycenter_service.DeleteResourceValueConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteSecurityHealthAnalyticsCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete security health + analytics custom module method over HTTP. + + Args: + request (~.securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): + The request object. Request message for deleting Security + Health Analytics custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/securityHealthAnalyticsSettings/customModules/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=folders/*/securityHealthAnalyticsSettings/customModules/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/securityHealthAnalyticsSettings/customModules/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_security_health_analytics_custom_module(request, metadata) + pb_request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _GetBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("GetBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> bigquery_export.BigQueryExport: + r"""Call the get big query export method over HTTP. + + Args: + request (~.securitycenter_service.GetBigQueryExportRequest): + The request object. Request message for retrieving a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/bigQueryExports/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/bigQueryExports/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/bigQueryExports/*}', + }, + ] + request, metadata = self._interceptor.pre_get_big_query_export(request, metadata) + pb_request = securitycenter_service.GetBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_big_query_export(resp) + return resp + + class _GetEffectiveEventThreatDetectionCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("GetEffectiveEventThreatDetectionCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: + r"""Call the get effective event + threat detection custom module method over HTTP. + + Args: + request (~.securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): + The request object. Request to get an + EffectiveEventThreatDetectionCustomModule. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: + An EffectiveEventThreatDetectionCustomModule is the + representation of an Event Threat Detection custom + module at a specified level of the resource hierarchy: + organization, folder, or project. If a custom module is + inherited from a parent organization or folder, the + value of the ``enablement_state`` property in + EffectiveEventThreatDetectionCustomModule is set to the + value that is effective in the parent, instead of + ``INHERITED``. For example, if the module is enabled in + a parent organization or folder, the effective + ``enablement_state`` for the module in all child folders + or projects is also ``enabled``. + EffectiveEventThreatDetectionCustomModule is read-only. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/eventThreatDetectionSettings/effectiveCustomModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/eventThreatDetectionSettings/effectiveCustomModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/eventThreatDetectionSettings/effectiveCustomModules/*}', + }, + ] + request, metadata = self._interceptor.pre_get_effective_event_threat_detection_custom_module(request, metadata) + pb_request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + pb_resp = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_effective_event_threat_detection_custom_module(resp) + return resp + + class _GetEffectiveSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("GetEffectiveSecurityHealthAnalyticsCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: + r"""Call the get effective security + health analytics custom module method over HTTP. + + Args: + request (~.securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): + The request object. Request message for getting effective + Security Health Analytics custom + modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: + An EffectiveSecurityHealthAnalyticsCustomModule is the + representation of a Security Health Analytics custom + module at a specified level of the resource hierarchy: + organization, folder, or project. If a custom module is + inherited from a parent organization or folder, the + value of the ``enablementState`` property in + EffectiveSecurityHealthAnalyticsCustomModule is set to + the value that is effective in the parent, instead of + ``INHERITED``. For example, if the module is enabled in + a parent organization or folder, the effective + enablement_state for the module in all child folders or + projects is also ``enabled``. + EffectiveSecurityHealthAnalyticsCustomModule is + read-only. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}', + }, + ] + request, metadata = self._interceptor.pre_get_effective_security_health_analytics_custom_module(request, metadata) + pb_request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + pb_resp = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_effective_security_health_analytics_custom_module(resp) + return resp + + class _GetEventThreatDetectionCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("GetEventThreatDetectionCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetEventThreatDetectionCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Call the get event threat + detection custom module method over HTTP. + + Args: + request (~.securitycenter_service.GetEventThreatDetectionCustomModuleRequest): + The request object. Request to get an Event Threat + Detection custom module. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.event_threat_detection_custom_module.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/eventThreatDetectionSettings/customModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/eventThreatDetectionSettings/customModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/eventThreatDetectionSettings/customModules/*}', + }, + ] + request, metadata = self._interceptor.pre_get_event_threat_detection_custom_module(request, metadata) + pb_request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + pb_resp = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_event_threat_detection_custom_module(resp) + return resp + + class _GetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=organizations/*/sources/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> mute_config.MuteConfig: + r"""Call the get mute config method over HTTP. + + Args: + request (~.securitycenter_service.GetMuteConfigRequest): + The request object. Request message for retrieving a mute + config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/muteConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_mute_config(request, metadata) + pb_request = securitycenter_service.GetMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = mute_config.MuteConfig() + pb_resp = mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_mute_config(resp) + return resp + + class _GetNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> notification_config.NotificationConfig: + r"""Call the get notification config method over HTTP. + + Args: + request (~.securitycenter_service.GetNotificationConfigRequest): + The request object. Request message for getting a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/notificationConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/notificationConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/notificationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_notification_config(request, metadata) + pb_request = securitycenter_service.GetNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = notification_config.NotificationConfig() + pb_resp = notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_notification_config(resp) + return resp + + class _GetOrganizationSettings(SecurityCenterRestStub): + def __hash__(self): + return hash("GetOrganizationSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetOrganizationSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> organization_settings.OrganizationSettings: + r"""Call the get organization settings method over HTTP. + + Args: + request (~.securitycenter_service.GetOrganizationSettingsRequest): + The request object. Request message for getting + organization 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: + ~.organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/organizationSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_organization_settings(request, metadata) + pb_request = securitycenter_service.GetOrganizationSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = organization_settings.OrganizationSettings() + pb_resp = organization_settings.OrganizationSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_organization_settings(resp) + return resp + + class _GetResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetResourceValueConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetResourceValueConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resource_value_config.ResourceValueConfig: + r"""Call the get resource value config method over HTTP. + + Args: + request (~.securitycenter_service.GetResourceValueConfigRequest): + The request object. Request message to get resource value + config + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource_value_config.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/resourceValueConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_resource_value_config(request, metadata) + pb_request = securitycenter_service.GetResourceValueConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource_value_config.ResourceValueConfig() + pb_resp = resource_value_config.ResourceValueConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_resource_value_config(resp) + return resp + + class _GetSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSecurityHealthAnalyticsCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Call the get security health + analytics custom module method over HTTP. + + Args: + request (~.securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): + The request object. Request message for getting Security + Health Analytics custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/securityHealthAnalyticsSettings/customModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/securityHealthAnalyticsSettings/customModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/securityHealthAnalyticsSettings/customModules/*}', + }, + ] + request, metadata = self._interceptor.pre_get_security_health_analytics_custom_module(request, metadata) + pb_request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + pb_resp = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_security_health_analytics_custom_module(resp) + return resp + + class _GetSimulation(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSimulation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSimulationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> simulation.Simulation: + r"""Call the get simulation method over HTTP. + + Args: + request (~.securitycenter_service.GetSimulationRequest): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.simulation.Simulation: + Attack path simulation + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/simulations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_simulation(request, metadata) + pb_request = securitycenter_service.GetSimulationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = simulation.Simulation() + pb_resp = simulation.Simulation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_simulation(resp) + return resp + + class _GetSource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> source.Source: + r"""Call the get source method over HTTP. + + Args: + request (~.securitycenter_service.GetSourceRequest): + The request object. Request message for getting a source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/sources/*}', + }, + ] + request, metadata = self._interceptor.pre_get_source(request, metadata) + pb_request = securitycenter_service.GetSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = source.Source() + pb_resp = source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_source(resp) + return resp + + class _GetValuedResource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetValuedResource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetValuedResourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> valued_resource.ValuedResource: + r"""Call the get valued resource method over HTTP. + + Args: + request (~.securitycenter_service.GetValuedResourceRequest): + The request object. Request message for getting a valued + resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.valued_resource.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/simulations/*/valuedResources/*}', + }, + ] + request, metadata = self._interceptor.pre_get_valued_resource(request, metadata) + pb_request = securitycenter_service.GetValuedResourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = valued_resource.ValuedResource() + pb_resp = valued_resource.ValuedResource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_valued_resource(resp) + return resp + + class _GroupAssets(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupAssetsResponse: + r"""Call the group assets method over HTTP. + + Args: + request (~.securitycenter_service.GroupAssetsRequest): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupAssetsResponse: + Response message for grouping by + assets. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/assets:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*}/assets:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/assets:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_assets(request, metadata) + pb_request = securitycenter_service.GroupAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupAssetsResponse() + pb_resp = securitycenter_service.GroupAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_assets(resp) + return resp + + class _GroupFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupFindingsResponse: + r"""Call the group findings method over HTTP. + + Args: + request (~.securitycenter_service.GroupFindingsRequest): + The request object. Request message for grouping by + findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupFindingsResponse: + Response message for group by + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/sources/*}/findings:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_findings(request, metadata) + pb_request = securitycenter_service.GroupFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupFindingsResponse() + pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_findings(resp) + return resp + + class _ListAssets(SecurityCenterRestStub): + def __hash__(self): + return hash("ListAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListAssetsResponse: + r"""Call the list assets method over HTTP. + + Args: + request (~.securitycenter_service.ListAssetsRequest): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListAssetsResponse: + Response message for listing assets. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*}/assets', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*}/assets', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*}/assets', + }, + ] + request, metadata = self._interceptor.pre_list_assets(request, metadata) + pb_request = securitycenter_service.ListAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListAssetsResponse() + pb_resp = securitycenter_service.ListAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_assets(resp) + return resp + + class _ListAttackPaths(SecurityCenterRestStub): + def __hash__(self): + return hash("ListAttackPaths") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListAttackPathsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListAttackPathsResponse: + r"""Call the list attack paths method over HTTP. + + Args: + request (~.securitycenter_service.ListAttackPathsRequest): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListAttackPathsResponse: + Response message for listing the + attack paths for a given simulation or + valued resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/simulations/*}/attackPaths', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/simulations/*/valuedResources/*}/attackPaths', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/simulations/*/attackExposureResults/*}/attackPaths', + }, + ] + request, metadata = self._interceptor.pre_list_attack_paths(request, metadata) + pb_request = securitycenter_service.ListAttackPathsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListAttackPathsResponse() + pb_resp = securitycenter_service.ListAttackPathsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_attack_paths(resp) + return resp + + class _ListBigQueryExports(SecurityCenterRestStub): + def __hash__(self): + return hash("ListBigQueryExports") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListBigQueryExportsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListBigQueryExportsResponse: + r"""Call the list big query exports method over HTTP. + + Args: + request (~.securitycenter_service.ListBigQueryExportsRequest): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or 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: + ~.securitycenter_service.ListBigQueryExportsResponse: + Response message for listing BigQuery + exports. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*}/bigQueryExports', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*}/bigQueryExports', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*}/bigQueryExports', + }, + ] + request, metadata = self._interceptor.pre_list_big_query_exports(request, metadata) + pb_request = securitycenter_service.ListBigQueryExportsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListBigQueryExportsResponse() + pb_resp = securitycenter_service.ListBigQueryExportsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_big_query_exports(resp) + return resp + + class _ListDescendantEventThreatDetectionCustomModules(SecurityCenterRestStub): + def __hash__(self): + return hash("ListDescendantEventThreatDetectionCustomModules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse: + r"""Call the list descendant event + threat detection custom modules method over HTTP. + + Args: + request (~.securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): + The request object. Request to list current and + descendant resident Event Threat + Detection custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse: + Response for listing current and + descendant resident Event Threat + Detection custom modules. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/customModules:listDescendant', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/customModules:listDescendant', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/customModules:listDescendant', + }, + ] + request, metadata = self._interceptor.pre_list_descendant_event_threat_detection_custom_modules(request, metadata) + pb_request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + pb_resp = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_descendant_event_threat_detection_custom_modules(resp) + return resp + + class _ListDescendantSecurityHealthAnalyticsCustomModules(SecurityCenterRestStub): + def __hash__(self): + return hash("ListDescendantSecurityHealthAnalyticsCustomModules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse: + r"""Call the list descendant security + health analytics custom modules method over HTTP. + + Args: + request (~.securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + The request object. Request message for listing + descendant Security Health Analytics + custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse: + Response message for listing + descendant Security Health Analytics + custom modules. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules:listDescendant', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules:listDescendant', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules:listDescendant', + }, + ] + request, metadata = self._interceptor.pre_list_descendant_security_health_analytics_custom_modules(request, metadata) + pb_request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + pb_resp = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_descendant_security_health_analytics_custom_modules(resp) + return resp + + class _ListEffectiveEventThreatDetectionCustomModules(SecurityCenterRestStub): + def __hash__(self): + return hash("ListEffectiveEventThreatDetectionCustomModules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse: + r"""Call the list effective event + threat detection custom modules method over HTTP. + + Args: + request (~.securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): + The request object. Request to list effective Event + Threat Detection custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse: + Response for listing + EffectiveEventThreatDetectionCustomModules. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/effectiveCustomModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/effectiveCustomModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/effectiveCustomModules', + }, + ] + request, metadata = self._interceptor.pre_list_effective_event_threat_detection_custom_modules(request, metadata) + pb_request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + pb_resp = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_effective_event_threat_detection_custom_modules(resp) + return resp + + class _ListEffectiveSecurityHealthAnalyticsCustomModules(SecurityCenterRestStub): + def __hash__(self): + return hash("ListEffectiveSecurityHealthAnalyticsCustomModules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse: + r"""Call the list effective security + health analytics custom modules method over HTTP. + + Args: + request (~.securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + The request object. Request message for listing effective + Security Health Analytics custom + modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse: + Response message for listing + effective Security Health Analytics + custom modules. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/effectiveCustomModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/effectiveCustomModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/effectiveCustomModules', + }, + ] + request, metadata = self._interceptor.pre_list_effective_security_health_analytics_custom_modules(request, metadata) + pb_request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + pb_resp = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_effective_security_health_analytics_custom_modules(resp) + return resp + + class _ListEventThreatDetectionCustomModules(SecurityCenterRestStub): + def __hash__(self): + return hash("ListEventThreatDetectionCustomModules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListEventThreatDetectionCustomModulesResponse: + r"""Call the list event threat + detection custom modules method over HTTP. + + Args: + request (~.securitycenter_service.ListEventThreatDetectionCustomModulesRequest): + The request object. Request to list Event Threat + Detection custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListEventThreatDetectionCustomModulesResponse: + Response for listing Event Threat + Detection custom modules. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/customModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/customModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/customModules', + }, + ] + request, metadata = self._interceptor.pre_list_event_threat_detection_custom_modules(request, metadata) + pb_request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + pb_resp = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_event_threat_detection_custom_modules(resp) + return resp + + class _ListFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("ListFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.securitycenter_service.ListFindingsRequest): + The request object. Request message for listing findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListFindingsResponse: + Response message for listing + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/sources/*}/findings', + }, + ] + request, metadata = self._interceptor.pre_list_findings(request, metadata) + pb_request = securitycenter_service.ListFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListFindingsResponse() + pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListMuteConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListMuteConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListMuteConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListMuteConfigsResponse: + r"""Call the list mute configs method over HTTP. + + Args: + request (~.securitycenter_service.ListMuteConfigsRequest): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or 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: + ~.securitycenter_service.ListMuteConfigsResponse: + Response message for listing mute + configs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/locations/*/muteConfigs}', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/locations/*/muteConfigs}', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/muteConfigs}', + }, + ] + request, metadata = self._interceptor.pre_list_mute_configs(request, metadata) + pb_request = securitycenter_service.ListMuteConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListMuteConfigsResponse() + pb_resp = securitycenter_service.ListMuteConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_mute_configs(resp) + return resp + + class _ListNotificationConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListNotificationConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListNotificationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListNotificationConfigsResponse: + r"""Call the list notification configs method over HTTP. + + Args: + request (~.securitycenter_service.ListNotificationConfigsRequest): + The request object. Request message for listing + notification configs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListNotificationConfigsResponse: + Response message for listing + notification configs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*}/notificationConfigs', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*}/notificationConfigs', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*}/notificationConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_notification_configs(request, metadata) + pb_request = securitycenter_service.ListNotificationConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListNotificationConfigsResponse() + pb_resp = securitycenter_service.ListNotificationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_notification_configs(resp) + return resp + + class _ListResourceValueConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListResourceValueConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListResourceValueConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListResourceValueConfigsResponse: + r"""Call the list resource value + configs method over HTTP. + + Args: + request (~.securitycenter_service.ListResourceValueConfigsRequest): + The request object. Request message to list resource + value configs of a parent + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListResourceValueConfigsResponse: + Response message to list resource + value configs + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*}/resourceValueConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_resource_value_configs(request, metadata) + pb_request = securitycenter_service.ListResourceValueConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListResourceValueConfigsResponse() + pb_resp = securitycenter_service.ListResourceValueConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_resource_value_configs(resp) + return resp + + class _ListSecurityHealthAnalyticsCustomModules(SecurityCenterRestStub): + def __hash__(self): + return hash("ListSecurityHealthAnalyticsCustomModules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse: + r"""Call the list security health + analytics custom modules method over HTTP. + + Args: + request (~.securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): + The request object. Request message for listing Security + Health Analytics custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse: + Response message for listing Security + Health Analytics custom modules. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules', + }, + ] + request, metadata = self._interceptor.pre_list_security_health_analytics_custom_modules(request, metadata) + pb_request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + pb_resp = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_security_health_analytics_custom_modules(resp) + return resp + + class _ListSources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListSources") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListSourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListSourcesResponse: + r"""Call the list sources method over HTTP. + + Args: + request (~.securitycenter_service.ListSourcesRequest): + The request object. Request message for listing sources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListSourcesResponse: + Response message for listing sources. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*}/sources', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*}/sources', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*}/sources', + }, + ] + request, metadata = self._interceptor.pre_list_sources(request, metadata) + pb_request = securitycenter_service.ListSourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListSourcesResponse() + pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sources(resp) + return resp + + class _ListValuedResources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListValuedResources") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListValuedResourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListValuedResourcesResponse: + r"""Call the list valued resources method over HTTP. + + Args: + request (~.securitycenter_service.ListValuedResourcesRequest): + The request object. Request message for listing the + valued resources for a given simulation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListValuedResourcesResponse: + Response message for listing the + valued resources for a given simulation. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/simulations/*}/valuedResources', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/simulations/*/attackExposureResults/*}/valuedResources', + }, + ] + request, metadata = self._interceptor.pre_list_valued_resources(request, metadata) + pb_request = securitycenter_service.ListValuedResourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListValuedResourcesResponse() + pb_resp = securitycenter_service.ListValuedResourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_valued_resources(resp) + return resp + + class _RunAssetDiscovery(SecurityCenterRestStub): + def __hash__(self): + return hash("RunAssetDiscovery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.RunAssetDiscoveryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the run asset discovery method over HTTP. + + Args: + request (~.securitycenter_service.RunAssetDiscoveryRequest): + The request object. Request message for running asset + discovery for an organization. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/assets:runDiscovery', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_run_asset_discovery(request, metadata) + pb_request = securitycenter_service.RunAssetDiscoveryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_run_asset_discovery(resp) + return resp + + class _SetFindingState(SecurityCenterRestStub): + def __hash__(self): + return hash("SetFindingState") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SetFindingStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the set finding state method over HTTP. + + Args: + request (~.securitycenter_service.SetFindingStateRequest): + The request object. Request message for updating a + finding's state. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=organizations/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{name=folders/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/sources/*/findings/*}:setState', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_finding_state(request, metadata) + pb_request = securitycenter_service.SetFindingStateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_set_finding_state(resp) + return resp + + class _SetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=organizations/*/sources/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _SetMute(SecurityCenterRestStub): + def __hash__(self): + return hash("SetMute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SetMuteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the set mute method over HTTP. + + Args: + request (~.securitycenter_service.SetMuteRequest): + The request object. Request message for updating a + finding's mute status. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=organizations/*/sources/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{name=folders/*/sources/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/sources/*/findings/*}:setMute', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_mute(request, metadata) + pb_request = securitycenter_service.SetMuteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_set_mute(resp) + return resp + + class _SimulateSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("SimulateSecurityHealthAnalyticsCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: + r"""Call the simulate security health + analytics custom module method over HTTP. + + Args: + request (~.securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): + The request object. Request message to simulate a + CustomConfig against a given test + resource. Maximum size of the request is + 4 MB by default. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: + Response message for simulating a + ``SecurityHealthAnalyticsCustomModule`` against a given + resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules:simulate', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules:simulate', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules:simulate', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_simulate_security_health_analytics_custom_module(request, metadata) + pb_request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + pb_resp = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_simulate_security_health_analytics_custom_module(resp) + return resp + + class _TestIamPermissions(SecurityCenterRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=organizations/*/sources/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UpdateBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> bigquery_export.BigQueryExport: + r"""Call the update big query export method over HTTP. + + Args: + request (~.securitycenter_service.UpdateBigQueryExportRequest): + The request object. Request message for updating a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{big_query_export.name=organizations/*/bigQueryExports/*}', + 'body': 'big_query_export', + }, +{ + 'method': 'patch', + 'uri': '/v1/{big_query_export.name=folders/*/bigQueryExports/*}', + 'body': 'big_query_export', + }, +{ + 'method': 'patch', + 'uri': '/v1/{big_query_export.name=projects/*/bigQueryExports/*}', + 'body': 'big_query_export', + }, + ] + request, metadata = self._interceptor.pre_update_big_query_export(request, metadata) + pb_request = securitycenter_service.UpdateBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_big_query_export(resp) + return resp + + class _UpdateEventThreatDetectionCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateEventThreatDetectionCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Call the update event threat + detection custom module method over HTTP. + + Args: + request (~.securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): + The request object. Request to update an Event Threat + Detection custom module. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{event_threat_detection_custom_module.name=organizations/*/eventThreatDetectionSettings/customModules/*}', + 'body': 'event_threat_detection_custom_module', + }, +{ + 'method': 'patch', + 'uri': '/v1/{event_threat_detection_custom_module.name=folders/*/eventThreatDetectionSettings/customModules/*}', + 'body': 'event_threat_detection_custom_module', + }, +{ + 'method': 'patch', + 'uri': '/v1/{event_threat_detection_custom_module.name=projects/*/eventThreatDetectionSettings/customModules/*}', + 'body': 'event_threat_detection_custom_module', + }, + ] + request, metadata = self._interceptor.pre_update_event_threat_detection_custom_module(request, metadata) + pb_request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + pb_resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_event_threat_detection_custom_module(resp) + return resp + + class _UpdateExternalSystem(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateExternalSystem") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateExternalSystemRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_external_system.ExternalSystem: + r"""Call the update external system method over HTTP. + + Args: + request (~.securitycenter_service.UpdateExternalSystemRequest): + The request object. Request message for updating a + ExternalSystem resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_external_system.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v1/{external_system.name=folders/*/sources/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v1/{external_system.name=projects/*/sources/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, + ] + request, metadata = self._interceptor.pre_update_external_system(request, metadata) + pb_request = securitycenter_service.UpdateExternalSystemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_external_system.ExternalSystem() + pb_resp = gcs_external_system.ExternalSystem.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_external_system(resp) + return resp + + class _UpdateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the update finding method over HTTP. + + Args: + request (~.securitycenter_service.UpdateFindingRequest): + The request object. Request message for updating or + creating a finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{finding.name=organizations/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v1/{finding.name=folders/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v1/{finding.name=projects/*/sources/*/findings/*}', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_update_finding(request, metadata) + pb_request = securitycenter_service.UpdateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_finding(resp) + return resp + + class _UpdateMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_mute_config.MuteConfig: + r"""Call the update mute config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateMuteConfigRequest): + The request object. Request message for updating a mute + config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{mute_config.name=organizations/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{mute_config.name=folders/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{mute_config.name=projects/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{mute_config.name=organizations/*/locations/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{mute_config.name=folders/*/locations/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{mute_config.name=projects/*/locations/*/muteConfigs/*}', + 'body': 'mute_config', + }, + ] + request, metadata = self._interceptor.pre_update_mute_config(request, metadata) + pb_request = securitycenter_service.UpdateMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_mute_config.MuteConfig() + pb_resp = gcs_mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_mute_config(resp) + return resp + + class _UpdateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the update notification + config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateNotificationConfigRequest): + The request object. Request message for updating a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{notification_config.name=organizations/*/notificationConfigs/*}', + 'body': 'notification_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{notification_config.name=folders/*/notificationConfigs/*}', + 'body': 'notification_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{notification_config.name=projects/*/notificationConfigs/*}', + 'body': 'notification_config', + }, + ] + request, metadata = self._interceptor.pre_update_notification_config(request, metadata) + pb_request = securitycenter_service.UpdateNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_notification_config(resp) + return resp + + class _UpdateOrganizationSettings(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateOrganizationSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateOrganizationSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Call the update organization + settings method over HTTP. + + Args: + request (~.securitycenter_service.UpdateOrganizationSettingsRequest): + The request object. Request message for updating an + organization's 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: + ~.gcs_organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{organization_settings.name=organizations/*/organizationSettings}', + 'body': 'organization_settings', + }, + ] + request, metadata = self._interceptor.pre_update_organization_settings(request, metadata) + pb_request = securitycenter_service.UpdateOrganizationSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_organization_settings.OrganizationSettings() + pb_resp = gcs_organization_settings.OrganizationSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_organization_settings(resp) + return resp + + class _UpdateResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateResourceValueConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateResourceValueConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Call the update resource value + config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateResourceValueConfigRequest): + The request object. Request message to update resource + value config + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_resource_value_config.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{resource_value_config.name=organizations/*/resourceValueConfigs/*}', + 'body': 'resource_value_config', + }, + ] + request, metadata = self._interceptor.pre_update_resource_value_config(request, metadata) + pb_request = securitycenter_service.UpdateResourceValueConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_resource_value_config.ResourceValueConfig() + pb_resp = gcs_resource_value_config.ResourceValueConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_resource_value_config(resp) + return resp + + class _UpdateSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSecurityHealthAnalyticsCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Call the update security health + analytics custom module method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): + The request object. Request message for updating Security + Health Analytics custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{security_health_analytics_custom_module.name=organizations/*/securityHealthAnalyticsSettings/customModules/*}', + 'body': 'security_health_analytics_custom_module', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_health_analytics_custom_module.name=folders/*/securityHealthAnalyticsSettings/customModules/*}', + 'body': 'security_health_analytics_custom_module', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_health_analytics_custom_module.name=projects/*/securityHealthAnalyticsSettings/customModules/*}', + 'body': 'security_health_analytics_custom_module', + }, + ] + request, metadata = self._interceptor.pre_update_security_health_analytics_custom_module(request, metadata) + pb_request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + pb_resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_security_health_analytics_custom_module(resp) + return resp + + class _UpdateSecurityMarks(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSecurityMarks") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSecurityMarksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_security_marks.SecurityMarks: + r"""Call the update security marks method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSecurityMarksRequest): + The request object. Request message for updating a + SecurityMarks resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{security_marks.name=organizations/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_marks.name=folders/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_marks.name=projects/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, + ] + request, metadata = self._interceptor.pre_update_security_marks(request, metadata) + pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_security_marks.SecurityMarks() + pb_resp = gcs_security_marks.SecurityMarks.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_security_marks(resp) + return resp + + class _UpdateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the update source method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSourceRequest): + The request object. Request message for updating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{source.name=organizations/*/sources/*}', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_update_source(request, metadata) + pb_request = securitycenter_service.UpdateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_source(resp) + return resp + + class _ValidateEventThreatDetectionCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("ValidateEventThreatDetectionCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: + r"""Call the validate event threat + detection custom module method over HTTP. + + Args: + request (~.securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): + The request object. Request to validate an Event Threat + Detection custom module. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: + Response to validating an Event + Threat Detection custom module. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}:validateCustomModule', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}:validateCustomModule', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}:validateCustomModule', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_validate_event_threat_detection_custom_module(request, metadata) + pb_request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() + pb_resp = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_validate_event_threat_detection_custom_module(resp) + return resp + + @property + def batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + securitycenter_service.BatchCreateResourceValueConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreateResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + 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._BulkMuteFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], + gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], + gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + 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._DeleteBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], + 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._DeleteEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + 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._DeleteMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + 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._DeleteNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + 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._DeleteResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], + 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._DeleteSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + bigquery_export.BigQueryExport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_effective_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEffectiveEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_effective_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEffectiveSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], + event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + mute_config.MuteConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + resource_value_config.ResourceValueConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + simulation.Simulation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSimulation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + valued_resource.ValuedResource]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetValuedResource(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + securitycenter_service.ListAttackPathsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAttackPaths(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + securitycenter_service.ListBigQueryExportsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBigQueryExports(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDescendantEventThreatDetectionCustomModules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDescendantSecurityHealthAnalyticsCustomModules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_effective_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEffectiveEventThreatDetectionCustomModules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_effective_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEffectiveSecurityHealthAnalyticsCustomModules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], + securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEventThreatDetectionCustomModules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.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_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + securitycenter_service.ListMuteConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMuteConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListNotificationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + securitycenter_service.ListResourceValueConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSecurityHealthAnalyticsCustomModules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + securitycenter_service.ListValuedResourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListValuedResources(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + 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._RunAssetDiscovery(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + 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._SetMute(self._session, self._host, self._interceptor) # type: ignore + + @property + def simulate_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SimulateSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], + gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + gcs_external_system.ExternalSystem]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateExternalSystem(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + gcs_resource_value_config.ResourceValueConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], + gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def validate_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], + securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ValidateEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=organizations/*/operations/*}:cancel', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In 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(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In 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(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), 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(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/operations}', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SecurityCenterRestTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py new file mode 100644 index 000000000000..fae209c726d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py @@ -0,0 +1,440 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .access import ( + Access, + Geolocation, + ServiceAccountDelegationInfo, +) +from .application import ( + Application, +) +from .asset import ( + Asset, +) +from .attack_exposure import ( + AttackExposure, +) +from .attack_path import ( + AttackPath, +) +from .backup_disaster_recovery import ( + BackupDisasterRecovery, +) +from .bigquery_export import ( + BigQueryExport, +) +from .cloud_armor import ( + AdaptiveProtection, + Attack, + CloudArmor, + Requests, + SecurityPolicy, +) +from .cloud_dlp_data_profile import ( + CloudDlpDataProfile, +) +from .cloud_dlp_inspection import ( + CloudDlpInspection, +) +from .compliance import ( + Compliance, +) +from .connection import ( + Connection, +) +from .contact_details import ( + Contact, + ContactDetails, +) +from .container import ( + Container, +) +from .database import ( + Database, +) +from .effective_event_threat_detection_custom_module import ( + EffectiveEventThreatDetectionCustomModule, +) +from .effective_security_health_analytics_custom_module import ( + EffectiveSecurityHealthAnalyticsCustomModule, +) +from .event_threat_detection_custom_module import ( + EventThreatDetectionCustomModule, +) +from .event_threat_detection_custom_module_validation_errors import ( + CustomModuleValidationError, + CustomModuleValidationErrors, + Position, +) +from .exfiltration import ( + ExfilResource, + Exfiltration, +) +from .external_system import ( + ExternalSystem, +) +from .file import ( + File, +) +from .finding import ( + Finding, +) +from .folder import ( + Folder, +) +from .group_membership import ( + GroupMembership, +) +from .iam_binding import ( + IamBinding, +) +from .indicator import ( + Indicator, +) +from .kernel_rootkit import ( + KernelRootkit, +) +from .kubernetes import ( + Kubernetes, +) +from .label import ( + Label, +) +from .load_balancer import ( + LoadBalancer, +) +from .log_entry import ( + CloudLoggingEntry, + LogEntry, +) +from .mitre_attack import ( + MitreAttack, +) +from .mute_config import ( + MuteConfig, +) +from .notebook import ( + Notebook, +) +from .notification_config import ( + NotificationConfig, +) +from .notification_message import ( + NotificationMessage, +) +from .org_policy import ( + OrgPolicy, +) +from .organization_settings import ( + OrganizationSettings, +) +from .process import ( + EnvironmentVariable, + Process, +) +from .resource import ( + AwsMetadata, + AzureMetadata, + Resource, + ResourcePath, + CloudProvider, +) +from .resource_value_config import ( + ResourceValueConfig, + ResourceValue, +) +from .run_asset_discovery_response import ( + RunAssetDiscoveryResponse, +) +from .security_health_analytics_custom_config import ( + CustomConfig, +) +from .security_health_analytics_custom_module import ( + SecurityHealthAnalyticsCustomModule, +) +from .security_marks import ( + SecurityMarks, +) +from .security_posture import ( + SecurityPosture, +) +from .securitycenter_service import ( + BatchCreateResourceValueConfigsRequest, + BatchCreateResourceValueConfigsResponse, + BulkMuteFindingsRequest, + BulkMuteFindingsResponse, + CreateBigQueryExportRequest, + CreateEventThreatDetectionCustomModuleRequest, + CreateFindingRequest, + CreateMuteConfigRequest, + CreateNotificationConfigRequest, + CreateResourceValueConfigRequest, + CreateSecurityHealthAnalyticsCustomModuleRequest, + CreateSourceRequest, + DeleteBigQueryExportRequest, + DeleteEventThreatDetectionCustomModuleRequest, + DeleteMuteConfigRequest, + DeleteNotificationConfigRequest, + DeleteResourceValueConfigRequest, + DeleteSecurityHealthAnalyticsCustomModuleRequest, + GetBigQueryExportRequest, + GetEffectiveEventThreatDetectionCustomModuleRequest, + GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, + GetEventThreatDetectionCustomModuleRequest, + GetMuteConfigRequest, + GetNotificationConfigRequest, + GetOrganizationSettingsRequest, + GetResourceValueConfigRequest, + GetSecurityHealthAnalyticsCustomModuleRequest, + GetSimulationRequest, + GetSourceRequest, + GetValuedResourceRequest, + GroupAssetsRequest, + GroupAssetsResponse, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListAssetsRequest, + ListAssetsResponse, + ListAttackPathsRequest, + ListAttackPathsResponse, + ListBigQueryExportsRequest, + ListBigQueryExportsResponse, + ListDescendantEventThreatDetectionCustomModulesRequest, + ListDescendantEventThreatDetectionCustomModulesResponse, + ListDescendantSecurityHealthAnalyticsCustomModulesRequest, + ListDescendantSecurityHealthAnalyticsCustomModulesResponse, + ListEffectiveEventThreatDetectionCustomModulesRequest, + ListEffectiveEventThreatDetectionCustomModulesResponse, + ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, + ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, + ListEventThreatDetectionCustomModulesRequest, + ListEventThreatDetectionCustomModulesResponse, + ListFindingsRequest, + ListFindingsResponse, + ListMuteConfigsRequest, + ListMuteConfigsResponse, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListResourceValueConfigsRequest, + ListResourceValueConfigsResponse, + ListSecurityHealthAnalyticsCustomModulesRequest, + ListSecurityHealthAnalyticsCustomModulesResponse, + ListSourcesRequest, + ListSourcesResponse, + ListValuedResourcesRequest, + ListValuedResourcesResponse, + RunAssetDiscoveryRequest, + SetFindingStateRequest, + SetMuteRequest, + SimulateSecurityHealthAnalyticsCustomModuleRequest, + SimulateSecurityHealthAnalyticsCustomModuleResponse, + UpdateBigQueryExportRequest, + UpdateEventThreatDetectionCustomModuleRequest, + UpdateExternalSystemRequest, + UpdateFindingRequest, + UpdateMuteConfigRequest, + UpdateNotificationConfigRequest, + UpdateOrganizationSettingsRequest, + UpdateResourceValueConfigRequest, + UpdateSecurityHealthAnalyticsCustomModuleRequest, + UpdateSecurityMarksRequest, + UpdateSourceRequest, + ValidateEventThreatDetectionCustomModuleRequest, + ValidateEventThreatDetectionCustomModuleResponse, +) +from .simulation import ( + Simulation, +) +from .source import ( + Source, +) +from .toxic_combination import ( + ToxicCombination, +) +from .valued_resource import ( + ResourceValueConfigMetadata, + ValuedResource, +) +from .vulnerability import ( + Cve, + Cvssv3, + Package, + Reference, + SecurityBulletin, + Vulnerability, +) + +__all__ = ( + 'Access', + 'Geolocation', + 'ServiceAccountDelegationInfo', + 'Application', + 'Asset', + 'AttackExposure', + 'AttackPath', + 'BackupDisasterRecovery', + 'BigQueryExport', + 'AdaptiveProtection', + 'Attack', + 'CloudArmor', + 'Requests', + 'SecurityPolicy', + 'CloudDlpDataProfile', + 'CloudDlpInspection', + 'Compliance', + 'Connection', + 'Contact', + 'ContactDetails', + 'Container', + 'Database', + 'EffectiveEventThreatDetectionCustomModule', + 'EffectiveSecurityHealthAnalyticsCustomModule', + 'EventThreatDetectionCustomModule', + 'CustomModuleValidationError', + 'CustomModuleValidationErrors', + 'Position', + 'ExfilResource', + 'Exfiltration', + 'ExternalSystem', + 'File', + 'Finding', + 'Folder', + 'GroupMembership', + 'IamBinding', + 'Indicator', + 'KernelRootkit', + 'Kubernetes', + 'Label', + 'LoadBalancer', + 'CloudLoggingEntry', + 'LogEntry', + 'MitreAttack', + 'MuteConfig', + 'Notebook', + 'NotificationConfig', + 'NotificationMessage', + 'OrgPolicy', + 'OrganizationSettings', + 'EnvironmentVariable', + 'Process', + 'AwsMetadata', + 'AzureMetadata', + 'Resource', + 'ResourcePath', + 'CloudProvider', + 'ResourceValueConfig', + 'ResourceValue', + 'RunAssetDiscoveryResponse', + 'CustomConfig', + 'SecurityHealthAnalyticsCustomModule', + 'SecurityMarks', + 'SecurityPosture', + 'BatchCreateResourceValueConfigsRequest', + 'BatchCreateResourceValueConfigsResponse', + 'BulkMuteFindingsRequest', + 'BulkMuteFindingsResponse', + 'CreateBigQueryExportRequest', + 'CreateEventThreatDetectionCustomModuleRequest', + 'CreateFindingRequest', + 'CreateMuteConfigRequest', + 'CreateNotificationConfigRequest', + 'CreateResourceValueConfigRequest', + 'CreateSecurityHealthAnalyticsCustomModuleRequest', + 'CreateSourceRequest', + 'DeleteBigQueryExportRequest', + 'DeleteEventThreatDetectionCustomModuleRequest', + 'DeleteMuteConfigRequest', + 'DeleteNotificationConfigRequest', + 'DeleteResourceValueConfigRequest', + 'DeleteSecurityHealthAnalyticsCustomModuleRequest', + 'GetBigQueryExportRequest', + 'GetEffectiveEventThreatDetectionCustomModuleRequest', + 'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', + 'GetEventThreatDetectionCustomModuleRequest', + 'GetMuteConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetResourceValueConfigRequest', + 'GetSecurityHealthAnalyticsCustomModuleRequest', + 'GetSimulationRequest', + 'GetSourceRequest', + 'GetValuedResourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListAttackPathsRequest', + 'ListAttackPathsResponse', + 'ListBigQueryExportsRequest', + 'ListBigQueryExportsResponse', + 'ListDescendantEventThreatDetectionCustomModulesRequest', + 'ListDescendantEventThreatDetectionCustomModulesResponse', + 'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', + 'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', + 'ListEffectiveEventThreatDetectionCustomModulesRequest', + 'ListEffectiveEventThreatDetectionCustomModulesResponse', + 'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', + 'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', + 'ListEventThreatDetectionCustomModulesRequest', + 'ListEventThreatDetectionCustomModulesResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListMuteConfigsRequest', + 'ListMuteConfigsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListResourceValueConfigsRequest', + 'ListResourceValueConfigsResponse', + 'ListSecurityHealthAnalyticsCustomModulesRequest', + 'ListSecurityHealthAnalyticsCustomModulesResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListValuedResourcesRequest', + 'ListValuedResourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'SetMuteRequest', + 'SimulateSecurityHealthAnalyticsCustomModuleRequest', + 'SimulateSecurityHealthAnalyticsCustomModuleResponse', + 'UpdateBigQueryExportRequest', + 'UpdateEventThreatDetectionCustomModuleRequest', + 'UpdateExternalSystemRequest', + 'UpdateFindingRequest', + 'UpdateMuteConfigRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateResourceValueConfigRequest', + 'UpdateSecurityHealthAnalyticsCustomModuleRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'ValidateEventThreatDetectionCustomModuleRequest', + 'ValidateEventThreatDetectionCustomModuleResponse', + 'Simulation', + 'Source', + 'ToxicCombination', + 'ResourceValueConfigMetadata', + 'ValuedResource', + 'Cve', + 'Cvssv3', + 'Package', + 'Reference', + 'SecurityBulletin', + 'Vulnerability', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py new file mode 100644 index 000000000000..46f1bc1e8a57 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v1', + manifest={ + 'Access', + 'ServiceAccountDelegationInfo', + 'Geolocation', + }, +) + + +class Access(proto.Message): + r"""Represents an access event. + + Attributes: + principal_email (str): + Associated email, such as "foo@google.com". + + The email address of the authenticated user or a service + account acting on behalf of a third party principal making + the request. For third party identity callers, the + ``principal_subject`` field is populated instead of this + field. For privacy reasons, the principal email address is + sometimes redacted. For more information, see `Caller + identities in audit + logs `__. + caller_ip (str): + Caller's IP address, such as "1.1.1.1". + caller_ip_geo (google.cloud.securitycenter_v1.types.Geolocation): + The caller IP's geolocation, which identifies + where the call came from. + user_agent_family (str): + Type of user agent associated with the + finding. For example, an operating system shell + or an embedded or standalone application. + user_agent (str): + The caller's user agent string associated + with the finding. + service_name (str): + This is the API service that the service + account made a call to, e.g. + "iam.googleapis.com". + method_name (str): + The method that the service account called, + e.g. "SetIamPolicy". + principal_subject (str): + A string that represents the principal_subject that is + associated with the identity. Unlike ``principal_email``, + ``principal_subject`` supports principals that aren't + associated with email addresses, such as third party + principals. For most identities, the format is + ``principal://iam.googleapis.com/{identity pool name}/subject/{subject}``. + Some GKE identities, such as GKE_WORKLOAD, FREEFORM, and + GKE_HUB_WORKLOAD, still use the legacy format + ``serviceAccount:{identity pool name}[{subject}]``. + service_account_key_name (str): + The name of the service account key that was used to create + or exchange credentials when authenticating the service + account that made the request. This is a scheme-less URI + full resource name. For example: + + "//iam.googleapis.com/projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}". + service_account_delegation_info (MutableSequence[google.cloud.securitycenter_v1.types.ServiceAccountDelegationInfo]): + The identity delegation history of an authenticated service + account that made the request. The + ``serviceAccountDelegationInfo[]`` object contains + information about the real authorities that try to access + Google Cloud resources by delegating on a service account. + When multiple authorities are present, they are guaranteed + to be sorted based on the original ordering of the identity + delegation events. + user_name (str): + A string that represents a username. The + username provided depends on the type of the + finding and is likely not an IAM principal. For + example, this can be a system username if the + finding is related to a virtual machine, or it + can be an application login username. + """ + + principal_email: str = proto.Field( + proto.STRING, + number=1, + ) + caller_ip: str = proto.Field( + proto.STRING, + number=2, + ) + caller_ip_geo: 'Geolocation' = proto.Field( + proto.MESSAGE, + number=3, + message='Geolocation', + ) + user_agent_family: str = proto.Field( + proto.STRING, + number=4, + ) + user_agent: str = proto.Field( + proto.STRING, + number=12, + ) + service_name: str = proto.Field( + proto.STRING, + number=5, + ) + method_name: str = proto.Field( + proto.STRING, + number=6, + ) + principal_subject: str = proto.Field( + proto.STRING, + number=7, + ) + service_account_key_name: str = proto.Field( + proto.STRING, + number=8, + ) + service_account_delegation_info: MutableSequence['ServiceAccountDelegationInfo'] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='ServiceAccountDelegationInfo', + ) + user_name: str = proto.Field( + proto.STRING, + number=11, + ) + + +class ServiceAccountDelegationInfo(proto.Message): + r"""Identity delegation history of an authenticated service + account. + + Attributes: + principal_email (str): + The email address of a Google account. + principal_subject (str): + A string representing the principal_subject associated with + the identity. As compared to ``principal_email``, supports + principals that aren't associated with email addresses, such + as third party principals. For most identities, the format + will be + ``principal://iam.googleapis.com/{identity pool name}/subjects/{subject}`` + except for some GKE identities (GKE_WORKLOAD, FREEFORM, + GKE_HUB_WORKLOAD) that are still in the legacy format + ``serviceAccount:{identity pool name}[{subject}]`` + """ + + principal_email: str = proto.Field( + proto.STRING, + number=1, + ) + principal_subject: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Geolocation(proto.Message): + r"""Represents a geographical location for a given access. + + Attributes: + region_code (str): + A CLDR. + """ + + region_code: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.py new file mode 100644 index 000000000000..96e0a3cd61dc --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Application', + }, +) + + +class Application(proto.Message): + r"""Represents an application associated with a finding. + + Attributes: + base_uri (str): + The base URI that identifies the network location of the + application in which the vulnerability was detected. For + example, ``http://example.com``. + full_uri (str): + The full URI with payload that can be used to reproduce the + vulnerability. For example, + ``http://example.com?p=aMmYgI6H``. + """ + + base_uri: str = proto.Field( + proto.STRING, + number=1, + ) + full_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py new file mode 100644 index 000000000000..5c4a957c4d1e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py @@ -0,0 +1,227 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1.types import folder +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Asset', + }, +) + + +class Asset(proto.Message): + r"""Security Command Center representation of a Google Cloud + resource. + + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All + modifications to an Asset are only within the context of + Security Command Center and don't affect the referenced Google + Cloud resource. + + Attributes: + name (str): + The relative resource name of this asset. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/assets/{asset_id}". + security_center_properties (google.cloud.securitycenter_v1.types.Asset.SecurityCenterProperties): + Security Command Center managed properties. + These properties are managed by Security Command + Center and cannot be modified by the user. + resource_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Resource managed properties. These properties + are managed and defined by the Google Cloud + resource and cannot be modified by the user. + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): + User specified security marks. These marks + are entirely managed by the user and come from + the SecurityMarks resource that belongs to the + asset. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was last updated + or added in Cloud SCC. + iam_policy (google.cloud.securitycenter_v1.types.Asset.IamPolicy): + Cloud IAM Policy information associated with + the Google Cloud resource described by the + Security Command Center asset. This information + is managed and defined by the Google Cloud + resource and cannot be modified by the user. + canonical_name (str): + The canonical name of the resource. It's either + "organizations/{organization_id}/assets/{asset_id}", + "folders/{folder_id}/assets/{asset_id}" or + "projects/{project_number}/assets/{asset_id}", depending on + the closest CRM ancestor of the resource. + """ + + class SecurityCenterProperties(proto.Message): + r"""Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified by + the user. + + Attributes: + resource_name (str): + The full resource name of the Google Cloud resource this + asset represents. This field is immutable after create time. + See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_type (str): + The type of the Google Cloud resource. + Examples include: APPLICATION, PROJECT, and + ORGANIZATION. This is a case insensitive field + defined by Security Command Center and/or the + producer of the resource and is immutable after + create time. + resource_parent (str): + The full resource name of the immediate parent of the + resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_project (str): + The full resource name of the project the resource belongs + to. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_owners (MutableSequence[str]): + Owners of the Google Cloud resource. + resource_display_name (str): + The user defined display name for this + resource. + resource_parent_display_name (str): + The user defined display name for the parent + of this resource. + resource_project_display_name (str): + The user defined display name for the project + of this resource. + folders (MutableSequence[google.cloud.securitycenter_v1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. + """ + + resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + resource_parent: str = proto.Field( + proto.STRING, + number=3, + ) + resource_project: str = proto.Field( + proto.STRING, + number=4, + ) + resource_owners: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + resource_display_name: str = proto.Field( + proto.STRING, + number=6, + ) + resource_parent_display_name: str = proto.Field( + proto.STRING, + number=7, + ) + resource_project_display_name: str = proto.Field( + proto.STRING, + number=8, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=folder.Folder, + ) + + class IamPolicy(proto.Message): + r"""Cloud IAM Policy information associated with the Google Cloud + resource described by the Security Command Center asset. This + information is managed and defined by the Google Cloud resource + and cannot be modified by the user. + + Attributes: + policy_blob (str): + The JSON representation of the Policy + associated with the asset. See + https://cloud.google.com/iam/reference/rest/v1/Policy + for format details. + """ + + policy_blob: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + security_center_properties: SecurityCenterProperties = proto.Field( + proto.MESSAGE, + number=2, + message=SecurityCenterProperties, + ) + resource_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + iam_policy: IamPolicy = proto.Field( + proto.MESSAGE, + number=11, + message=IamPolicy, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=13, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.py new file mode 100644 index 000000000000..71c641c4f226 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'AttackExposure', + }, +) + + +class AttackExposure(proto.Message): + r"""An attack exposure contains the results of an attack path + simulation run. + + Attributes: + score (float): + A number between 0 (inclusive) and infinity + that represents how important this finding is to + remediate. The higher the score, the more + important it is to remediate. + latest_calculation_time (google.protobuf.timestamp_pb2.Timestamp): + The most recent time the attack exposure was + updated on this finding. + attack_exposure_result (str): + The resource name of the attack path simulation result that + contains the details regarding this attack exposure score. + Example: + ``organizations/123/simulations/456/attackExposureResults/789`` + state (google.cloud.securitycenter_v1.types.AttackExposure.State): + What state this AttackExposure is in. This + captures whether or not an attack exposure has + been calculated or not. + exposed_high_value_resources_count (int): + The number of high value resources that are + exposed as a result of this finding. + exposed_medium_value_resources_count (int): + The number of medium value resources that are + exposed as a result of this finding. + exposed_low_value_resources_count (int): + The number of high value resources that are + exposed as a result of this finding. + """ + class State(proto.Enum): + r"""This enum defines the various states an AttackExposure can be + in. + + Values: + STATE_UNSPECIFIED (0): + The state is not specified. + CALCULATED (1): + The attack exposure has been calculated. + NOT_CALCULATED (2): + The attack exposure has not been calculated. + """ + STATE_UNSPECIFIED = 0 + CALCULATED = 1 + NOT_CALCULATED = 2 + + score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + latest_calculation_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + attack_exposure_result: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + exposed_high_value_resources_count: int = proto.Field( + proto.INT32, + number=5, + ) + exposed_medium_value_resources_count: int = proto.Field( + proto.INT32, + number=6, + ) + exposed_low_value_resources_count: int = proto.Field( + proto.INT32, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py new file mode 100644 index 000000000000..d298b28f7407 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v1', + manifest={ + 'AttackPath', + }, +) + + +class AttackPath(proto.Message): + r"""A path that an attacker could take to reach an exposed + resource. + + Attributes: + name (str): + The attack path name, for example, + ``organizations/12/simulation/34/valuedResources/56/attackPaths/78`` + path_nodes (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode]): + A list of nodes that exist in this attack + path. + edges (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathEdge]): + A list of the edges between nodes in this + attack path. + """ + + class AttackPathNode(proto.Message): + r"""Represents one point that an attacker passes through in this + attack path. + + Attributes: + resource (str): + The name of the resource at this point in the attack path. + The format of the name follows the Cloud Asset Inventory + `resource name + format `__ + resource_type (str): + The `supported resource + type `__ + display_name (str): + Human-readable name of this resource. + associated_findings (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode.PathNodeAssociatedFinding]): + The findings associated with this node in the + attack path. + uuid (str): + Unique id of the attack path node. + attack_steps (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode.AttackStepNode]): + A list of attack step nodes that exist in + this attack path node. + """ + class NodeType(proto.Enum): + r"""The type of the incoming attack step node. + + Values: + NODE_TYPE_UNSPECIFIED (0): + Type not specified + NODE_TYPE_AND (1): + Incoming edge joined with AND + NODE_TYPE_OR (2): + Incoming edge joined with OR + NODE_TYPE_DEFENSE (3): + Incoming edge is defense + NODE_TYPE_ATTACKER (4): + Incoming edge is attacker + """ + NODE_TYPE_UNSPECIFIED = 0 + NODE_TYPE_AND = 1 + NODE_TYPE_OR = 2 + NODE_TYPE_DEFENSE = 3 + NODE_TYPE_ATTACKER = 4 + + class PathNodeAssociatedFinding(proto.Message): + r"""A finding that is associated with this node in the attack + path. + + Attributes: + canonical_finding (str): + Canonical name of the associated findings. Example: + ``organizations/123/sources/456/findings/789`` + finding_category (str): + The additional taxonomy group within findings + from a given source. + name (str): + Full resource name of the finding. + """ + + canonical_finding: str = proto.Field( + proto.STRING, + number=1, + ) + finding_category: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class AttackStepNode(proto.Message): + r"""Detailed steps the attack can take between path nodes. + + Attributes: + uuid (str): + Unique ID for one Node + type_ (google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode.NodeType): + Attack step type. Can be either AND, OR or + DEFENSE + display_name (str): + User friendly name of the attack step + labels (MutableMapping[str, str]): + Attack step labels for metadata + description (str): + Attack step description + """ + + uuid: str = proto.Field( + proto.STRING, + number=1, + ) + type_: 'AttackPath.AttackPathNode.NodeType' = proto.Field( + proto.ENUM, + number=2, + enum='AttackPath.AttackPathNode.NodeType', + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + + resource: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + associated_findings: MutableSequence['AttackPath.AttackPathNode.PathNodeAssociatedFinding'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AttackPath.AttackPathNode.PathNodeAssociatedFinding', + ) + uuid: str = proto.Field( + proto.STRING, + number=5, + ) + attack_steps: MutableSequence['AttackPath.AttackPathNode.AttackStepNode'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='AttackPath.AttackPathNode.AttackStepNode', + ) + + class AttackPathEdge(proto.Message): + r"""Represents a connection between a source node and a + destination node in this attack path. + + Attributes: + source (str): + The attack node uuid of the source node. + destination (str): + The attack node uuid of the destination node. + """ + + source: str = proto.Field( + proto.STRING, + number=1, + ) + destination: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + path_nodes: MutableSequence[AttackPathNode] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=AttackPathNode, + ) + edges: MutableSequence[AttackPathEdge] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=AttackPathEdge, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py new file mode 100644 index 000000000000..2497cff8afd8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v1', + manifest={ + 'BackupDisasterRecovery', + }, +) + + +class BackupDisasterRecovery(proto.Message): + r"""Information related to Google Cloud Backup and DR Service + findings. + + Attributes: + backup_template (str): + The name of a Backup and DR template which comprises one or + more backup policies. See the `Backup and DR + documentation `__ + for more information. For example, ``snap-ov``. + policies (MutableSequence[str]): + The names of Backup and DR policies that are associated with + a template and that define when to run a backup, how + frequently to run a backup, and how long to retain the + backup image. For example, ``onvaults``. + host (str): + The name of a Backup and DR host, which is managed by the + backup and recovery appliance and known to the management + console. The host can be of type Generic (for example, + Compute Engine, SQL Server, Oracle DB, SMB file system, + etc.), vCenter, or an ESX server. See the `Backup and DR + documentation on + hosts `__ + for more information. For example, ``centos7-01``. + applications (MutableSequence[str]): + The names of Backup and DR applications. An application is a + VM, database, or file system on a managed host monitored by + a backup and recovery appliance. For example, + ``centos7-01-vol00``, ``centos7-01-vol01``, + ``centos7-01-vol02``. + storage_pool (str): + The name of the Backup and DR storage pool that the backup + and recovery appliance is storing data in. The storage pool + could be of type Cloud, Primary, Snapshot, or OnVault. See + the `Backup and DR documentation on storage + pools `__. + For example, ``DiskPoolOne``. + policy_options (MutableSequence[str]): + The names of Backup and DR advanced policy options of a + policy applying to an application. See the `Backup and DR + documentation on policy + options `__. + For example, ``skipofflineappsincongrp, nounmap``. + profile (str): + The name of the Backup and DR resource profile that + specifies the storage media for backups of application and + VM data. See the `Backup and DR documentation on + profiles `__. + For example, ``GCP``. + appliance (str): + The name of the Backup and DR appliance that captures, + moves, and manages the lifecycle of backup data. For + example, ``backup-server-57137``. + backup_type (str): + The backup type of the Backup and DR image. For example, + ``Snapshot``, ``Remote Snapshot``, ``OnVault``. + backup_create_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp at which the Backup and DR + backup was created. + """ + + backup_template: str = proto.Field( + proto.STRING, + number=1, + ) + policies: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + host: str = proto.Field( + proto.STRING, + number=3, + ) + applications: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + storage_pool: str = proto.Field( + proto.STRING, + number=5, + ) + policy_options: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + profile: str = proto.Field( + proto.STRING, + number=7, + ) + appliance: str = proto.Field( + proto.STRING, + number=8, + ) + backup_type: str = proto.Field( + proto.STRING, + number=9, + ) + backup_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py new file mode 100644 index 000000000000..9e8288f7fd7b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py @@ -0,0 +1,135 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v1', + manifest={ + 'BigQueryExport', + }, +) + + +class BigQueryExport(proto.Message): + r"""Configures how to deliver Findings to BigQuery Instance. + + Attributes: + name (str): + The relative resource name of this export. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name. + Example format: + "organizations/{organization_id}/bigQueryExports/{export_id}" + Example format: + "folders/{folder_id}/bigQueryExports/{export_id}" Example + format: "projects/{project_id}/bigQueryExports/{export_id}" + This field is provided in responses, and is ignored when + provided in create requests. + description (str): + The description of the export (max of 1024 + characters). + filter (str): + Expression that defines the filter to apply across + create/update events of findings. The expression is a list + of zero or more restrictions combined via logical operators + ``AND`` and ``OR``. Parentheses are supported, and ``OR`` + has higher precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + dataset (str): + The dataset to write findings' updates to. Its format is + "projects/[project_id]/datasets/[bigquery_dataset_id]". + BigQuery Dataset unique ID must contain only letters (a-z, + A-Z), numbers (0-9), or underscores (_). + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the BigQuery + export was created. This field is set by the + server and will be ignored if provided on export + on creation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time at which + the BigQuery export was updated. This field is + set by the server and will be ignored if + provided on export creation or update. + most_recent_editor (str): + Output only. Email address of the user who + last edited the BigQuery export. This field is + set by the server and will be ignored if + provided on export creation or update. + principal (str): + Output only. The service account that needs + permission to create table and upload data to + the BigQuery dataset. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + dataset: 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, + ) + most_recent_editor: str = proto.Field( + proto.STRING, + number=7, + ) + principal: str = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.py new file mode 100644 index 000000000000..45b7e2fb7d51 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.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.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'CloudArmor', + 'SecurityPolicy', + 'Requests', + 'AdaptiveProtection', + 'Attack', + }, +) + + +class CloudArmor(proto.Message): + r"""Fields related to Google Cloud Armor findings. + + Attributes: + security_policy (google.cloud.securitycenter_v1.types.SecurityPolicy): + Information about the `Google Cloud Armor security + policy `__ + relevant to the finding. + requests (google.cloud.securitycenter_v1.types.Requests): + Information about incoming requests evaluated by `Google + Cloud Armor security + policies `__. + adaptive_protection (google.cloud.securitycenter_v1.types.AdaptiveProtection): + Information about potential Layer 7 DDoS attacks identified + by `Google Cloud Armor Adaptive + Protection `__. + attack (google.cloud.securitycenter_v1.types.Attack): + Information about DDoS attack volume and + classification. + threat_vector (str): + Distinguish between volumetric & protocol DDoS attack and + application layer attacks. For example, "L3_4" for Layer 3 + and Layer 4 DDoS attacks, or "L_7" for Layer 7 DDoS attacks. + duration (google.protobuf.duration_pb2.Duration): + Duration of attack from the start until the + current moment (updated every 5 minutes). + """ + + security_policy: 'SecurityPolicy' = proto.Field( + proto.MESSAGE, + number=1, + message='SecurityPolicy', + ) + requests: 'Requests' = proto.Field( + proto.MESSAGE, + number=2, + message='Requests', + ) + adaptive_protection: 'AdaptiveProtection' = proto.Field( + proto.MESSAGE, + number=3, + message='AdaptiveProtection', + ) + attack: 'Attack' = proto.Field( + proto.MESSAGE, + number=4, + message='Attack', + ) + threat_vector: str = proto.Field( + proto.STRING, + number=5, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + + +class SecurityPolicy(proto.Message): + r"""Information about the `Google Cloud Armor security + policy `__ + relevant to the finding. + + Attributes: + name (str): + The name of the Google Cloud Armor security + policy, for example, "my-security-policy". + type_ (str): + The type of Google Cloud Armor security + policy for example, 'backend security policy', + 'edge security policy', 'network edge security + policy', or 'always-on DDoS protection'. + preview (bool): + Whether or not the associated rule or policy + is in preview mode. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + preview: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class Requests(proto.Message): + r"""Information about the requests relevant to the finding. + + Attributes: + ratio (float): + For 'Increasing deny ratio', the ratio is the + denied traffic divided by the allowed traffic. + For 'Allowed traffic spike', the ratio is the + allowed traffic in the short term divided by + allowed traffic in the long term. + short_term_allowed (int): + Allowed RPS (requests per second) in the + short term. + long_term_allowed (int): + Allowed RPS (requests per second) over the + long term. + long_term_denied (int): + Denied RPS (requests per second) over the + long term. + """ + + ratio: float = proto.Field( + proto.DOUBLE, + number=1, + ) + short_term_allowed: int = proto.Field( + proto.INT32, + number=2, + ) + long_term_allowed: int = proto.Field( + proto.INT32, + number=3, + ) + long_term_denied: int = proto.Field( + proto.INT32, + number=4, + ) + + +class AdaptiveProtection(proto.Message): + r"""Information about `Google Cloud Armor Adaptive + Protection `__. + + Attributes: + confidence (float): + A score of 0 means that there is low confidence that the + detected event is an actual attack. A score of 1 means that + there is high confidence that the detected event is an + attack. See the `Adaptive Protection + documentation `__ + for further explanation. + """ + + confidence: float = proto.Field( + proto.DOUBLE, + number=1, + ) + + +class Attack(proto.Message): + r"""Information about DDoS attack volume and classification. + + Attributes: + volume_pps (int): + Total PPS (packets per second) volume of + attack. + volume_bps (int): + Total BPS (bytes per second) volume of + attack. + classification (str): + Type of attack, for example, 'SYN-flood', + 'NTP-udp', or 'CHARGEN-udp'. + """ + + volume_pps: int = proto.Field( + proto.INT32, + number=1, + ) + volume_bps: int = proto.Field( + proto.INT32, + number=2, + ) + classification: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.py new file mode 100644 index 000000000000..52cece2651fc --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.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.cloud.securitycenter.v1', + manifest={ + 'CloudDlpDataProfile', + }, +) + + +class CloudDlpDataProfile(proto.Message): + r"""The `data + profile `__ + associated with the finding. + + Attributes: + data_profile (str): + Name of the data profile, for example, + ``projects/123/locations/europe/tableProfiles/8383929``. + parent_type (google.cloud.securitycenter_v1.types.CloudDlpDataProfile.ParentType): + The resource hierarchy level at which the + data profile was generated. + """ + class ParentType(proto.Enum): + r"""Parents for configurations that produce data profile + findings. + + Values: + PARENT_TYPE_UNSPECIFIED (0): + Unspecified parent type. + ORGANIZATION (1): + Organization-level configurations. + PROJECT (2): + Project-level configurations. + """ + PARENT_TYPE_UNSPECIFIED = 0 + ORGANIZATION = 1 + PROJECT = 2 + + data_profile: str = proto.Field( + proto.STRING, + number=1, + ) + parent_type: ParentType = proto.Field( + proto.ENUM, + number=2, + enum=ParentType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.py new file mode 100644 index 000000000000..46b9848965a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'CloudDlpInspection', + }, +) + + +class CloudDlpInspection(proto.Message): + r"""Details about the Cloud Data Loss Prevention (Cloud DLP) `inspection + job `__ + that produced the finding. + + Attributes: + inspect_job (str): + Name of the inspection job, for example, + ``projects/123/locations/europe/dlpJobs/i-8383929``. + info_type (str): + The type of information (or + `infoType `__) + found, for example, ``EMAIL_ADDRESS`` or ``STREET_ADDRESS``. + info_type_count (int): + The number of times Cloud DLP found this + infoType within this job and resource. + full_scan (bool): + Whether Cloud DLP scanned the complete + resource or a sampled subset. + """ + + inspect_job: str = proto.Field( + proto.STRING, + number=1, + ) + info_type: str = proto.Field( + proto.STRING, + number=2, + ) + info_type_count: int = proto.Field( + proto.INT64, + number=3, + ) + full_scan: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.py new file mode 100644 index 000000000000..432ca7841d82 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Compliance', + }, +) + + +class Compliance(proto.Message): + r"""Contains compliance information about a security standard + indicating unmet recommendations. + + Attributes: + standard (str): + Industry-wide compliance standards or + benchmarks, such as CIS, PCI, and OWASP. + version (str): + Version of the standard or benchmark, for + example, 1.1 + ids (MutableSequence[str]): + Policies within the standard or benchmark, + for example, A.12.4.1 + """ + + standard: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.py new file mode 100644 index 000000000000..0f36fbdfd761 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.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.cloud.securitycenter.v1', + manifest={ + 'Connection', + }, +) + + +class Connection(proto.Message): + r"""Contains information about the IP connection associated with + the finding. + + Attributes: + destination_ip (str): + Destination IP address. Not present for + sockets that are listening and not connected. + destination_port (int): + Destination port. Not present for sockets + that are listening and not connected. + source_ip (str): + Source IP address. + source_port (int): + Source port. + protocol (google.cloud.securitycenter_v1.types.Connection.Protocol): + IANA Internet Protocol Number such as TCP(6) + and UDP(17). + """ + class Protocol(proto.Enum): + r"""IANA Internet Protocol Number such as TCP(6) and UDP(17). + + Values: + PROTOCOL_UNSPECIFIED (0): + Unspecified protocol (not HOPOPT). + ICMP (1): + Internet Control Message Protocol. + TCP (6): + Transmission Control Protocol. + UDP (17): + User Datagram Protocol. + GRE (47): + Generic Routing Encapsulation. + ESP (50): + Encap Security Payload. + """ + PROTOCOL_UNSPECIFIED = 0 + ICMP = 1 + TCP = 6 + UDP = 17 + GRE = 47 + ESP = 50 + + destination_ip: str = proto.Field( + proto.STRING, + number=1, + ) + destination_port: int = proto.Field( + proto.INT32, + number=2, + ) + source_ip: str = proto.Field( + proto.STRING, + number=3, + ) + source_port: int = proto.Field( + proto.INT32, + number=4, + ) + protocol: Protocol = proto.Field( + proto.ENUM, + number=5, + enum=Protocol, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.py new file mode 100644 index 000000000000..7fdd88c15c7e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'ContactDetails', + 'Contact', + }, +) + + +class ContactDetails(proto.Message): + r"""Details about specific contacts + + Attributes: + contacts (MutableSequence[google.cloud.securitycenter_v1.types.Contact]): + A list of contacts + """ + + contacts: MutableSequence['Contact'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Contact', + ) + + +class Contact(proto.Message): + r"""The email address of a contact. + + Attributes: + email (str): + An email address. For example, "``person123@company.com``". + """ + + email: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.py new file mode 100644 index 000000000000..d953244d3583 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v1.types import label +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Container', + }, +) + + +class Container(proto.Message): + r"""Container associated with the finding. + + Attributes: + name (str): + Name of the container. + uri (str): + Container image URI provided when configuring + a pod or container. This string can identify a + container image version using mutable tags. + image_id (str): + Optional container image ID, if provided by + the container runtime. Uniquely identifies the + container image launched using a container image + digest. + labels (MutableSequence[google.cloud.securitycenter_v1.types.Label]): + Container labels, as provided by the + container runtime. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time that the container was created. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + image_id: str = proto.Field( + proto.STRING, + number=3, + ) + labels: MutableSequence[label.Label] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=label.Label, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.py new file mode 100644 index 000000000000..3372ba324532 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Database', + }, +) + + +class Database(proto.Message): + r"""Represents database access information, such as queries. A database + may be a sub-resource of an instance (as in the case of Cloud SQL + instances or Cloud Spanner instances), or the database instance + itself. Some database resources might not have the `full resource + name `__ populated + because these resource types, such as Cloud SQL databases, are not + yet supported by Cloud Asset Inventory. In these cases only the + display name is provided. + + Attributes: + name (str): + Some database resources may not have the `full resource + name `__ + populated because these resource types are not yet supported + by Cloud Asset Inventory (e.g. Cloud SQL databases). In + these cases only the display name will be provided. The + `full resource + name `__ of + the database that the user connected to, if it is supported + by Cloud Asset Inventory. + display_name (str): + The human-readable name of the database that + the user connected to. + user_name (str): + The username used to connect to the database. + The username might not be an IAM principal and + does not have a set format. + query (str): + The SQL statement that is associated with the + database access. + grantees (MutableSequence[str]): + The target usernames, roles, or groups of an + SQL privilege grant, which is not an IAM policy + change. + version (str): + The version of the database, for example, POSTGRES_14. See + `the complete + list `__. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + user_name: str = proto.Field( + proto.STRING, + number=3, + ) + query: str = proto.Field( + proto.STRING, + number=4, + ) + grantees: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + version: str = proto.Field( + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.py new file mode 100644 index 000000000000..ba51ed0b1ec6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.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.cloud.securitycenter.v1', + manifest={ + 'EffectiveEventThreatDetectionCustomModule', + }, +) + + +class EffectiveEventThreatDetectionCustomModule(proto.Message): + r"""An EffectiveEventThreatDetectionCustomModule is the representation + of an Event Threat Detection custom module at a specified level of + the resource hierarchy: organization, folder, or project. If a + custom module is inherited from a parent organization or folder, the + value of the ``enablement_state`` property in + EffectiveEventThreatDetectionCustomModule is set to the value that + is effective in the parent, instead of ``INHERITED``. For example, + if the module is enabled in a parent organization or folder, the + effective ``enablement_state`` for the module in all child folders + or projects is also ``enabled``. + EffectiveEventThreatDetectionCustomModule is read-only. + + Attributes: + name (str): + Output only. The resource name of the effective ETD custom + module. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + config (google.protobuf.struct_pb2.Struct): + Output only. Config for the effective module. + enablement_state (google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule.EnablementState): + Output only. The effective state of + enablement for the module at the given level of + the hierarchy. + type_ (str): + Output only. Type for the module. e.g. CONFIGURABLE_BAD_IP. + display_name (str): + Output only. The human readable name to be + displayed for the module. + description (str): + Output only. The description for the module. + """ + class EnablementState(proto.Enum): + r"""The enablement state of the module. + + Values: + ENABLEMENT_STATE_UNSPECIFIED (0): + Unspecified enablement state. + ENABLED (1): + The module is enabled at the given level. + DISABLED (2): + The module is disabled at the given level. + """ + ENABLEMENT_STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + config: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + enablement_state: EnablementState = proto.Field( + proto.ENUM, + number=3, + enum=EnablementState, + ) + type_: str = proto.Field( + proto.STRING, + number=4, + ) + display_name: str = proto.Field( + proto.STRING, + number=5, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.py new file mode 100644 index 000000000000..2396c38d1aaf --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'EffectiveSecurityHealthAnalyticsCustomModule', + }, +) + + +class EffectiveSecurityHealthAnalyticsCustomModule(proto.Message): + r"""An EffectiveSecurityHealthAnalyticsCustomModule is the + representation of a Security Health Analytics custom module at a + specified level of the resource hierarchy: organization, folder, or + project. If a custom module is inherited from a parent organization + or folder, the value of the ``enablementState`` property in + EffectiveSecurityHealthAnalyticsCustomModule is set to the value + that is effective in the parent, instead of ``INHERITED``. For + example, if the module is enabled in a parent organization or + folder, the effective enablement_state for the module in all child + folders or projects is also ``enabled``. + EffectiveSecurityHealthAnalyticsCustomModule is read-only. + + Attributes: + name (str): + Output only. The resource name of the custom + module. Its format is + "organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}", + or + "folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}", + or + "projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}". + custom_config (google.cloud.securitycenter_v1.types.CustomConfig): + Output only. The user-specified configuration + for the module. + enablement_state (google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState): + Output only. The effective state of + enablement for the module at the given level of + the hierarchy. + display_name (str): + Output only. The display name for the custom + module. The name must be between 1 and 128 + characters, start with a lowercase letter, and + contain alphanumeric characters or underscores + only. + """ + class EnablementState(proto.Enum): + r"""The enablement state of the module. + + Values: + ENABLEMENT_STATE_UNSPECIFIED (0): + Unspecified enablement state. + ENABLED (1): + The module is enabled at the given level. + DISABLED (2): + The module is disabled at the given level. + """ + ENABLEMENT_STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + custom_config: security_health_analytics_custom_config.CustomConfig = proto.Field( + proto.MESSAGE, + number=2, + message=security_health_analytics_custom_config.CustomConfig, + ) + enablement_state: EnablementState = proto.Field( + proto.ENUM, + number=3, + enum=EnablementState, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.py new file mode 100644 index 000000000000..6b6e83626bb9 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'EventThreatDetectionCustomModule', + }, +) + + +class EventThreatDetectionCustomModule(proto.Message): + r"""Represents an instance of an Event Threat Detection custom + module, including its full module name, display name, enablement + state, and last updated time. You can create a custom module at + the organization, folder, or project level. Custom modules that + you create at the organization or folder level are inherited by + child folders and projects. + + Attributes: + name (str): + Immutable. The resource name of the Event Threat Detection + custom module. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. + config (google.protobuf.struct_pb2.Struct): + Config for the module. For the resident + module, its config value is defined at this + level. For the inherited module, its config + value is inherited from the ancestor module. + ancestor_module (str): + Output only. The closest ancestor module that + this module inherits the enablement state from. + The format is the same as the + EventThreatDetectionCustomModule resource name. + enablement_state (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule.EnablementState): + The state of enablement for the module at the + given level of the hierarchy. + type_ (str): + Type for the module. e.g. CONFIGURABLE_BAD_IP. + display_name (str): + The human readable name to be displayed for + the module. + description (str): + The description for the module. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the module was last + updated. + last_editor (str): + Output only. The editor the module was last + updated by. + """ + class EnablementState(proto.Enum): + r"""The enablement state of the module. + + Values: + ENABLEMENT_STATE_UNSPECIFIED (0): + Unspecified enablement state. + ENABLED (1): + The module is enabled at the given level. + DISABLED (2): + The module is disabled at the given level. + INHERITED (3): + When the enablement state is inherited. + """ + ENABLEMENT_STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + INHERITED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + config: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + ancestor_module: str = proto.Field( + proto.STRING, + number=3, + ) + enablement_state: EnablementState = proto.Field( + proto.ENUM, + number=4, + enum=EnablementState, + ) + type_: str = proto.Field( + proto.STRING, + number=5, + ) + display_name: str = proto.Field( + proto.STRING, + number=6, + ) + description: str = proto.Field( + proto.STRING, + number=7, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + last_editor: str = proto.Field( + proto.STRING, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.py new file mode 100644 index 000000000000..12b7e815de3f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'CustomModuleValidationErrors', + 'CustomModuleValidationError', + 'Position', + }, +) + + +class CustomModuleValidationErrors(proto.Message): + r"""A list of zero or more errors encountered while validating + the uploaded configuration of an Event Threat Detection Custom + Module. + + Attributes: + errors (MutableSequence[google.cloud.securitycenter_v1.types.CustomModuleValidationError]): + + """ + + errors: MutableSequence['CustomModuleValidationError'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CustomModuleValidationError', + ) + + +class CustomModuleValidationError(proto.Message): + r"""An error encountered while validating the uploaded + configuration of an Event Threat Detection Custom Module. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + description (str): + A description of the error, suitable for + human consumption. Required. + field_path (str): + The path, in RFC 8901 JSON Pointer format, to + the field that failed validation. This may be + left empty if no specific field is affected. + start (google.cloud.securitycenter_v1.types.Position): + The initial position of the error in the + uploaded text version of the module. This field + may be omitted if no specific position applies, + or if one could not be computed. + + This field is a member of `oneof`_ ``_start``. + end (google.cloud.securitycenter_v1.types.Position): + The end position of the error in the uploaded + text version of the module. This field may be + omitted if no specific position applies, or if + one could not be computed.. + + This field is a member of `oneof`_ ``_end``. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + field_path: str = proto.Field( + proto.STRING, + number=2, + ) + start: 'Position' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='Position', + ) + end: 'Position' = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message='Position', + ) + + +class Position(proto.Message): + r"""A position in the uploaded text version of a module. + + Attributes: + line_number (int): + + column_number (int): + + """ + + line_number: int = proto.Field( + proto.INT32, + number=1, + ) + column_number: int = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.py new file mode 100644 index 000000000000..68a2b9fd7d98 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Exfiltration', + 'ExfilResource', + }, +) + + +class Exfiltration(proto.Message): + r"""Exfiltration represents a data exfiltration attempt from one or more + sources to one or more targets. The ``sources`` attribute lists the + sources of the exfiltrated data. The ``targets`` attribute lists the + destinations the data was copied to. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v1.types.ExfilResource]): + If there are multiple sources, then the data + is considered "joined" between them. For + instance, BigQuery can join multiple tables, and + each table would be considered a source. + targets (MutableSequence[google.cloud.securitycenter_v1.types.ExfilResource]): + If there are multiple targets, each target + would get a complete copy of the "joined" source + data. + total_exfiltrated_bytes (int): + Total exfiltrated bytes processed for the + entire job. + """ + + sources: MutableSequence['ExfilResource'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ExfilResource', + ) + targets: MutableSequence['ExfilResource'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ExfilResource', + ) + total_exfiltrated_bytes: int = proto.Field( + proto.INT64, + number=3, + ) + + +class ExfilResource(proto.Message): + r"""Resource where data was exfiltrated from or exfiltrated to. + + Attributes: + name (str): + The resource's `full resource + name `__. + components (MutableSequence[str]): + Subcomponents of the asset that was + exfiltrated, like URIs used during exfiltration, + table names, databases, and filenames. For + example, multiple tables might have been + exfiltrated from the same Cloud SQL instance, or + multiple files might have been exfiltrated from + the same Cloud Storage bucket. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + components: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py new file mode 100644 index 000000000000..50a7a7e921f6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v1', + manifest={ + 'ExternalSystem', + }, +) + + +class ExternalSystem(proto.Message): + r"""Representation of third party SIEM/SOAR fields within SCC. + + Attributes: + name (str): + Full resource name of the external system, + for example: + "organizations/1234/sources/5678/findings/123456/externalSystems/jira", + "folders/1234/sources/5678/findings/123456/externalSystems/jira", + "projects/1234/sources/5678/findings/123456/externalSystems/jira". + assignees (MutableSequence[str]): + References primary/secondary etc assignees in + the external system. + external_uid (str): + The identifier that's used to track the + finding's corresponding case in the external + system. + status (str): + The most recent status of the finding's + corresponding case, as reported by the external + system. + external_system_update_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was last updated, as + reported by the external system. + case_uri (str): + The link to the finding's corresponding case + in the external system. + case_priority (str): + The priority of the finding's corresponding + case in the external system. + case_sla (google.protobuf.timestamp_pb2.Timestamp): + The SLA of the finding's corresponding case + in the external system. + case_create_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was created, as + reported by the external system. + case_close_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was closed, as + reported by the external system. + ticket_info (google.cloud.securitycenter_v1.types.ExternalSystem.TicketInfo): + Information about the ticket, if any, that is + being used to track the resolution of the issue + that is identified by this finding. + """ + + class TicketInfo(proto.Message): + r"""Information about the ticket, if any, that is being used to + track the resolution of the issue that is identified by this + finding. + + Attributes: + id (str): + The identifier of the ticket in the ticket + system. + assignee (str): + The assignee of the ticket in the ticket + system. + description (str): + The description of the ticket in the ticket + system. + uri (str): + The link to the ticket in the ticket system. + status (str): + The latest status of the ticket, as reported + by the ticket system. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the ticket was last updated, as + reported by the ticket system. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + assignee: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + uri: str = proto.Field( + proto.STRING, + number=4, + ) + status: str = proto.Field( + proto.STRING, + number=5, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + assignees: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + external_uid: str = proto.Field( + proto.STRING, + number=3, + ) + status: str = proto.Field( + proto.STRING, + number=4, + ) + external_system_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + case_uri: str = proto.Field( + proto.STRING, + number=6, + ) + case_priority: str = proto.Field( + proto.STRING, + number=7, + ) + case_sla: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + case_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + case_close_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + ticket_info: TicketInfo = proto.Field( + proto.MESSAGE, + number=8, + message=TicketInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.py new file mode 100644 index 000000000000..017abee53151 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'File', + }, +) + + +class File(proto.Message): + r"""File information about the related binary/library used by an + executable, or the script used by a script interpreter + + Attributes: + path (str): + Absolute path of the file as a JSON encoded + string. + size (int): + Size of the file in bytes. + sha256 (str): + SHA256 hash of the first hashed_size bytes of the file + encoded as a hex string. If hashed_size == size, sha256 + represents the SHA256 hash of the entire file. + hashed_size (int): + The length in bytes of the file prefix that was hashed. If + hashed_size == size, any hashes reported represent the + entire file. + partially_hashed (bool): + True when the hash covers only a prefix of + the file. + contents (str): + Prefix of the file contents as a JSON-encoded + string. + disk_path (google.cloud.securitycenter_v1.types.File.DiskPath): + Path of the file in terms of underlying + disk/partition identifiers. + """ + + class DiskPath(proto.Message): + r"""Path of the file in terms of underlying disk/partition + identifiers. + + Attributes: + partition_uuid (str): + UUID of the partition (format + https://wiki.archlinux.org/title/persistent_block_device_naming#by-uuid) + relative_path (str): + Relative path of the file in the partition as a JSON encoded + string. Example: /home/user1/executable_file.sh + """ + + partition_uuid: str = proto.Field( + proto.STRING, + number=1, + ) + relative_path: str = proto.Field( + proto.STRING, + number=2, + ) + + path: str = proto.Field( + proto.STRING, + number=1, + ) + size: int = proto.Field( + proto.INT64, + number=2, + ) + sha256: str = proto.Field( + proto.STRING, + number=3, + ) + hashed_size: int = proto.Field( + proto.INT64, + number=4, + ) + partially_hashed: bool = proto.Field( + proto.BOOL, + number=5, + ) + contents: str = proto.Field( + proto.STRING, + number=6, + ) + disk_path: DiskPath = proto.Field( + proto.MESSAGE, + number=7, + message=DiskPath, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py new file mode 100644 index 000000000000..0d3897e0092f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v1.types import access as gcs_access +from google.cloud.securitycenter_v1.types import application as gcs_application +from google.cloud.securitycenter_v1.types import attack_exposure as gcs_attack_exposure +from google.cloud.securitycenter_v1.types import backup_disaster_recovery as gcs_backup_disaster_recovery +from google.cloud.securitycenter_v1.types import cloud_armor as gcs_cloud_armor +from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile as gcs_cloud_dlp_data_profile +from google.cloud.securitycenter_v1.types import cloud_dlp_inspection as gcs_cloud_dlp_inspection +from google.cloud.securitycenter_v1.types import compliance +from google.cloud.securitycenter_v1.types import connection +from google.cloud.securitycenter_v1.types import contact_details +from google.cloud.securitycenter_v1.types import container +from google.cloud.securitycenter_v1.types import database as gcs_database +from google.cloud.securitycenter_v1.types import exfiltration as gcs_exfiltration +from google.cloud.securitycenter_v1.types import external_system +from google.cloud.securitycenter_v1.types import file +from google.cloud.securitycenter_v1.types import group_membership +from google.cloud.securitycenter_v1.types import iam_binding +from google.cloud.securitycenter_v1.types import indicator as gcs_indicator +from google.cloud.securitycenter_v1.types import kernel_rootkit as gcs_kernel_rootkit +from google.cloud.securitycenter_v1.types import kubernetes as gcs_kubernetes +from google.cloud.securitycenter_v1.types import load_balancer +from google.cloud.securitycenter_v1.types import log_entry +from google.cloud.securitycenter_v1.types import mitre_attack as gcs_mitre_attack +from google.cloud.securitycenter_v1.types import notebook as gcs_notebook +from google.cloud.securitycenter_v1.types import org_policy +from google.cloud.securitycenter_v1.types import process +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import security_posture as gcs_security_posture +from google.cloud.securitycenter_v1.types import toxic_combination as gcs_toxic_combination +from google.cloud.securitycenter_v1.types import vulnerability as gcs_vulnerability +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + + A finding is a record of assessment data like security, risk, + health, or privacy, that is ingested into Security Command + Center for presentation, notification, analysis, policy testing, + and enforcement. For example, a cross-site scripting (XSS) + vulnerability in an App Engine application is a finding. + + Attributes: + name (str): + The `relative resource + name `__ + of the finding. Example: + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}", + "projects/{project_id}/sources/{source_id}/findings/{finding_id}". + parent (str): + The relative resource name of the source the finding belongs + to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. For example: + "organizations/{organization_id}/sources/{source_id}". + resource_name (str): + For findings on Google Cloud resources, the full resource + name of the Google Cloud resource this finding is for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + This field is immutable after creation time. + state (google.cloud.securitycenter_v1.types.Finding.State): + The state of the finding. + category (str): + The additional taxonomy group within findings from a given + source. This field is immutable after creation time. + Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (google.protobuf.timestamp_pb2.Timestamp): + The time the finding was first detected. If + an existing finding is updated, then this is the + time the update occurred. For example, if the + finding represents an open firewall, this + property captures the time the detector believes + the firewall became open. The accuracy is + determined by the detector. If the finding is + later resolved, then this time reflects when the + finding was resolved. This must not be set to a + value greater than the current timestamp. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the finding was created in + Security Command Center. + severity (google.cloud.securitycenter_v1.types.Finding.Severity): + The severity of the finding. This field is + managed by the source that writes the finding. + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" + or + "projects/{project_number}/sources/{source_id}/findings/{finding_id}", + depending on the closest CRM ancestor of the resource + associated with the finding. + mute (google.cloud.securitycenter_v1.types.Finding.Mute): + Indicates the mute state of a finding (either + muted, unmuted or undefined). Unlike other + attributes of a finding, a finding provider + shouldn't set the value of mute. + finding_class (google.cloud.securitycenter_v1.types.Finding.FindingClass): + The class of the finding. + indicator (google.cloud.securitycenter_v1.types.Indicator): + Represents what's commonly known as an *indicator of + compromise* (IoC) in computer forensics. This is an artifact + observed on a network or in an operating system that, with + high confidence, indicates a computer intrusion. For more + information, see `Indicator of + compromise `__. + vulnerability (google.cloud.securitycenter_v1.types.Vulnerability): + Represents vulnerability-specific fields like + CVE and CVSS scores. CVE stands for Common + Vulnerabilities and Exposures + (https://cve.mitre.org/about/) + mute_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time this + finding was muted or unmuted. + external_systems (MutableMapping[str, google.cloud.securitycenter_v1.types.ExternalSystem]): + Output only. Third party SIEM/SOAR fields + within SCC, contains external system information + and external system finding fields. + mitre_attack (google.cloud.securitycenter_v1.types.MitreAttack): + MITRE ATT&CK tactics and techniques related + to this finding. See: https://attack.mitre.org + access (google.cloud.securitycenter_v1.types.Access): + Access details associated with the finding, + such as more information on the caller, which + method was accessed, and from where. + connections (MutableSequence[google.cloud.securitycenter_v1.types.Connection]): + Contains information about the IP connection + associated with the finding. + mute_initiator (str): + Records additional information about the mute operation, for + example, the `mute + configuration `__ + that muted the finding and the user who muted the finding. + processes (MutableSequence[google.cloud.securitycenter_v1.types.Process]): + Represents operating system processes + associated with the Finding. + contacts (MutableMapping[str, google.cloud.securitycenter_v1.types.ContactDetails]): + Output only. Map containing the points of contact for the + given finding. The key represents the type of contact, while + the value contains a list of all the contacts that pertain. + Please refer to: + https://cloud.google.com/resource-manager/docs/managing-notification-contacts#notification-categories + + :: + + { + "security": { + "contacts": [ + { + "email": "person1@company.com" + }, + { + "email": "person2@company.com" + } + ] + } + } + compliances (MutableSequence[google.cloud.securitycenter_v1.types.Compliance]): + Contains compliance information for security + standards associated to the finding. + parent_display_name (str): + Output only. The human readable display name + of the finding source such as "Event Threat + Detection" or "Security Health Analytics". + description (str): + Contains more details about the finding. + exfiltration (google.cloud.securitycenter_v1.types.Exfiltration): + Represents exfiltrations associated with the + finding. + iam_bindings (MutableSequence[google.cloud.securitycenter_v1.types.IamBinding]): + Represents IAM bindings associated with the + finding. + next_steps (str): + Steps to address the finding. + module_name (str): + Unique identifier of the module which + generated the finding. Example: + + folders/598186756061/securityHealthAnalyticsSettings/customModules/56799441161885 + containers (MutableSequence[google.cloud.securitycenter_v1.types.Container]): + Containers associated with the finding. This + field provides information for both Kubernetes + and non-Kubernetes containers. + kubernetes (google.cloud.securitycenter_v1.types.Kubernetes): + Kubernetes resources associated with the + finding. + database (google.cloud.securitycenter_v1.types.Database): + Database associated with the finding. + attack_exposure (google.cloud.securitycenter_v1.types.AttackExposure): + The results of an attack path simulation + relevant to this finding. + files (MutableSequence[google.cloud.securitycenter_v1.types.File]): + File associated with the finding. + cloud_dlp_inspection (google.cloud.securitycenter_v1.types.CloudDlpInspection): + Cloud Data Loss Prevention (Cloud DLP) + inspection results that are associated with the + finding. + cloud_dlp_data_profile (google.cloud.securitycenter_v1.types.CloudDlpDataProfile): + Cloud DLP data profile that is associated + with the finding. + kernel_rootkit (google.cloud.securitycenter_v1.types.KernelRootkit): + Signature of the kernel rootkit. + org_policies (MutableSequence[google.cloud.securitycenter_v1.types.OrgPolicy]): + Contains information about the org policies + associated with the finding. + application (google.cloud.securitycenter_v1.types.Application): + Represents an application associated with the + finding. + backup_disaster_recovery (google.cloud.securitycenter_v1.types.BackupDisasterRecovery): + Fields related to Backup and DR findings. + security_posture (google.cloud.securitycenter_v1.types.SecurityPosture): + The security posture associated with the + finding. + log_entries (MutableSequence[google.cloud.securitycenter_v1.types.LogEntry]): + Log entries that are relevant to the finding. + load_balancers (MutableSequence[google.cloud.securitycenter_v1.types.LoadBalancer]): + The load balancers associated with the + finding. + cloud_armor (google.cloud.securitycenter_v1.types.CloudArmor): + Fields related to Cloud Armor findings. + notebook (google.cloud.securitycenter_v1.types.Notebook): + Notebook associated with the finding. + toxic_combination (google.cloud.securitycenter_v1.types.ToxicCombination): + Contains details about a group of security + issues that, when the issues occur together, + represent a greater risk than when the issues + occur independently. A group of such issues is + referred to as a toxic combination. + This field cannot be updated. Its value is + ignored in all update requests. + group_memberships (MutableSequence[google.cloud.securitycenter_v1.types.GroupMembership]): + Contains details about groups of which this + finding is a member. A group is a collection of + findings that are related in some way. This + field cannot be updated. Its value is ignored in + all update requests. + """ + class State(proto.Enum): + r"""The state of the finding. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + ACTIVE (1): + The finding requires attention and has not + been addressed yet. + INACTIVE (2): + The finding has been fixed, triaged as a + non-issue or otherwise addressed and is no + longer active. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + class Severity(proto.Enum): + r"""The severity of the finding. + + Values: + SEVERITY_UNSPECIFIED (0): + This value is used for findings when a source + doesn't write a severity value. + CRITICAL (1): + Vulnerability: + + A critical vulnerability is easily discoverable + by an external actor, exploitable, and results + in the direct ability to execute arbitrary code, + exfiltrate data, and otherwise gain additional + access and privileges to cloud resources and + workloads. Examples include publicly accessible + unprotected user data and public SSH access with + weak or no passwords. + + Threat: + + Indicates a threat that is able to access, + modify, or delete data or execute unauthorized + code within existing resources. + HIGH (2): + Vulnerability: + + A high risk vulnerability can be easily + discovered and exploited in combination with + other vulnerabilities in order to gain direct + access and the ability to execute arbitrary + code, exfiltrate data, and otherwise gain + additional access and privileges to cloud + resources and workloads. An example is a + database with weak or no passwords that is only + accessible internally. This database could + easily be compromised by an actor that had + access to the internal network. + + Threat: + + Indicates a threat that is able to create new + computational resources in an environment but + not able to access data or execute code in + existing resources. + MEDIUM (3): + Vulnerability: + + A medium risk vulnerability could be used by an + actor to gain access to resources or privileges + that enable them to eventually (through multiple + steps or a complex exploit) gain access and the + ability to execute arbitrary code or exfiltrate + data. An example is a service account with + access to more projects than it should have. If + an actor gains access to the service account, + they could potentially use that access to + manipulate a project the service account was not + intended to. + + Threat: + + Indicates a threat that is able to cause + operational impact but may not access data or + execute unauthorized code. + LOW (4): + Vulnerability: + + A low risk vulnerability hampers a security + organization's ability to detect vulnerabilities + or active threats in their deployment, or + prevents the root cause investigation of + security issues. An example is monitoring and + logs being disabled for resource configurations + and access. + + Threat: + + Indicates a threat that has obtained minimal + access to an environment but is not able to + access data, execute code, or create resources. + """ + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + HIGH = 2 + MEDIUM = 3 + LOW = 4 + + class Mute(proto.Enum): + r"""Mute state a finding can be in. + + Values: + MUTE_UNSPECIFIED (0): + Unspecified. + MUTED (1): + Finding has been muted. + UNMUTED (2): + Finding has been unmuted. + UNDEFINED (4): + Finding has never been muted/unmuted. + """ + MUTE_UNSPECIFIED = 0 + MUTED = 1 + UNMUTED = 2 + UNDEFINED = 4 + + class FindingClass(proto.Enum): + r"""Represents what kind of Finding it is. + + Values: + FINDING_CLASS_UNSPECIFIED (0): + Unspecified finding class. + THREAT (1): + Describes unwanted or malicious activity. + VULNERABILITY (2): + Describes a potential weakness in software + that increases risk to Confidentiality & + Integrity & Availability. + MISCONFIGURATION (3): + Describes a potential weakness in cloud + resource/asset configuration that increases + risk. + OBSERVATION (4): + Describes a security observation that is for + informational purposes. + SCC_ERROR (5): + Describes an error that prevents some SCC + functionality. + POSTURE_VIOLATION (6): + Describes a potential security risk due to a + change in the security posture. + TOXIC_COMBINATION (7): + Describes a group of security issues that, + when the issues occur together, represent a + greater risk than when the issues occur + independently. A group of such issues is + referred to as a toxic combination. + """ + FINDING_CLASS_UNSPECIFIED = 0 + THREAT = 1 + VULNERABILITY = 2 + MISCONFIGURATION = 3 + OBSERVATION = 4 + SCC_ERROR = 5 + POSTURE_VIOLATION = 6 + TOXIC_COMBINATION = 7 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + resource_name: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + category: str = proto.Field( + proto.STRING, + number=5, + ) + external_uri: str = proto.Field( + proto.STRING, + number=6, + ) + source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=12, + enum=Severity, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=14, + ) + mute: Mute = proto.Field( + proto.ENUM, + number=15, + enum=Mute, + ) + finding_class: FindingClass = proto.Field( + proto.ENUM, + number=17, + enum=FindingClass, + ) + indicator: gcs_indicator.Indicator = proto.Field( + proto.MESSAGE, + number=18, + message=gcs_indicator.Indicator, + ) + vulnerability: gcs_vulnerability.Vulnerability = proto.Field( + proto.MESSAGE, + number=20, + message=gcs_vulnerability.Vulnerability, + ) + mute_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=21, + message=timestamp_pb2.Timestamp, + ) + external_systems: MutableMapping[str, external_system.ExternalSystem] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=22, + message=external_system.ExternalSystem, + ) + mitre_attack: gcs_mitre_attack.MitreAttack = proto.Field( + proto.MESSAGE, + number=25, + message=gcs_mitre_attack.MitreAttack, + ) + access: gcs_access.Access = proto.Field( + proto.MESSAGE, + number=26, + message=gcs_access.Access, + ) + connections: MutableSequence[connection.Connection] = proto.RepeatedField( + proto.MESSAGE, + number=31, + message=connection.Connection, + ) + mute_initiator: str = proto.Field( + proto.STRING, + number=28, + ) + processes: MutableSequence[process.Process] = proto.RepeatedField( + proto.MESSAGE, + number=30, + message=process.Process, + ) + contacts: MutableMapping[str, contact_details.ContactDetails] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=33, + message=contact_details.ContactDetails, + ) + compliances: MutableSequence[compliance.Compliance] = proto.RepeatedField( + proto.MESSAGE, + number=34, + message=compliance.Compliance, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=36, + ) + description: str = proto.Field( + proto.STRING, + number=37, + ) + exfiltration: gcs_exfiltration.Exfiltration = proto.Field( + proto.MESSAGE, + number=38, + message=gcs_exfiltration.Exfiltration, + ) + iam_bindings: MutableSequence[iam_binding.IamBinding] = proto.RepeatedField( + proto.MESSAGE, + number=39, + message=iam_binding.IamBinding, + ) + next_steps: str = proto.Field( + proto.STRING, + number=40, + ) + module_name: str = proto.Field( + proto.STRING, + number=41, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=42, + message=container.Container, + ) + kubernetes: gcs_kubernetes.Kubernetes = proto.Field( + proto.MESSAGE, + number=43, + message=gcs_kubernetes.Kubernetes, + ) + database: gcs_database.Database = proto.Field( + proto.MESSAGE, + number=44, + message=gcs_database.Database, + ) + attack_exposure: gcs_attack_exposure.AttackExposure = proto.Field( + proto.MESSAGE, + number=45, + message=gcs_attack_exposure.AttackExposure, + ) + files: MutableSequence[file.File] = proto.RepeatedField( + proto.MESSAGE, + number=46, + message=file.File, + ) + cloud_dlp_inspection: gcs_cloud_dlp_inspection.CloudDlpInspection = proto.Field( + proto.MESSAGE, + number=48, + message=gcs_cloud_dlp_inspection.CloudDlpInspection, + ) + cloud_dlp_data_profile: gcs_cloud_dlp_data_profile.CloudDlpDataProfile = proto.Field( + proto.MESSAGE, + number=49, + message=gcs_cloud_dlp_data_profile.CloudDlpDataProfile, + ) + kernel_rootkit: gcs_kernel_rootkit.KernelRootkit = proto.Field( + proto.MESSAGE, + number=50, + message=gcs_kernel_rootkit.KernelRootkit, + ) + org_policies: MutableSequence[org_policy.OrgPolicy] = proto.RepeatedField( + proto.MESSAGE, + number=51, + message=org_policy.OrgPolicy, + ) + application: gcs_application.Application = proto.Field( + proto.MESSAGE, + number=53, + message=gcs_application.Application, + ) + backup_disaster_recovery: gcs_backup_disaster_recovery.BackupDisasterRecovery = proto.Field( + proto.MESSAGE, + number=55, + message=gcs_backup_disaster_recovery.BackupDisasterRecovery, + ) + security_posture: gcs_security_posture.SecurityPosture = proto.Field( + proto.MESSAGE, + number=56, + message=gcs_security_posture.SecurityPosture, + ) + log_entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( + proto.MESSAGE, + number=57, + message=log_entry.LogEntry, + ) + load_balancers: MutableSequence[load_balancer.LoadBalancer] = proto.RepeatedField( + proto.MESSAGE, + number=58, + message=load_balancer.LoadBalancer, + ) + cloud_armor: gcs_cloud_armor.CloudArmor = proto.Field( + proto.MESSAGE, + number=59, + message=gcs_cloud_armor.CloudArmor, + ) + notebook: gcs_notebook.Notebook = proto.Field( + proto.MESSAGE, + number=63, + message=gcs_notebook.Notebook, + ) + toxic_combination: gcs_toxic_combination.ToxicCombination = proto.Field( + proto.MESSAGE, + number=64, + message=gcs_toxic_combination.ToxicCombination, + ) + group_memberships: MutableSequence[group_membership.GroupMembership] = proto.RepeatedField( + proto.MESSAGE, + number=65, + message=group_membership.GroupMembership, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.py new file mode 100644 index 000000000000..577452411641 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.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.securitycenter.v1', + manifest={ + 'Folder', + }, +) + + +class Folder(proto.Message): + r"""Message that contains the resource name and display name of a + folder resource. + + Attributes: + resource_folder (str): + Full resource name of this folder. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_folder_display_name (str): + The user defined display name for this + folder. + """ + + resource_folder: str = proto.Field( + proto.STRING, + number=1, + ) + resource_folder_display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.py new file mode 100644 index 000000000000..d95cb97ea0a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.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.cloud.securitycenter.v1', + manifest={ + 'GroupMembership', + }, +) + + +class GroupMembership(proto.Message): + r"""Contains details about groups of which this finding is a + member. A group is a collection of findings that are related in + some way. + + Attributes: + group_type (google.cloud.securitycenter_v1.types.GroupMembership.GroupType): + Type of group. + group_id (str): + ID of the group. + """ + class GroupType(proto.Enum): + r"""Possible types of groups. + + Values: + GROUP_TYPE_UNSPECIFIED (0): + Default value. + GROUP_TYPE_TOXIC_COMBINATION (1): + Group represents a toxic combination. + """ + GROUP_TYPE_UNSPECIFIED = 0 + GROUP_TYPE_TOXIC_COMBINATION = 1 + + group_type: GroupType = proto.Field( + proto.ENUM, + number=1, + enum=GroupType, + ) + group_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py new file mode 100644 index 000000000000..cab59d31ec7c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v1', + manifest={ + 'IamBinding', + }, +) + + +class IamBinding(proto.Message): + r"""Represents a particular IAM binding, which captures a + member's role addition, removal, or state. + + Attributes: + action (google.cloud.securitycenter_v1.types.IamBinding.Action): + The action that was performed on a Binding. + role (str): + Role that is assigned to "members". + For example, "roles/viewer", "roles/editor", or + "roles/owner". + member (str): + A single identity requesting access for a + Cloud Platform resource, for example, + "foo@google.com". + """ + class Action(proto.Enum): + r"""The type of action performed on a Binding in a policy. + + Values: + ACTION_UNSPECIFIED (0): + Unspecified. + ADD (1): + Addition of a Binding. + REMOVE (2): + Removal of a Binding. + """ + ACTION_UNSPECIFIED = 0 + ADD = 1 + REMOVE = 2 + + action: Action = proto.Field( + proto.ENUM, + number=1, + enum=Action, + ) + role: str = proto.Field( + proto.STRING, + number=2, + ) + member: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py new file mode 100644 index 000000000000..f75bd00701dd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v1', + manifest={ + 'Indicator', + }, +) + + +class Indicator(proto.Message): + r"""Represents what's commonly known as an *indicator of compromise* + (IoC) in computer forensics. This is an artifact observed on a + network or in an operating system that, with high confidence, + indicates a computer intrusion. For more information, see `Indicator + of + compromise `__. + + Attributes: + ip_addresses (MutableSequence[str]): + The list of IP addresses that are associated + with the finding. + domains (MutableSequence[str]): + List of domains associated to the Finding. + signatures (MutableSequence[google.cloud.securitycenter_v1.types.Indicator.ProcessSignature]): + The list of matched signatures indicating + that the given process is present in the + environment. + uris (MutableSequence[str]): + The list of URIs associated to the Findings. + """ + + class ProcessSignature(proto.Message): + r"""Indicates what signature matched this process. + + 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: + memory_hash_signature (google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.MemoryHashSignature): + Signature indicating that a binary family was + matched. + + This field is a member of `oneof`_ ``signature``. + yara_rule_signature (google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.YaraRuleSignature): + Signature indicating that a YARA rule was + matched. + + This field is a member of `oneof`_ ``signature``. + signature_type (google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.SignatureType): + Describes the type of resource associated + with the signature. + """ + class SignatureType(proto.Enum): + r"""Possible resource types to be associated with a signature. + + Values: + SIGNATURE_TYPE_UNSPECIFIED (0): + The default signature type. + SIGNATURE_TYPE_PROCESS (1): + Used for signatures concerning processes. + SIGNATURE_TYPE_FILE (2): + Used for signatures concerning disks. + """ + SIGNATURE_TYPE_UNSPECIFIED = 0 + SIGNATURE_TYPE_PROCESS = 1 + SIGNATURE_TYPE_FILE = 2 + + class MemoryHashSignature(proto.Message): + r"""A signature corresponding to memory page hashes. + + Attributes: + binary_family (str): + The binary family. + detections (MutableSequence[google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.MemoryHashSignature.Detection]): + The list of memory hash detections + contributing to the binary family match. + """ + + class Detection(proto.Message): + r"""Memory hash detection contributing to the binary family + match. + + Attributes: + binary (str): + The name of the binary associated with the + memory hash signature detection. + percent_pages_matched (float): + The percentage of memory page hashes in the + signature that were matched. + """ + + binary: str = proto.Field( + proto.STRING, + number=2, + ) + percent_pages_matched: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + binary_family: str = proto.Field( + proto.STRING, + number=1, + ) + detections: MutableSequence['Indicator.ProcessSignature.MemoryHashSignature.Detection'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Indicator.ProcessSignature.MemoryHashSignature.Detection', + ) + + class YaraRuleSignature(proto.Message): + r"""A signature corresponding to a YARA rule. + + Attributes: + yara_rule (str): + The name of the YARA rule. + """ + + yara_rule: str = proto.Field( + proto.STRING, + number=5, + ) + + memory_hash_signature: 'Indicator.ProcessSignature.MemoryHashSignature' = proto.Field( + proto.MESSAGE, + number=6, + oneof='signature', + message='Indicator.ProcessSignature.MemoryHashSignature', + ) + yara_rule_signature: 'Indicator.ProcessSignature.YaraRuleSignature' = proto.Field( + proto.MESSAGE, + number=7, + oneof='signature', + message='Indicator.ProcessSignature.YaraRuleSignature', + ) + signature_type: 'Indicator.ProcessSignature.SignatureType' = proto.Field( + proto.ENUM, + number=8, + enum='Indicator.ProcessSignature.SignatureType', + ) + + ip_addresses: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + domains: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + signatures: MutableSequence[ProcessSignature] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=ProcessSignature, + ) + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.py new file mode 100644 index 000000000000..d9c18edeec46 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'KernelRootkit', + }, +) + + +class KernelRootkit(proto.Message): + r"""Kernel mode rootkit signatures. + + Attributes: + name (str): + Rootkit name, when available. + unexpected_code_modification (bool): + True if unexpected modifications of kernel + code memory are present. + unexpected_read_only_data_modification (bool): + True if unexpected modifications of kernel + read-only data memory are present. + unexpected_ftrace_handler (bool): + True if ``ftrace`` points are present with callbacks + pointing to regions that are not in the expected kernel or + module code range. + unexpected_kprobe_handler (bool): + True if ``kprobe`` points are present with callbacks + pointing to regions that are not in the expected kernel or + module code range. + unexpected_kernel_code_pages (bool): + True if kernel code pages that are not in the + expected kernel or module code regions are + present. + unexpected_system_call_handler (bool): + True if system call handlers that are are not + in the expected kernel or module code regions + are present. + unexpected_interrupt_handler (bool): + True if interrupt handlers that are are not + in the expected kernel or module code regions + are present. + unexpected_processes_in_runqueue (bool): + True if unexpected processes in the scheduler + run queue are present. Such processes are in the + run queue, but not in the process task list. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + unexpected_code_modification: bool = proto.Field( + proto.BOOL, + number=2, + ) + unexpected_read_only_data_modification: bool = proto.Field( + proto.BOOL, + number=3, + ) + unexpected_ftrace_handler: bool = proto.Field( + proto.BOOL, + number=4, + ) + unexpected_kprobe_handler: bool = proto.Field( + proto.BOOL, + number=5, + ) + unexpected_kernel_code_pages: bool = proto.Field( + proto.BOOL, + number=6, + ) + unexpected_system_call_handler: bool = proto.Field( + proto.BOOL, + number=7, + ) + unexpected_interrupt_handler: bool = proto.Field( + proto.BOOL, + number=8, + ) + unexpected_processes_in_runqueue: bool = proto.Field( + proto.BOOL, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.py new file mode 100644 index 000000000000..b91973ac449b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v1.types import container +from google.cloud.securitycenter_v1.types import label + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Kubernetes', + }, +) + + +class Kubernetes(proto.Message): + r"""Kubernetes-related attributes. + + Attributes: + pods (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Pod]): + Kubernetes + `Pods `__ + associated with the finding. This field contains Pod records + for each container that is owned by a Pod. + nodes (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Node]): + Provides Kubernetes + `node `__ + information. + node_pools (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.NodePool]): + GKE `node + pools `__ + associated with the finding. This field contains node pool + information for each node, when it is available. + roles (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Role]): + Provides Kubernetes role information for findings that + involve `Roles or + ClusterRoles `__. + bindings (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Binding]): + Provides Kubernetes role binding information for findings + that involve `RoleBindings or + ClusterRoleBindings `__. + access_reviews (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.AccessReview]): + Provides information on any Kubernetes access + reviews (privilege checks) relevant to the + finding. + objects (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Object]): + Kubernetes objects related to the finding. + """ + + class Pod(proto.Message): + r"""A Kubernetes Pod. + + Attributes: + ns (str): + Kubernetes Pod namespace. + name (str): + Kubernetes Pod name. + labels (MutableSequence[google.cloud.securitycenter_v1.types.Label]): + Pod labels. For Kubernetes containers, these + are applied to the container. + containers (MutableSequence[google.cloud.securitycenter_v1.types.Container]): + Pod containers associated with this finding, + if any. + """ + + ns: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + labels: MutableSequence[label.Label] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=label.Label, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=container.Container, + ) + + class Node(proto.Message): + r"""Kubernetes nodes associated with the finding. + + Attributes: + name (str): + `Full resource + name `__ of + the Compute Engine VM running the cluster node. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + class NodePool(proto.Message): + r"""Provides GKE node pool information. + + Attributes: + name (str): + Kubernetes node pool name. + nodes (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Node]): + Nodes associated with the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + nodes: MutableSequence['Kubernetes.Node'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Kubernetes.Node', + ) + + class Role(proto.Message): + r"""Kubernetes Role or ClusterRole. + + Attributes: + kind (google.cloud.securitycenter_v1.types.Kubernetes.Role.Kind): + Role type. + ns (str): + Role namespace. + name (str): + Role name. + """ + class Kind(proto.Enum): + r"""Types of Kubernetes roles. + + Values: + KIND_UNSPECIFIED (0): + Role type is not specified. + ROLE (1): + Kubernetes Role. + CLUSTER_ROLE (2): + Kubernetes ClusterRole. + """ + KIND_UNSPECIFIED = 0 + ROLE = 1 + CLUSTER_ROLE = 2 + + kind: 'Kubernetes.Role.Kind' = proto.Field( + proto.ENUM, + number=1, + enum='Kubernetes.Role.Kind', + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class Binding(proto.Message): + r"""Represents a Kubernetes RoleBinding or ClusterRoleBinding. + + Attributes: + ns (str): + Namespace for the binding. + name (str): + Name for the binding. + role (google.cloud.securitycenter_v1.types.Kubernetes.Role): + The Role or ClusterRole referenced by the + binding. + subjects (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Subject]): + Represents one or more subjects that are + bound to the role. Not always available for + PATCH requests. + """ + + ns: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + role: 'Kubernetes.Role' = proto.Field( + proto.MESSAGE, + number=3, + message='Kubernetes.Role', + ) + subjects: MutableSequence['Kubernetes.Subject'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Kubernetes.Subject', + ) + + class Subject(proto.Message): + r"""Represents a Kubernetes subject. + + Attributes: + kind (google.cloud.securitycenter_v1.types.Kubernetes.Subject.AuthType): + Authentication type for the subject. + ns (str): + Namespace for the subject. + name (str): + Name for the subject. + """ + class AuthType(proto.Enum): + r"""Auth types that can be used for the subject's kind field. + + Values: + AUTH_TYPE_UNSPECIFIED (0): + Authentication is not specified. + USER (1): + User with valid certificate. + SERVICEACCOUNT (2): + Users managed by Kubernetes API with + credentials stored as secrets. + GROUP (3): + Collection of users. + """ + AUTH_TYPE_UNSPECIFIED = 0 + USER = 1 + SERVICEACCOUNT = 2 + GROUP = 3 + + kind: 'Kubernetes.Subject.AuthType' = proto.Field( + proto.ENUM, + number=1, + enum='Kubernetes.Subject.AuthType', + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class AccessReview(proto.Message): + r"""Conveys information about a Kubernetes access review (such as one + returned by a + ```kubectl auth can-i`` `__ + command) that was involved in a finding. + + Attributes: + group (str): + The API group of the resource. "*" means all. + ns (str): + Namespace of the action being requested. + Currently, there is no distinction between no + namespace and all namespaces. Both are + represented by "" (empty). + name (str): + The name of the resource being requested. + Empty means all. + resource (str): + The optional resource type requested. "*" means all. + subresource (str): + The optional subresource type. + verb (str): + A Kubernetes resource API verb, like get, list, watch, + create, update, delete, proxy. "*" means all. + version (str): + The API version of the resource. "*" means all. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + resource: str = proto.Field( + proto.STRING, + number=4, + ) + subresource: str = proto.Field( + proto.STRING, + number=5, + ) + verb: str = proto.Field( + proto.STRING, + number=6, + ) + version: str = proto.Field( + proto.STRING, + number=7, + ) + + class Object(proto.Message): + r"""Kubernetes object related to the finding, uniquely identified + by GKNN. Used if the object Kind is not one of Pod, Node, + NodePool, Binding, or AccessReview. + + Attributes: + group (str): + Kubernetes object group, such as + "policy.k8s.io/v1". + kind (str): + Kubernetes object kind, such as "Namespace". + ns (str): + Kubernetes object namespace. Must be a valid + DNS label. Named "ns" to avoid collision with + C++ namespace keyword. For details see + https://kubernetes.io/docs/tasks/administer-cluster/namespaces/. + name (str): + Kubernetes object name. For details see + https://kubernetes.io/docs/concepts/overview/working-with-objects/names/. + containers (MutableSequence[google.cloud.securitycenter_v1.types.Container]): + Pod containers associated with this finding, + if any. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + kind: str = proto.Field( + proto.STRING, + number=2, + ) + ns: str = proto.Field( + proto.STRING, + number=3, + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=container.Container, + ) + + pods: MutableSequence[Pod] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Pod, + ) + nodes: MutableSequence[Node] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Node, + ) + node_pools: MutableSequence[NodePool] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=NodePool, + ) + roles: MutableSequence[Role] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Role, + ) + bindings: MutableSequence[Binding] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Binding, + ) + access_reviews: MutableSequence[AccessReview] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=AccessReview, + ) + objects: MutableSequence[Object] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Object, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.py new file mode 100644 index 000000000000..8ece19d81c07 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.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.securitycenter.v1', + manifest={ + 'Label', + }, +) + + +class Label(proto.Message): + r"""Represents a generic name-value label. A label has separate name and + value fields to support filtering with the ``contains()`` function. + For more information, see `Filtering on array-type + fields `__. + + Attributes: + name (str): + Name of the label. + value (str): + Value that corresponds to the label's name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.py new file mode 100644 index 000000000000..050b3b0c6c9a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.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.cloud.securitycenter.v1', + manifest={ + 'LoadBalancer', + }, +) + + +class LoadBalancer(proto.Message): + r"""Contains information related to the load balancer associated + with the finding. + + Attributes: + name (str): + The name of the load balancer associated with + the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.py new file mode 100644 index 000000000000..6e4222745dd0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.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 __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.securitycenter.v1', + manifest={ + 'LogEntry', + 'CloudLoggingEntry', + }, +) + + +class LogEntry(proto.Message): + r"""An individual entry in a log. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_logging_entry (google.cloud.securitycenter_v1.types.CloudLoggingEntry): + An individual entry in a log stored in Cloud + Logging. + + This field is a member of `oneof`_ ``log_entry``. + """ + + cloud_logging_entry: 'CloudLoggingEntry' = proto.Field( + proto.MESSAGE, + number=1, + oneof='log_entry', + message='CloudLoggingEntry', + ) + + +class CloudLoggingEntry(proto.Message): + r"""Metadata taken from a `Cloud Logging + LogEntry `__ + + Attributes: + insert_id (str): + A unique identifier for the log entry. + log_id (str): + The type of the log (part of ``log_name``. ``log_name`` is + the resource name of the log to which this log entry + belongs). For example: + ``cloudresourcemanager.googleapis.com/activity``. Note that + this field is not URL-encoded, unlike the ``LOG_ID`` field + in ``LogEntry``. + resource_container (str): + The organization, folder, or project of the + monitored resource that produced this log entry. + timestamp (google.protobuf.timestamp_pb2.Timestamp): + The time the event described by the log entry + occurred. + """ + + insert_id: str = proto.Field( + proto.STRING, + number=1, + ) + log_id: str = proto.Field( + proto.STRING, + number=2, + ) + resource_container: str = proto.Field( + proto.STRING, + number=3, + ) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.py new file mode 100644 index 000000000000..fe3616643316 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'MitreAttack', + }, +) + + +class MitreAttack(proto.Message): + r"""MITRE ATT&CK tactics and techniques related to this finding. + See: https://attack.mitre.org + + Attributes: + primary_tactic (google.cloud.securitycenter_v1.types.MitreAttack.Tactic): + The MITRE ATT&CK tactic most closely + represented by this finding, if any. + primary_techniques (MutableSequence[google.cloud.securitycenter_v1.types.MitreAttack.Technique]): + The MITRE ATT&CK technique most closely represented by this + finding, if any. primary_techniques is a repeated field + because there are multiple levels of MITRE ATT&CK + techniques. If the technique most closely represented by + this finding is a sub-technique (e.g. + ``SCANNING_IP_BLOCKS``), both the sub-technique and its + parent technique(s) will be listed (e.g. + ``SCANNING_IP_BLOCKS``, ``ACTIVE_SCANNING``). + additional_tactics (MutableSequence[google.cloud.securitycenter_v1.types.MitreAttack.Tactic]): + Additional MITRE ATT&CK tactics related to + this finding, if any. + additional_techniques (MutableSequence[google.cloud.securitycenter_v1.types.MitreAttack.Technique]): + Additional MITRE ATT&CK techniques related to + this finding, if any, along with any of their + respective parent techniques. + version (str): + The MITRE ATT&CK version referenced by the + above fields. E.g. "8". + """ + class Tactic(proto.Enum): + r"""MITRE ATT&CK tactics that can be referenced by SCC findings. + See: https://attack.mitre.org/tactics/enterprise/ + + Values: + TACTIC_UNSPECIFIED (0): + Unspecified value. + RECONNAISSANCE (1): + TA0043 + RESOURCE_DEVELOPMENT (2): + TA0042 + INITIAL_ACCESS (5): + TA0001 + EXECUTION (3): + TA0002 + PERSISTENCE (6): + TA0003 + PRIVILEGE_ESCALATION (8): + TA0004 + DEFENSE_EVASION (7): + TA0005 + CREDENTIAL_ACCESS (9): + TA0006 + DISCOVERY (10): + TA0007 + LATERAL_MOVEMENT (11): + TA0008 + COLLECTION (12): + TA0009 + COMMAND_AND_CONTROL (4): + TA0011 + EXFILTRATION (13): + TA0010 + IMPACT (14): + TA0040 + """ + TACTIC_UNSPECIFIED = 0 + RECONNAISSANCE = 1 + RESOURCE_DEVELOPMENT = 2 + INITIAL_ACCESS = 5 + EXECUTION = 3 + PERSISTENCE = 6 + PRIVILEGE_ESCALATION = 8 + DEFENSE_EVASION = 7 + CREDENTIAL_ACCESS = 9 + DISCOVERY = 10 + LATERAL_MOVEMENT = 11 + COLLECTION = 12 + COMMAND_AND_CONTROL = 4 + EXFILTRATION = 13 + IMPACT = 14 + + class Technique(proto.Enum): + r"""MITRE ATT&CK techniques that can be referenced by SCC + findings. See: https://attack.mitre.org/techniques/enterprise/ + Next ID: 63 + + Values: + TECHNIQUE_UNSPECIFIED (0): + Unspecified value. + MASQUERADING (49): + T1036 + MATCH_LEGITIMATE_NAME_OR_LOCATION (50): + T1036.005 + BOOT_OR_LOGON_INITIALIZATION_SCRIPTS (37): + T1037 + STARTUP_ITEMS (38): + T1037.005 + NETWORK_SERVICE_DISCOVERY (32): + T1046 + PROCESS_DISCOVERY (56): + T1057 + COMMAND_AND_SCRIPTING_INTERPRETER (6): + T1059 + UNIX_SHELL (7): + T1059.004 + PYTHON (59): + T1059.006 + PERMISSION_GROUPS_DISCOVERY (18): + T1069 + CLOUD_GROUPS (19): + T1069.003 + APPLICATION_LAYER_PROTOCOL (45): + T1071 + DNS (46): + T1071.004 + SOFTWARE_DEPLOYMENT_TOOLS (47): + T1072 + VALID_ACCOUNTS (14): + T1078 + DEFAULT_ACCOUNTS (35): + T1078.001 + LOCAL_ACCOUNTS (15): + T1078.003 + CLOUD_ACCOUNTS (16): + T1078.004 + PROXY (9): + T1090 + EXTERNAL_PROXY (10): + T1090.002 + MULTI_HOP_PROXY (11): + T1090.003 + ACCOUNT_MANIPULATION (22): + T1098 + ADDITIONAL_CLOUD_CREDENTIALS (40): + T1098.001 + SSH_AUTHORIZED_KEYS (23): + T1098.004 + ADDITIONAL_CONTAINER_CLUSTER_ROLES (58): + T1098.006 + INGRESS_TOOL_TRANSFER (3): + T1105 + NATIVE_API (4): + T1106 + BRUTE_FORCE (44): + T1110 + SHARED_MODULES (5): + T1129 + ACCESS_TOKEN_MANIPULATION (33): + T1134 + TOKEN_IMPERSONATION_OR_THEFT (39): + T1134.001 + EXPLOIT_PUBLIC_FACING_APPLICATION (27): + T1190 + DOMAIN_POLICY_MODIFICATION (30): + T1484 + DATA_DESTRUCTION (29): + T1485 + SERVICE_STOP (52): + T1489 + INHIBIT_SYSTEM_RECOVERY (36): + T1490 + RESOURCE_HIJACKING (8): + T1496 + NETWORK_DENIAL_OF_SERVICE (17): + T1498 + CLOUD_SERVICE_DISCOVERY (48): + T1526 + STEAL_APPLICATION_ACCESS_TOKEN (42): + T1528 + ACCOUNT_ACCESS_REMOVAL (51): + T1531 + STEAL_WEB_SESSION_COOKIE (25): + T1539 + CREATE_OR_MODIFY_SYSTEM_PROCESS (24): + T1543 + ABUSE_ELEVATION_CONTROL_MECHANISM (34): + T1548 + UNSECURED_CREDENTIALS (13): + T1552 + MODIFY_AUTHENTICATION_PROCESS (28): + T1556 + IMPAIR_DEFENSES (31): + T1562 + DISABLE_OR_MODIFY_TOOLS (55): + T1562.001 + EXFILTRATION_OVER_WEB_SERVICE (20): + T1567 + EXFILTRATION_TO_CLOUD_STORAGE (21): + T1567.002 + DYNAMIC_RESOLUTION (12): + T1568 + LATERAL_TOOL_TRANSFER (41): + T1570 + MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE (26): + T1578 + CREATE_SNAPSHOT (54): + T1578.001 + CLOUD_INFRASTRUCTURE_DISCOVERY (53): + T1580 + OBTAIN_CAPABILITIES (43): + T1588 + ACTIVE_SCANNING (1): + T1595 + SCANNING_IP_BLOCKS (2): + T1595.001 + CONTAINER_ADMINISTRATION_COMMAND (60): + T1609 + ESCAPE_TO_HOST (61): + T1611 + CONTAINER_AND_RESOURCE_DISCOVERY (57): + T1613 + STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES (62): + T1649 + """ + TECHNIQUE_UNSPECIFIED = 0 + MASQUERADING = 49 + MATCH_LEGITIMATE_NAME_OR_LOCATION = 50 + BOOT_OR_LOGON_INITIALIZATION_SCRIPTS = 37 + STARTUP_ITEMS = 38 + NETWORK_SERVICE_DISCOVERY = 32 + PROCESS_DISCOVERY = 56 + COMMAND_AND_SCRIPTING_INTERPRETER = 6 + UNIX_SHELL = 7 + PYTHON = 59 + PERMISSION_GROUPS_DISCOVERY = 18 + CLOUD_GROUPS = 19 + APPLICATION_LAYER_PROTOCOL = 45 + DNS = 46 + SOFTWARE_DEPLOYMENT_TOOLS = 47 + VALID_ACCOUNTS = 14 + DEFAULT_ACCOUNTS = 35 + LOCAL_ACCOUNTS = 15 + CLOUD_ACCOUNTS = 16 + PROXY = 9 + EXTERNAL_PROXY = 10 + MULTI_HOP_PROXY = 11 + ACCOUNT_MANIPULATION = 22 + ADDITIONAL_CLOUD_CREDENTIALS = 40 + SSH_AUTHORIZED_KEYS = 23 + ADDITIONAL_CONTAINER_CLUSTER_ROLES = 58 + INGRESS_TOOL_TRANSFER = 3 + NATIVE_API = 4 + BRUTE_FORCE = 44 + SHARED_MODULES = 5 + ACCESS_TOKEN_MANIPULATION = 33 + TOKEN_IMPERSONATION_OR_THEFT = 39 + EXPLOIT_PUBLIC_FACING_APPLICATION = 27 + DOMAIN_POLICY_MODIFICATION = 30 + DATA_DESTRUCTION = 29 + SERVICE_STOP = 52 + INHIBIT_SYSTEM_RECOVERY = 36 + RESOURCE_HIJACKING = 8 + NETWORK_DENIAL_OF_SERVICE = 17 + CLOUD_SERVICE_DISCOVERY = 48 + STEAL_APPLICATION_ACCESS_TOKEN = 42 + ACCOUNT_ACCESS_REMOVAL = 51 + STEAL_WEB_SESSION_COOKIE = 25 + CREATE_OR_MODIFY_SYSTEM_PROCESS = 24 + ABUSE_ELEVATION_CONTROL_MECHANISM = 34 + UNSECURED_CREDENTIALS = 13 + MODIFY_AUTHENTICATION_PROCESS = 28 + IMPAIR_DEFENSES = 31 + DISABLE_OR_MODIFY_TOOLS = 55 + EXFILTRATION_OVER_WEB_SERVICE = 20 + EXFILTRATION_TO_CLOUD_STORAGE = 21 + DYNAMIC_RESOLUTION = 12 + LATERAL_TOOL_TRANSFER = 41 + MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE = 26 + CREATE_SNAPSHOT = 54 + CLOUD_INFRASTRUCTURE_DISCOVERY = 53 + OBTAIN_CAPABILITIES = 43 + ACTIVE_SCANNING = 1 + SCANNING_IP_BLOCKS = 2 + CONTAINER_ADMINISTRATION_COMMAND = 60 + ESCAPE_TO_HOST = 61 + CONTAINER_AND_RESOURCE_DISCOVERY = 57 + STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES = 62 + + primary_tactic: Tactic = proto.Field( + proto.ENUM, + number=1, + enum=Tactic, + ) + primary_techniques: MutableSequence[Technique] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=Technique, + ) + additional_tactics: MutableSequence[Tactic] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=Tactic, + ) + additional_techniques: MutableSequence[Technique] = proto.RepeatedField( + proto.ENUM, + number=4, + enum=Technique, + ) + version: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py new file mode 100644 index 000000000000..ee8a03538484 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.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 __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.securitycenter.v1', + manifest={ + 'MuteConfig', + }, +) + + +class MuteConfig(proto.Message): + r"""A mute config is a Cloud SCC resource that contains the + configuration to mute create/update events of findings. + + Attributes: + name (str): + This field will be ignored if provided on config creation. + Format + ``organizations/{organization}/muteConfigs/{mute_config}`` + ``folders/{folder}/muteConfigs/{mute_config}`` + ``projects/{project}/muteConfigs/{mute_config}`` + ``organizations/{organization}/locations/global/muteConfigs/{mute_config}`` + ``folders/{folder}/locations/global/muteConfigs/{mute_config}`` + ``projects/{project}/locations/global/muteConfigs/{mute_config}`` + display_name (str): + The human readable name to be displayed for + the mute config. + description (str): + A description of the mute config. + filter (str): + Required. An expression that defines the filter to apply + across create/update events of findings. While creating a + filter string, be mindful of the scope in which the mute + configuration is being created. E.g., If a filter contains + project = X but is created under the project = Y scope, it + might not match any findings. + + The following field and operator combinations are supported: + + - severity: ``=``, ``:`` + - category: ``=``, ``:`` + - resource.name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.folders.resource_folder: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + - finding_class: ``=``, ``:`` + - indicator.ip_addresses: ``=``, ``:`` + - indicator.domains: ``=``, ``:`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the mute + config was created. This field is set by the + server and will be ignored if provided on config + creation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time at which + the mute config was updated. This field is set + by the server and will be ignored if provided on + config creation or update. + most_recent_editor (str): + Output only. Email address of the user who + last edited the mute config. This field is set + by the server and will be ignored if provided on + config creation or update. + """ + + 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, + ) + filter: 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, + ) + most_recent_editor: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py new file mode 100644 index 000000000000..564197159f0c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v1', + manifest={ + 'Notebook', + }, +) + + +class Notebook(proto.Message): + r"""Represents a Jupyter notebook IPYNB file, such as a `Colab + Enterprise + notebook `__ file, + that is associated with a finding. + + Attributes: + name (str): + The name of the notebook. + service (str): + The source notebook service, for example, + "Colab Enterprise". + last_author (str): + The user ID of the latest author to modify + the notebook. + notebook_update_time (google.protobuf.timestamp_pb2.Timestamp): + The most recent time the notebook was + updated. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + service: str = proto.Field( + proto.STRING, + number=2, + ) + last_author: str = proto.Field( + proto.STRING, + number=3, + ) + notebook_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.py new file mode 100644 index 000000000000..d26990314b74 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'NotificationConfig', + }, +) + + +class NotificationConfig(proto.Message): + r"""Cloud Security Command Center (Cloud SCC) notification + configs. + A notification config is a Cloud SCC resource that contains the + configuration to send notifications for create/update events of + findings, assets and etc. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The relative resource name of this notification config. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/notificationConfigs/notify_public_bucket", + "folders/{folder_id}/notificationConfigs/notify_public_bucket", + or + "projects/{project_id}/notificationConfigs/notify_public_bucket". + description (str): + The description of the notification config + (max of 1024 characters). + pubsub_topic (str): + The Pub/Sub topic to send notifications to. Its format is + "projects/[project_id]/topics/[topic]". + service_account (str): + Output only. The service account that needs + "pubsub.topics.publish" permission to publish to + the Pub/Sub topic. + streaming_config (google.cloud.securitycenter_v1.types.NotificationConfig.StreamingConfig): + The config for triggering streaming-based + notifications. + + This field is a member of `oneof`_ ``notify_config``. + """ + + class StreamingConfig(proto.Message): + r"""The config for streaming-based notifications, which send each + event as soon as it is detected. + + Attributes: + filter (str): + Expression that defines the filter to apply across + create/update events of assets or findings as specified by + the event type. The expression is a list of zero or more + restrictions combined via logical operators ``AND`` and + ``OR``. Parentheses are supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + """ + + filter: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + pubsub_topic: str = proto.Field( + proto.STRING, + number=3, + ) + service_account: str = proto.Field( + proto.STRING, + number=4, + ) + streaming_config: StreamingConfig = proto.Field( + proto.MESSAGE, + number=5, + oneof='notify_config', + message=StreamingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.py new file mode 100644 index 000000000000..f979d5f7a0ec --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import resource as gcs_resource + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'NotificationMessage', + }, +) + + +class NotificationMessage(proto.Message): + r"""Cloud SCC's Notification + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + notification_config_name (str): + Name of the notification config that + generated current notification. + finding (google.cloud.securitycenter_v1.types.Finding): + If it's a Finding based notification config, + this field will be populated. + + This field is a member of `oneof`_ ``event``. + resource (google.cloud.securitycenter_v1.types.Resource): + The Cloud resource tied to this + notification's Finding. + """ + + notification_config_name: str = proto.Field( + proto.STRING, + number=1, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=2, + oneof='event', + message=gcs_finding.Finding, + ) + resource: gcs_resource.Resource = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_resource.Resource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.py new file mode 100644 index 000000000000..ebd7ac4b0424 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.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.cloud.securitycenter.v1', + manifest={ + 'OrgPolicy', + }, +) + + +class OrgPolicy(proto.Message): + r"""Contains information about the org policies associated with + the finding. + + Attributes: + name (str): + The resource name of the org policy. Example: + "organizations/{organization_id}/policies/{constraint_name}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.py new file mode 100644 index 000000000000..81c2816a1e66 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'OrganizationSettings', + }, +) + + +class OrganizationSettings(proto.Message): + r"""User specified settings that are attached to the Security + Command Center organization. + + Attributes: + name (str): + The relative resource name of the settings. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/organizationSettings". + enable_asset_discovery (bool): + A flag that indicates if Asset Discovery should be enabled. + If the flag is set to ``true``, then discovery of assets + will occur. If it is set to ``false``, all historical assets + will remain, but discovery of future assets will not occur. + asset_discovery_config (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig): + The configuration used for Asset Discovery + runs. + """ + + class AssetDiscoveryConfig(proto.Message): + r"""The configuration used for Asset Discovery runs. + + Attributes: + project_ids (MutableSequence[str]): + The project ids to use for filtering asset + discovery. + inclusion_mode (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + The mode to use for filtering asset + discovery. + folder_ids (MutableSequence[str]): + The folder ids to use for filtering asset + discovery. It consists of only digits, e.g., + 756619654966. + """ + class InclusionMode(proto.Enum): + r"""The mode of inclusion when running Asset Discovery. Asset discovery + can be limited by explicitly identifying projects to be included or + excluded. If INCLUDE_ONLY is set, then only those projects within + the organization and their children are discovered during asset + discovery. If EXCLUDE is set, then projects that don't match those + projects are discovered during asset discovery. If neither are set, + then all projects within the organization are discovered during + asset discovery. + + Values: + INCLUSION_MODE_UNSPECIFIED (0): + Unspecified. Setting the mode with this value + will disable inclusion/exclusion filtering for + Asset Discovery. + INCLUDE_ONLY (1): + Asset Discovery will capture only the + resources within the projects specified. All + other resources will be ignored. + EXCLUDE (2): + Asset Discovery will ignore all resources + under the projects specified. All other + resources will be retrieved. + """ + INCLUSION_MODE_UNSPECIFIED = 0 + INCLUDE_ONLY = 1 + EXCLUDE = 2 + + project_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + inclusion_mode: 'OrganizationSettings.AssetDiscoveryConfig.InclusionMode' = proto.Field( + proto.ENUM, + number=2, + enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', + ) + folder_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + enable_asset_discovery: bool = proto.Field( + proto.BOOL, + number=2, + ) + asset_discovery_config: AssetDiscoveryConfig = proto.Field( + proto.MESSAGE, + number=3, + message=AssetDiscoveryConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py new file mode 100644 index 000000000000..881b8df6dfa1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1.types import file + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Process', + 'EnvironmentVariable', + }, +) + + +class Process(proto.Message): + r"""Represents an operating system process. + + Attributes: + name (str): + The process name, as displayed in utilities like ``top`` and + ``ps``. This name can be accessed through + ``/proc/[pid]/comm`` and changed with + ``prctl(PR_SET_NAME)``. + binary (google.cloud.securitycenter_v1.types.File): + File information for the process executable. + libraries (MutableSequence[google.cloud.securitycenter_v1.types.File]): + File information for libraries loaded by the + process. + script (google.cloud.securitycenter_v1.types.File): + When the process represents the invocation of a script, + ``binary`` provides information about the interpreter, while + ``script`` provides information about the script file + provided to the interpreter. + args (MutableSequence[str]): + Process arguments as JSON encoded strings. + arguments_truncated (bool): + True if ``args`` is incomplete. + env_variables (MutableSequence[google.cloud.securitycenter_v1.types.EnvironmentVariable]): + Process environment variables. + env_variables_truncated (bool): + True if ``env_variables`` is incomplete. + pid (int): + The process ID. + parent_pid (int): + The parent process ID. + """ + + name: str = proto.Field( + proto.STRING, + number=12, + ) + binary: file.File = proto.Field( + proto.MESSAGE, + number=3, + message=file.File, + ) + libraries: MutableSequence[file.File] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=file.File, + ) + script: file.File = proto.Field( + proto.MESSAGE, + number=5, + message=file.File, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + arguments_truncated: bool = proto.Field( + proto.BOOL, + number=7, + ) + env_variables: MutableSequence['EnvironmentVariable'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='EnvironmentVariable', + ) + env_variables_truncated: bool = proto.Field( + proto.BOOL, + number=9, + ) + pid: int = proto.Field( + proto.INT64, + number=10, + ) + parent_pid: int = proto.Field( + proto.INT64, + number=11, + ) + + +class EnvironmentVariable(proto.Message): + r"""A name-value pair representing an environment variable used + in an operating system process. + + Attributes: + name (str): + Environment variable name as a JSON encoded + string. + val (str): + Environment variable value as a JSON encoded + string. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + val: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py new file mode 100644 index 000000000000..f66c0ab5f06d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py @@ -0,0 +1,474 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1.types import folder + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'CloudProvider', + 'Resource', + 'AwsMetadata', + 'AzureMetadata', + 'ResourcePath', + }, +) + + +class CloudProvider(proto.Enum): + r"""Enumeration representing the various cloud providers a + finding's resource could reside in. + + Values: + CLOUD_PROVIDER_UNSPECIFIED (0): + The cloud provider is unspecified. + GOOGLE_CLOUD_PLATFORM (1): + The cloud provider is Google Cloud Platform. + AMAZON_WEB_SERVICES (2): + The cloud provider is Amazon Web Services. + MICROSOFT_AZURE (3): + The cloud provider is Microsoft Azure. + """ + CLOUD_PROVIDER_UNSPECIFIED = 0 + GOOGLE_CLOUD_PLATFORM = 1 + AMAZON_WEB_SERVICES = 2 + MICROSOFT_AZURE = 3 + + +class Resource(proto.Message): + r"""Information related to the Google Cloud 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): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + display_name (str): + The human readable name of the resource. + type_ (str): + The full resource type of the resource. + project (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The project ID that the resource belongs to. + parent (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (MutableSequence[google.cloud.securitycenter_v1.types.Folder]): + Output only. Contains a Folder message for + each folder in the assets ancestry. The first + folder is the deepest nested folder, and the + last folder is the folder directly under the + Organization. + cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): + Indicates which cloud provider the resource + resides in. + organization (str): + Indicates which organization or tenant in the + cloud provider the finding applies to. + service (str): + The parent service or product from which the + resource is provided, for example, GKE or SNS. + location (str): + The region or location of the service (if + applicable). + aws_metadata (google.cloud.securitycenter_v1.types.AwsMetadata): + The AWS metadata associated with the finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + azure_metadata (google.cloud.securitycenter_v1.types.AzureMetadata): + The Azure metadata associated with the + finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + resource_path (google.cloud.securitycenter_v1.types.ResourcePath): + Provides the path to the resource within the + resource hierarchy. + resource_path_string (str): + A string representation of the resource path. For Google + Cloud, it has the format of + ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` + where there can be any number of folders. For AWS, it has + the format of + ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` + where there can be any number of organizational units. For + Azure, it has the format of + ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` + where there can be any number of management groups. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=8, + ) + type_: str = proto.Field( + proto.STRING, + number=6, + ) + project: str = proto.Field( + proto.STRING, + number=2, + ) + project_display_name: str = proto.Field( + proto.STRING, + number=3, + ) + parent: str = proto.Field( + proto.STRING, + number=4, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=5, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=folder.Folder, + ) + cloud_provider: 'CloudProvider' = proto.Field( + proto.ENUM, + number=9, + enum='CloudProvider', + ) + organization: str = proto.Field( + proto.STRING, + number=10, + ) + service: str = proto.Field( + proto.STRING, + number=11, + ) + location: str = proto.Field( + proto.STRING, + number=12, + ) + aws_metadata: 'AwsMetadata' = proto.Field( + proto.MESSAGE, + number=16, + oneof='cloud_provider_metadata', + message='AwsMetadata', + ) + azure_metadata: 'AzureMetadata' = proto.Field( + proto.MESSAGE, + number=17, + oneof='cloud_provider_metadata', + message='AzureMetadata', + ) + resource_path: 'ResourcePath' = proto.Field( + proto.MESSAGE, + number=18, + message='ResourcePath', + ) + resource_path_string: str = proto.Field( + proto.STRING, + number=19, + ) + + +class AwsMetadata(proto.Message): + r"""AWS metadata associated with the resource, only applicable if + the finding's cloud provider is Amazon Web Services. + + Attributes: + organization (google.cloud.securitycenter_v1.types.AwsMetadata.AwsOrganization): + The AWS organization associated with the + resource. + organizational_units (MutableSequence[google.cloud.securitycenter_v1.types.AwsMetadata.AwsOrganizationalUnit]): + A list of AWS organizational units associated + with the resource, ordered from lowest level + (closest to the account) to highest level. + account (google.cloud.securitycenter_v1.types.AwsMetadata.AwsAccount): + The AWS account associated with the resource. + """ + + class AwsOrganization(proto.Message): + r"""An organization is a collection of accounts that are + centrally managed together using consolidated billing, organized + hierarchically with organizational units (OUs), and controlled + with policies. + + Attributes: + id (str): + The unique identifier (ID) for the + organization. The regex pattern for an + organization ID string requires "o-" followed by + from 10 to 32 lowercase letters or digits. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + + class AwsOrganizationalUnit(proto.Message): + r"""An Organizational Unit (OU) is a container of AWS accounts + within a root of an organization. Policies that are attached to + an OU apply to all accounts contained in that OU and in any + child OUs. + + Attributes: + id (str): + The unique identifier (ID) associated with + this OU. The regex pattern for an organizational + unit ID string requires "ou-" followed by from 4 + to 32 lowercase letters or digits (the ID of the + root that contains the OU). This string is + followed by a second "-" dash and from 8 to 32 + additional lowercase letters or digits. For + example, "ou-ab12-cd34ef56". + name (str): + The friendly name of the OU. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + + class AwsAccount(proto.Message): + r"""An AWS account that is a member of an organization. + + Attributes: + id (str): + The unique identifier (ID) of the account, + containing exactly 12 digits. + name (str): + The friendly name of this account. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + + organization: AwsOrganization = proto.Field( + proto.MESSAGE, + number=2, + message=AwsOrganization, + ) + organizational_units: MutableSequence[AwsOrganizationalUnit] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=AwsOrganizationalUnit, + ) + account: AwsAccount = proto.Field( + proto.MESSAGE, + number=4, + message=AwsAccount, + ) + + +class AzureMetadata(proto.Message): + r"""Azure metadata associated with the resource, only applicable + if the finding's cloud provider is Microsoft Azure. + + Attributes: + management_groups (MutableSequence[google.cloud.securitycenter_v1.types.AzureMetadata.AzureManagementGroup]): + A list of Azure management groups associated + with the resource, ordered from lowest level + (closest to the subscription) to highest level. + subscription (google.cloud.securitycenter_v1.types.AzureMetadata.AzureSubscription): + The Azure subscription associated with the + resource. + resource_group (google.cloud.securitycenter_v1.types.AzureMetadata.AzureResourceGroup): + The Azure resource group associated with the + resource. + """ + + class AzureManagementGroup(proto.Message): + r"""Represents an Azure management group. + + Attributes: + id (str): + The UUID of the Azure management group, for example, + ``20000000-0001-0000-0000-000000000000``. + display_name (str): + The display name of the Azure management + group. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + class AzureSubscription(proto.Message): + r"""Represents an Azure subscription. + + Attributes: + id (str): + The UUID of the Azure subscription, for example, + ``291bba3f-e0a5-47bc-a099-3bdcb2a50a05``. + display_name (str): + The display name of the Azure subscription. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + class AzureResourceGroup(proto.Message): + r"""Represents an Azure resource group. + + Attributes: + name (str): + The name of the Azure resource group. This is + not a UUID. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + management_groups: MutableSequence[AzureManagementGroup] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=AzureManagementGroup, + ) + subscription: AzureSubscription = proto.Field( + proto.MESSAGE, + number=5, + message=AzureSubscription, + ) + resource_group: AzureResourceGroup = proto.Field( + proto.MESSAGE, + number=6, + message=AzureResourceGroup, + ) + + +class ResourcePath(proto.Message): + r"""Represents the path of resources leading up to the resource + this finding is about. + + Attributes: + nodes (MutableSequence[google.cloud.securitycenter_v1.types.ResourcePath.ResourcePathNode]): + The list of nodes that make the up resource + path, ordered from lowest level to highest + level. + """ + class ResourcePathNodeType(proto.Enum): + r"""The type of resource the node represents. + + Values: + RESOURCE_PATH_NODE_TYPE_UNSPECIFIED (0): + Node type is unspecified. + GCP_ORGANIZATION (1): + The node represents a Google Cloud + organization. + GCP_FOLDER (2): + The node represents a Google Cloud folder. + GCP_PROJECT (3): + The node represents a Google Cloud project. + AWS_ORGANIZATION (4): + The node represents an AWS organization. + AWS_ORGANIZATIONAL_UNIT (5): + The node represents an AWS organizational + unit. + AWS_ACCOUNT (6): + The node represents an AWS account. + AZURE_MANAGEMENT_GROUP (7): + The node represents an Azure management + group. + AZURE_SUBSCRIPTION (8): + The node represents an Azure subscription. + AZURE_RESOURCE_GROUP (9): + The node represents an Azure resource group. + """ + RESOURCE_PATH_NODE_TYPE_UNSPECIFIED = 0 + GCP_ORGANIZATION = 1 + GCP_FOLDER = 2 + GCP_PROJECT = 3 + AWS_ORGANIZATION = 4 + AWS_ORGANIZATIONAL_UNIT = 5 + AWS_ACCOUNT = 6 + AZURE_MANAGEMENT_GROUP = 7 + AZURE_SUBSCRIPTION = 8 + AZURE_RESOURCE_GROUP = 9 + + class ResourcePathNode(proto.Message): + r"""A node within the resource path. Each node represents a + resource within the resource hierarchy. + + Attributes: + node_type (google.cloud.securitycenter_v1.types.ResourcePath.ResourcePathNodeType): + The type of resource this node represents. + id (str): + The ID of the resource this node represents. + display_name (str): + The display name of the resource this node + represents. + """ + + node_type: 'ResourcePath.ResourcePathNodeType' = proto.Field( + proto.ENUM, + number=1, + enum='ResourcePath.ResourcePathNodeType', + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + + nodes: MutableSequence[ResourcePathNode] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ResourcePathNode, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py new file mode 100644 index 000000000000..f88354103169 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1.types import resource +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'ResourceValue', + 'ResourceValueConfig', + }, +) + + +class ResourceValue(proto.Enum): + r"""Value enum to map to a resource + + Values: + RESOURCE_VALUE_UNSPECIFIED (0): + Unspecific value + HIGH (1): + High resource value + MEDIUM (2): + Medium resource value + LOW (3): + Low resource value + NONE (4): + No resource value, e.g. ignore these + resources + """ + RESOURCE_VALUE_UNSPECIFIED = 0 + HIGH = 1 + MEDIUM = 2 + LOW = 3 + NONE = 4 + + +class ResourceValueConfig(proto.Message): + r"""A resource value configuration (RVC) is a mapping + configuration of user's resources to resource values. Used in + Attack path simulations. + + Attributes: + name (str): + Name for the resource value configuration + resource_value (google.cloud.securitycenter_v1.types.ResourceValue): + Required. Resource value level this + expression represents + tag_values (MutableSequence[str]): + Required. Tag values combined with ``AND`` to check against. + Values in the form "tagValues/123" Example: + ``[ "tagValues/123", "tagValues/456", "tagValues/789" ]`` + https://cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing + resource_type (str): + Apply resource_value only to resources that match + resource_type. resource_type will be checked with ``AND`` of + other resources. For example, + "storage.googleapis.com/Bucket" with resource_value "HIGH" + will apply "HIGH" value only to + "storage.googleapis.com/Bucket" resources. + scope (str): + Project or folder to scope this configuration to. For + example, "project/456" would apply this configuration only + to resources in "project/456" scope will be checked with + ``AND`` of other resources. + resource_labels_selector (MutableMapping[str, str]): + List of resource labels to search for, evaluated with + ``AND``. For example, + ``"resource_labels_selector": {"key": "value", "env": "prod"}`` + will match resources with labels "key": "value" ``AND`` + "env": "prod" + https://cloud.google.com/resource-manager/docs/creating-managing-labels + description (str): + Description of the resource value + configuration. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp this resource value + configuration was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp this resource value + configuration was last updated. + cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): + Cloud provider this configuration applies to + sensitive_data_protection_mapping (google.cloud.securitycenter_v1.types.ResourceValueConfig.SensitiveDataProtectionMapping): + A mapping of the sensitivity on Sensitive Data Protection + finding to resource values. This mapping can only be used in + combination with a resource_type that is related to + BigQuery, e.g. "bigquery.googleapis.com/Dataset". + """ + + class SensitiveDataProtectionMapping(proto.Message): + r"""Resource value mapping for Sensitive Data Protection findings. If + any of these mappings have a resource value that is not unspecified, + the resource_value field will be ignored when reading this + configuration. + + Attributes: + high_sensitivity_mapping (google.cloud.securitycenter_v1.types.ResourceValue): + Resource value mapping for high-sensitivity + Sensitive Data Protection findings + medium_sensitivity_mapping (google.cloud.securitycenter_v1.types.ResourceValue): + Resource value mapping for medium-sensitivity + Sensitive Data Protection findings + """ + + high_sensitivity_mapping: 'ResourceValue' = proto.Field( + proto.ENUM, + number=1, + enum='ResourceValue', + ) + medium_sensitivity_mapping: 'ResourceValue' = proto.Field( + proto.ENUM, + number=2, + enum='ResourceValue', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_value: 'ResourceValue' = proto.Field( + proto.ENUM, + number=2, + enum='ResourceValue', + ) + tag_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + resource_type: str = proto.Field( + proto.STRING, + number=4, + ) + scope: str = proto.Field( + proto.STRING, + number=5, + ) + resource_labels_selector: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + description: str = proto.Field( + proto.STRING, + number=7, + ) + 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, + ) + cloud_provider: resource.CloudProvider = proto.Field( + proto.ENUM, + number=10, + enum=resource.CloudProvider, + ) + sensitive_data_protection_mapping: SensitiveDataProtectionMapping = proto.Field( + proto.MESSAGE, + number=11, + message=SensitiveDataProtectionMapping, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py new file mode 100644 index 000000000000..e6ccc16862c3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.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 + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'RunAssetDiscoveryResponse', + }, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + + Attributes: + state (google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (google.protobuf.duration_pb2.Duration): + The duration between asset discovery run + start and end + """ + class State(proto.Enum): + r"""The state of an asset discovery run. + + Values: + STATE_UNSPECIFIED (0): + Asset discovery run state was unspecified. + COMPLETED (1): + Asset discovery run completed successfully. + SUPERSEDED (2): + Asset discovery run was cancelled with tasks + still pending, as another run for the same + organization was started with a higher priority. + TERMINATED (3): + Asset discovery run was killed and + terminated. + """ + STATE_UNSPECIFIED = 0 + COMPLETED = 1 + SUPERSEDED = 2 + TERMINATED = 3 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py new file mode 100644 index 000000000000..bb412145607c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py @@ -0,0 +1,173 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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 expr_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'CustomConfig', + }, +) + + +class CustomConfig(proto.Message): + r"""Defines the properties in a custom module configuration for + Security Health Analytics. Use the custom module configuration + to create custom detectors that generate custom findings for + resources that you specify. + + Attributes: + predicate (google.type.expr_pb2.Expr): + The CEL expression to evaluate to produce + findings. When the expression evaluates to true + against a resource, a finding is generated. + custom_output (google.cloud.securitycenter_v1.types.CustomConfig.CustomOutputSpec): + Custom output properties. + resource_selector (google.cloud.securitycenter_v1.types.CustomConfig.ResourceSelector): + The resource types that the custom module + operates on. Each custom module can specify up + to 5 resource types. + severity (google.cloud.securitycenter_v1.types.CustomConfig.Severity): + The severity to assign to findings generated + by the module. + description (str): + Text that describes the vulnerability or + misconfiguration that the custom module detects. + This explanation is returned with each finding + instance to help investigators understand the + detected issue. The text must be enclosed in + quotation marks. + recommendation (str): + An explanation of the recommended steps that security teams + can take to resolve the detected issue. This explanation is + returned with each finding generated by this module in the + ``nextSteps`` property of the finding JSON. + """ + class Severity(proto.Enum): + r"""Defines the valid value options for the severity of a + finding. + + Values: + SEVERITY_UNSPECIFIED (0): + Unspecified severity. + 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 + + class CustomOutputSpec(proto.Message): + r"""A set of optional name-value pairs that define custom source + properties to return with each finding that is generated by the + custom module. The custom source properties that are defined here + are included in the finding JSON under ``sourceProperties``. + + Attributes: + properties (MutableSequence[google.cloud.securitycenter_v1.types.CustomConfig.CustomOutputSpec.Property]): + A list of custom output properties to add to + the finding. + """ + + class Property(proto.Message): + r"""An individual name-value pair that defines a custom source + property. + + Attributes: + name (str): + Name of the property for the custom output. + value_expression (google.type.expr_pb2.Expr): + The CEL expression for the custom output. A + resource property can be specified to return the + value of the property or a text string enclosed + in quotation marks. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value_expression: expr_pb2.Expr = proto.Field( + proto.MESSAGE, + number=2, + message=expr_pb2.Expr, + ) + + properties: MutableSequence['CustomConfig.CustomOutputSpec.Property'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CustomConfig.CustomOutputSpec.Property', + ) + + class ResourceSelector(proto.Message): + r"""Resource for selecting resource type. + + Attributes: + resource_types (MutableSequence[str]): + The resource types to run the detector on. + """ + + resource_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + predicate: expr_pb2.Expr = proto.Field( + proto.MESSAGE, + number=1, + message=expr_pb2.Expr, + ) + custom_output: CustomOutputSpec = proto.Field( + proto.MESSAGE, + number=2, + message=CustomOutputSpec, + ) + resource_selector: ResourceSelector = proto.Field( + proto.MESSAGE, + number=3, + message=ResourceSelector, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=4, + enum=Severity, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + recommendation: str = proto.Field( + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.py new file mode 100644 index 000000000000..654cd7d75826 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'SecurityHealthAnalyticsCustomModule', + }, +) + + +class SecurityHealthAnalyticsCustomModule(proto.Message): + r"""Represents an instance of a Security Health Analytics custom + module, including its full module name, display name, enablement + state, and last updated time. You can create a custom module at + the organization, folder, or project level. Custom modules that + you create at the organization or folder level are inherited by + the child folders and projects. + + Attributes: + name (str): + Immutable. The resource name of the custom + module. Its format is + "organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}", + or + "folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}", + or + "projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}" + + The id {customModule} is server-generated and is + not user settable. It will be a numeric id + containing 1-20 digits. + display_name (str): + The display name of the Security Health + Analytics custom module. This display name + becomes the finding category for all findings + that are returned by this custom module. The + display name must be between 1 and 128 + characters, start with a lowercase letter, and + contain alphanumeric characters or underscores + only. + enablement_state (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule.EnablementState): + The enablement state of the custom module. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the custom + module was last updated. + last_editor (str): + Output only. The editor that last updated the + custom module. + ancestor_module (str): + Output only. If empty, indicates that the custom module was + created in the organization, folder, or project in which you + are viewing the custom module. Otherwise, + ``ancestor_module`` specifies the organization or folder + from which the custom module is inherited. + custom_config (google.cloud.securitycenter_v1.types.CustomConfig): + The user specified custom configuration for + the module. + """ + class EnablementState(proto.Enum): + r"""Possible enablement states of a custom module. + + Values: + ENABLEMENT_STATE_UNSPECIFIED (0): + Unspecified enablement state. + ENABLED (1): + The module is enabled at the given CRM + resource. + DISABLED (2): + The module is disabled at the given CRM + resource. + INHERITED (3): + State is inherited from an ancestor module. + The module will either be effectively ENABLED or + DISABLED based on its closest non-inherited + ancestor module in the CRM hierarchy. + """ + ENABLEMENT_STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + INHERITED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + enablement_state: EnablementState = proto.Field( + proto.ENUM, + number=4, + enum=EnablementState, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + last_editor: str = proto.Field( + proto.STRING, + number=6, + ) + ancestor_module: str = proto.Field( + proto.STRING, + number=7, + ) + custom_config: security_health_analytics_custom_config.CustomConfig = proto.Field( + proto.MESSAGE, + number=8, + message=security_health_analytics_custom_config.CustomConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.py new file mode 100644 index 000000000000..4c141c1aa108 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'SecurityMarks', + }, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". + marks (MutableMapping[str, str]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + canonical_name (str): + The canonical name of the marks. Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "folders/{folder_id}/assets/{asset_id}/securityMarks" + "projects/{project_number}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + marks: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.py new file mode 100644 index 000000000000..c929af3ef59a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'SecurityPosture', + }, +) + + +class SecurityPosture(proto.Message): + r"""Represents a posture that is deployed on Google Cloud by the + Security Command Center Posture Management service. A posture + contains one or more policy sets. A policy set is a group of + policies that enforce a set of security rules on Google Cloud. + + Attributes: + name (str): + Name of the posture, for example, ``CIS-Posture``. + revision_id (str): + The version of the posture, for example, ``c7cfa2a8``. + posture_deployment_resource (str): + The project, folder, or organization on which the posture is + deployed, for example, ``projects/{project_number}``. + posture_deployment (str): + The name of the posture deployment, for example, + ``organizations/{org_id}/posturedeployments/{posture_deployment_id}``. + changed_policy (str): + The name of the updated policy, for example, + ``projects/{project_id}/policies/{constraint_name}``. + policy_set (str): + The name of the updated policyset, for example, + ``cis-policyset``. + policy (str): + The ID of the updated policy, for example, + ``compute-policy-1``. + policy_drift_details (MutableSequence[google.cloud.securitycenter_v1.types.SecurityPosture.PolicyDriftDetails]): + The details about a change in an updated + policy that violates the deployed posture. + """ + + class PolicyDriftDetails(proto.Message): + r"""The policy field that violates the deployed posture and its + expected and detected values. + + Attributes: + field (str): + The name of the updated field, for example + constraint.implementation.policy_rules[0].enforce + expected_value (str): + The value of this field that was configured in a posture, + for example, ``true`` or + ``allowed_values={"projects/29831892"}``. + detected_value (str): + The detected value that violates the deployed posture, for + example, ``false`` or + ``allowed_values={"projects/22831892"}``. + """ + + field: str = proto.Field( + proto.STRING, + number=1, + ) + expected_value: str = proto.Field( + proto.STRING, + number=2, + ) + detected_value: str = proto.Field( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + ) + posture_deployment_resource: str = proto.Field( + proto.STRING, + number=3, + ) + posture_deployment: str = proto.Field( + proto.STRING, + number=4, + ) + changed_policy: str = proto.Field( + proto.STRING, + number=5, + ) + policy_set: str = proto.Field( + proto.STRING, + number=6, + ) + policy: str = proto.Field( + proto.STRING, + number=7, + ) + policy_drift_details: MutableSequence[PolicyDriftDetails] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=PolicyDriftDetails, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py new file mode 100644 index 000000000000..385bd4c37c53 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py @@ -0,0 +1,3494 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1.types import asset as gcs_asset +from google.cloud.securitycenter_v1.types import attack_path +from google.cloud.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import folder +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import resource as gcs_resource +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import valued_resource +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'BulkMuteFindingsRequest', + 'BulkMuteFindingsResponse', + 'CreateFindingRequest', + 'CreateMuteConfigRequest', + 'CreateResourceValueConfigRequest', + 'BatchCreateResourceValueConfigsRequest', + 'BatchCreateResourceValueConfigsResponse', + 'DeleteResourceValueConfigRequest', + 'GetResourceValueConfigRequest', + 'ListResourceValueConfigsRequest', + 'ListResourceValueConfigsResponse', + 'UpdateResourceValueConfigRequest', + 'CreateNotificationConfigRequest', + 'CreateSecurityHealthAnalyticsCustomModuleRequest', + 'CreateSourceRequest', + 'DeleteMuteConfigRequest', + 'DeleteNotificationConfigRequest', + 'DeleteSecurityHealthAnalyticsCustomModuleRequest', + 'GetBigQueryExportRequest', + 'GetMuteConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', + 'GetSecurityHealthAnalyticsCustomModuleRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', + 'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', + 'ListValuedResourcesRequest', + 'ListValuedResourcesResponse', + 'ListAttackPathsRequest', + 'ListAttackPathsResponse', + 'GetSimulationRequest', + 'GetValuedResourceRequest', + 'ListMuteConfigsRequest', + 'ListMuteConfigsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', + 'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', + 'ListSecurityHealthAnalyticsCustomModulesRequest', + 'ListSecurityHealthAnalyticsCustomModulesResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'SetFindingStateRequest', + 'SetMuteRequest', + 'RunAssetDiscoveryRequest', + 'SimulateSecurityHealthAnalyticsCustomModuleRequest', + 'SimulateSecurityHealthAnalyticsCustomModuleResponse', + 'UpdateExternalSystemRequest', + 'UpdateFindingRequest', + 'UpdateMuteConfigRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityHealthAnalyticsCustomModuleRequest', + 'UpdateSourceRequest', + 'UpdateSecurityMarksRequest', + 'CreateBigQueryExportRequest', + 'UpdateBigQueryExportRequest', + 'ListBigQueryExportsRequest', + 'ListBigQueryExportsResponse', + 'DeleteBigQueryExportRequest', + 'CreateEventThreatDetectionCustomModuleRequest', + 'ValidateEventThreatDetectionCustomModuleRequest', + 'ValidateEventThreatDetectionCustomModuleResponse', + 'DeleteEventThreatDetectionCustomModuleRequest', + 'GetEventThreatDetectionCustomModuleRequest', + 'ListDescendantEventThreatDetectionCustomModulesRequest', + 'ListDescendantEventThreatDetectionCustomModulesResponse', + 'ListEventThreatDetectionCustomModulesRequest', + 'ListEventThreatDetectionCustomModulesResponse', + 'UpdateEventThreatDetectionCustomModuleRequest', + 'GetEffectiveEventThreatDetectionCustomModuleRequest', + 'ListEffectiveEventThreatDetectionCustomModulesRequest', + 'ListEffectiveEventThreatDetectionCustomModulesResponse', + }, +) + + +class BulkMuteFindingsRequest(proto.Message): + r"""Request message for bulk findings update. + + Note: + + 1. If multiple bulk update requests match the same resource, the + order in which they get executed is not defined. + 2. Once a bulk operation is started, there is no way to stop it. + + Attributes: + parent (str): + Required. The parent, at which bulk action needs to be + applied. Its format is ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + filter (str): + Expression that identifies findings that should be updated. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + mute_annotation (str): + This can be a mute configuration name or any + identifier for mute/unmute of findings based on + the filter. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + mute_annotation: str = proto.Field( + proto.STRING, + number=3, + ) + + +class BulkMuteFindingsResponse(proto.Message): + r"""The response to a BulkMute request. Contains the LRO + information. + + """ + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + + Attributes: + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + ``organizations/[organization_id]/sources/[source_id]``. + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + alphanumeric and less than or equal to 32 + characters and greater than 0 characters in + length. + finding (google.cloud.securitycenter_v1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + finding_id: str = proto.Field( + proto.STRING, + number=2, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_finding.Finding, + ) + + +class CreateMuteConfigRequest(proto.Message): + r"""Request message for creating a mute config. + + Attributes: + parent (str): + Required. Resource name of the new mute configs's parent. + Its format is ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + mute_config (google.cloud.securitycenter_v1.types.MuteConfig): + Required. The mute config being created. + mute_config_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must consist + of only lowercase letters, numbers, and hyphens, + must start with a letter, must end with either a + letter or a number, and must be 63 characters or + less. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + mute_config: gcs_mute_config.MuteConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_mute_config.MuteConfig, + ) + mute_config_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateResourceValueConfigRequest(proto.Message): + r"""Request message to create single resource value config + + Attributes: + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. + resource_value_config (google.cloud.securitycenter_v1.types.ResourceValueConfig): + Required. The resource value config being + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_resource_value_config.ResourceValueConfig, + ) + + +class BatchCreateResourceValueConfigsRequest(proto.Message): + r"""Request message to create multiple resource value configs + + Attributes: + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. The parent field + in the CreateResourceValueConfigRequest messages + must either be empty or match this field. + requests (MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]): + Required. The resource value configs to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence['CreateResourceValueConfigRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='CreateResourceValueConfigRequest', + ) + + +class BatchCreateResourceValueConfigsResponse(proto.Message): + r"""Response message for BatchCreateResourceValueConfigs + + Attributes: + resource_value_configs (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfig]): + The resource value configs created + """ + + resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + + +class DeleteResourceValueConfigRequest(proto.Message): + r"""Request message to delete resource value config + + Attributes: + name (str): + Required. Name of the ResourceValueConfig to + delete + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetResourceValueConfigRequest(proto.Message): + r"""Request message to get resource value config + + Attributes: + name (str): + Required. Name of the resource value config to retrieve. Its + format is + ``organizations/{organization}/resourceValueConfigs/{config_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListResourceValueConfigsRequest(proto.Message): + r"""Request message to list resource value configs of a parent + + Attributes: + parent (str): + Required. The parent, which owns the collection of resource + value configs. Its format is + ``organizations/[organization_id]`` + page_size (int): + The number of results to return. The service + may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous + ``ListResourceValueConfigs`` call. Provide this to retrieve + the subsequent page. + + When paginating, all other parameters provided to + ``ListResourceValueConfigs`` must match the call that + provided the page token. + + page_size can be specified, and the new page_size 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, + ) + + +class ListResourceValueConfigsResponse(proto.Message): + r"""Response message to list resource value configs + + Attributes: + resource_value_configs (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfig]): + The resource value configs from the specified + parent. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is empty, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateResourceValueConfigRequest(proto.Message): + r"""Request message to update resource value config + + Attributes: + resource_value_config (google.cloud.securitycenter_v1.types.ResourceValueConfig): + Required. The resource value config being + updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class CreateNotificationConfigRequest(proto.Message): + r"""Request message for creating a notification config. + + Attributes: + parent (str): + Required. Resource name of the new notification config's + parent. Its format is ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + config_id (str): + Required. + Unique identifier provided by the client within + the parent scope. It must be between 1 and 128 + characters and contain alphanumeric characters, + underscores, or hyphens only. + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): + Required. The notification config being + created. The name and the service account will + be ignored as they are both output only fields + on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + config_id: str = proto.Field( + proto.STRING, + number=2, + ) + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_notification_config.NotificationConfig, + ) + + +class CreateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): + r"""Request message for creating Security Health Analytics custom + modules. + + Attributes: + parent (str): + Required. Resource name of the new custom module's parent. + Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): + Required. SecurityHealthAnalytics custom + module to create. The provided name is ignored + and reset with provided parent information and + server-generated ID. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + security_health_analytics_custom_module: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be ``organizations/[organization_id]``. + source (google.cloud.securitycenter_v1.types.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_source.Source, + ) + + +class DeleteMuteConfigRequest(proto.Message): + r"""Request message for deleting a mute config. + + Attributes: + name (str): + Required. Name of the mute config to delete. Its format is + ``organizations/{organization}/muteConfigs/{config_id}``, + ``folders/{folder}/muteConfigs/{config_id}``, + ``projects/{project}/muteConfigs/{config_id}``, + ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, + ``folders/{folder}/locations/global/muteConfigs/{config_id}``, + or + ``projects/{project}/locations/global/muteConfigs/{config_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteNotificationConfigRequest(proto.Message): + r"""Request message for deleting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to delete. Its + format is + ``organizations/[organization_id]/notificationConfigs/[config_id]``, + ``folders/[folder_id]/notificationConfigs/[config_id]``, or + ``projects/[project_id]/notificationConfigs/[config_id]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteSecurityHealthAnalyticsCustomModuleRequest(proto.Message): + r"""Request message for deleting Security Health Analytics custom + modules. + + Attributes: + name (str): + Required. Name of the custom module to delete. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetBigQueryExportRequest(proto.Message): + r"""Request message for retrieving a BigQuery export. + + Attributes: + name (str): + Required. Name of the BigQuery export to retrieve. Its + format is + ``organizations/{organization}/bigQueryExports/{export_id}``, + ``folders/{folder}/bigQueryExports/{export_id}``, or + ``projects/{project}/bigQueryExports/{export_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetMuteConfigRequest(proto.Message): + r"""Request message for retrieving a mute config. + + Attributes: + name (str): + Required. Name of the mute config to retrieve. Its format is + ``organizations/{organization}/muteConfigs/{config_id}``, + ``folders/{folder}/muteConfigs/{config_id}``, + ``projects/{project}/muteConfigs/{config_id}``, + ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, + ``folders/{folder}/locations/global/muteConfigs/{config_id}``, + or + ``projects/{project}/locations/global/muteConfigs/{config_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetNotificationConfigRequest(proto.Message): + r"""Request message for getting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to get. Its format + is + ``organizations/[organization_id]/notificationConfigs/[config_id]``, + ``folders/[folder_id]/notificationConfigs/[config_id]``, or + ``projects/[project_id]/notificationConfigs/[config_id]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetOrganizationSettingsRequest(proto.Message): + r"""Request message for getting organization settings. + + Attributes: + name (str): + Required. Name of the organization to get organization + settings for. Its format is + ``organizations/[organization_id]/organizationSettings``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(proto.Message): + r"""Request message for getting effective Security Health + Analytics custom modules. + + Attributes: + name (str): + Required. Name of the effective custom module to get. Its + format is + ``organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSecurityHealthAnalyticsCustomModuleRequest(proto.Message): + r"""Request message for getting Security Health Analytics custom + modules. + + Attributes: + name (str): + Required. Name of the custom module to get. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is ``organizations/[organization_id]/source/[source_id]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GroupAssetsRequest(proto.Message): + r"""Request message for grouping by assets. + + Attributes: + parent (str): + Required. The name of the parent to group the assets by. Its + format is ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, + ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is + not set: + + - security_center_properties.resource_project + - security_center_properties.resource_project_display_name + - security_center_properties.resource_type + - security_center_properties.resource_parent + - security_center_properties.resource_parent_display_name + + The following fields are supported when compare_duration is + set: + + - security_center_properties.resource_type + - security_center_properties.resource_project_display_name + - security_center_properties.resource_parent_display_name + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the GroupResult's + "state_change" property is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at + reference_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and reference_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupAssetsResponse``; + indicates that this is a continuation of a prior + ``GroupAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupAssetsResponse(proto.Message): + r"""Response message for grouping by assets. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + + Attributes: + parent (str): + Required. Name of the source to groupBy. Its format is + ``organizations/[organization_id]/sources/[source_id]``, + ``folders/[folder_id]/sources/[source_id]``, or + ``projects/[project_id]/sources/[source_id]``. To groupBy + across all sources provide a source_id of ``-``. For + example: + ``organizations/{organization_id}/sources/-, folders/{folder_id}/sources/-``, + or ``projects/{project_id}/sources/-`` + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - severity: ``=``, ``:`` + + - workflow_state: ``=``, ``:`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based + on a property existing: + ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + + - resource: + + - resource.name: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping (including ``state_change``). The string value + should follow SQL syntax: comma separated list of fields. + For example: "parent,resource_name". + + The following fields are supported when compare_duration is + set: + + - state_change + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the GroupResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=struct_pb2.Value, + ) + count: int = proto.Field( + proto.INT64, + number=2, + ) + + +class ListDescendantSecurityHealthAnalyticsCustomModulesRequest(proto.Message): + r"""Request message for listing descendant Security Health + Analytics custom modules. + + Attributes: + parent (str): + Required. Name of parent to list descendant custom modules. + Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + page_token (str): + The value returned by the last call + indicating a continuation + """ + + 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 ListDescendantSecurityHealthAnalyticsCustomModulesResponse(proto.Message): + r"""Response message for listing descendant Security Health + Analytics custom modules. + + Attributes: + security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule]): + Custom modules belonging to the requested + parent and its descendants. + next_page_token (str): + If not empty, indicates that there may be + more custom modules to be returned. + """ + + @property + def raw_page(self): + return self + + security_health_analytics_custom_modules: MutableSequence[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListValuedResourcesRequest(proto.Message): + r"""Request message for listing the valued resources for a given + simulation. + + Attributes: + parent (str): + Required. Name of parent to list valued resources. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + filter (str): + The filter expression that filters the valued resources in + the response. Supported fields: + + - ``resource_value`` supports = + - ``resource_type`` supports = + page_token (str): + The value returned by the last + ``ListValuedResourcesResponse``; indicates that this is a + continuation of a prior ``ListValuedResources`` call, and + that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + order_by (str): + Optional. The fields by which to order the valued resources + response. + + Supported fields: + + - ``exposed_score`` + + - ``resource_value`` + + - ``resource_type`` + + - ``resource`` + + - ``display_name`` + + Values should be a comma separated list of fields. For + example: ``exposed_score,resource_value``. + + The default sorting order is descending. To specify + ascending or descending order for a field, append a ``ASC`` + or a ``DESC`` suffix, respectively; for example: + ``exposed_score DESC``. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListValuedResourcesResponse(proto.Message): + r"""Response message for listing the valued resources for a given + simulation. + + Attributes: + valued_resources (MutableSequence[google.cloud.securitycenter_v1.types.ValuedResource]): + The valued resources that the attack path + simulation identified. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The estimated total number of results + matching the query. + """ + + @property + def raw_page(self): + return self + + valued_resources: MutableSequence[valued_resource.ValuedResource] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=valued_resource.ValuedResource, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListAttackPathsRequest(proto.Message): + r"""Request message for listing the attack paths for a given + simulation or valued resource. + + Attributes: + parent (str): + Required. Name of parent to list attack paths. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + filter (str): + The filter expression that filters the attack path in the + response. Supported fields: + + - ``valued_resources`` supports = + page_token (str): + The value returned by the last ``ListAttackPathsResponse``; + indicates that this is a continuation of a prior + ``ListAttackPaths`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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 ListAttackPathsResponse(proto.Message): + r"""Response message for listing the attack paths for a given + simulation or valued resource. + + Attributes: + attack_paths (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath]): + The attack paths that the attack path + simulation identified. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + attack_paths: MutableSequence[attack_path.AttackPath] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=attack_path.AttackPath, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetSimulationRequest(proto.Message): + r"""Request message for getting simulation. + Simulation name can include "latest" to retrieve the latest + simulation For example, "organizations/123/simulations/latest" + + Attributes: + name (str): + Required. The organization name or simulation name of this + simulation + + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetValuedResourceRequest(proto.Message): + r"""Request message for getting a valued resource. + + Attributes: + name (str): + Required. The name of this valued resource + + Valid format: + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListMuteConfigsRequest(proto.Message): + r"""Request message for listing mute configs at a given scope + e.g. organization, folder or project. + + Attributes: + parent (str): + Required. The parent, which owns the collection of mute + configs. Its format is ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + page_size (int): + The maximum number of configs to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListMuteConfigs`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListMuteConfigs`` 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 ListMuteConfigsResponse(proto.Message): + r"""Response message for listing mute configs. + + Attributes: + mute_configs (MutableSequence[google.cloud.securitycenter_v1.types.MuteConfig]): + The mute configs from the specified parent. + 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 + + mute_configs: MutableSequence[gcs_mute_config.MuteConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_mute_config.MuteConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListNotificationConfigsRequest(proto.Message): + r"""Request message for listing notification configs. + + Attributes: + parent (str): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]", "folders/[folder_id]", or + "projects/[project_id]". + page_token (str): + The value returned by the last + ``ListNotificationConfigsResponse``; indicates that this is + a continuation of a prior ``ListNotificationConfigs`` call, + and that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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 ListNotificationConfigsResponse(proto.Message): + r"""Response message for listing notification configs. + + Attributes: + notification_configs (MutableSequence[google.cloud.securitycenter_v1.types.NotificationConfig]): + Notification configs belonging to the + requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + notification_configs: MutableSequence[gcs_notification_config.NotificationConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(proto.Message): + r"""Request message for listing effective Security Health + Analytics custom modules. + + Attributes: + parent (str): + Required. Name of parent to list effective custom modules. + Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + page_token (str): + The value returned by the last call + indicating a continuation + """ + + 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 ListEffectiveSecurityHealthAnalyticsCustomModulesResponse(proto.Message): + r"""Response message for listing effective Security Health + Analytics custom modules. + + Attributes: + effective_security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule]): + Effective custom modules belonging to the + requested parent. + next_page_token (str): + If not empty, indicates that there may be + more effective custom modules to be returned. + """ + + @property + def raw_page(self): + return self + + effective_security_health_analytics_custom_modules: MutableSequence[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSecurityHealthAnalyticsCustomModulesRequest(proto.Message): + r"""Request message for listing Security Health Analytics custom + modules. + + Attributes: + parent (str): + Required. Name of parent to list custom modules. Its format + is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + page_token (str): + The value returned by the last call + indicating a continuation + """ + + 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 ListSecurityHealthAnalyticsCustomModulesResponse(proto.Message): + r"""Response message for listing Security Health Analytics custom + modules. + + Attributes: + security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule]): + Custom modules belonging to the requested + parent. + next_page_token (str): + If not empty, indicates that there may be + more custom modules to be returned. + """ + + @property + def raw_page(self): + return self + + security_health_analytics_custom_modules: MutableSequence[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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=7, + ) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v1.types.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAssetsRequest(proto.Message): + r"""Request message for listing assets. + + Attributes: + parent (str): + Required. The name of the parent resource that contains the + assets. The value that you can specify on parent depends on + the method in which you specify parent. You can specify one + of the following values: + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following are the allowed field and operator + combinations: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, + ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,resource_properties.a_property". + Redundant space characters in the syntax are insignificant. + "name desc,resource_properties.a_property" and " name desc , + resource_properties.a_property " are equivalent. + + The following fields are supported: name update_time + resource_properties security_marks.marks + security_center_properties.resource_name + security_center_properties.resource_display_name + security_center_properties.resource_parent + security_center_properties.resource_parent_display_name + security_center_properties.resource_project + security_center_properties.resource_project_display_name + security_center_properties.resource_type + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListAssetsResult's + "state_change" attribute is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at read_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at read_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the ListAssetsResult + fields to be listed in the response. + An empty field mask will list all fields. + page_token (str): + The value returned by the last ``ListAssetsResponse``; + indicates that this is a continuation of a prior + ``ListAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=9, + ) + + +class ListAssetsResponse(proto.Message): + r"""Response message for listing assets. + + Attributes: + list_assets_results (MutableSequence[google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of assets matching the + query. + """ + + class ListAssetsResult(proto.Message): + r"""Result containing the Asset and its State. + + Attributes: + asset (google.cloud.securitycenter_v1.types.Asset): + Asset matching the search request. + state_change (google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult.StateChange): + State change of the asset between the points + in time. + """ + class StateChange(proto.Enum): + r"""The change in state of the asset. + + When querying across two points in time this describes the change + between the two points: ADDED, REMOVED, or ACTIVE. If there was no + compare_duration supplied in the request the state change will be: + UNUSED + + Values: + UNUSED (0): + State change is unused, this is the canonical + default for this enum. + ADDED (1): + Asset was added between the points in time. + REMOVED (2): + Asset was removed between the points in time. + ACTIVE (3): + Asset was present at both point(s) in time. + """ + UNUSED = 0 + ADDED = 1 + REMOVED = 2 + ACTIVE = 3 + + asset: gcs_asset.Asset = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_asset.Asset, + ) + state_change: 'ListAssetsResponse.ListAssetsResult.StateChange' = proto.Field( + proto.ENUM, + number=2, + enum='ListAssetsResponse.ListAssetsResult.StateChange', + ) + + @property + def raw_page(self): + return self + + list_assets_results: MutableSequence[ListAssetsResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListAssetsResult, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + + Attributes: + parent (str): + Required. Name of the source the findings belong to. Its + format is + ``organizations/[organization_id]/sources/[source_id]``, + ``folders/[folder_id]/sources/[source_id]``, or + ``projects/[project_id]/sources/[source_id]``. To list + across all sources provide a source_id of ``-``. For + example: ``organizations/{organization_id}/sources/-``, + ``folders/{folder_id}/sources/-`` or + ``projects/{projects_id}/sources/-`` + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - severity: ``=``, ``:`` + + - workflow_state: ``=``, ``:`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based + on a property existing: + ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + + - resource: + + - resource.name: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + - resource.folders.resource_folder: ``=``, ``:`` + - resource.display_name: ``=``, ``:`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,source_properties.a_property". Redundant + space characters in the syntax are insignificant. "name + desc,source_properties.a_property" and " name desc , + source_properties.a_property " are equivalent. + + The following fields are supported: name parent state + category resource_name event_time source_properties + security_marks.marks + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListFindingsResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added in any state during + the compare_duration period of time that precedes the + read_time. This is the time between (read_time - + compare_duration) and read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the Finding fields to + be listed in the response. An empty field mask + will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=9, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + + Attributes: + list_findings_results (MutableSequence[google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult]): + Findings matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + class ListFindingsResult(proto.Message): + r"""Result containing the Finding and its StateChange. + + Attributes: + finding (google.cloud.securitycenter_v1.types.Finding): + Finding matching the search request. + state_change (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.StateChange): + State change of the finding between the + points in time. + resource (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.Resource): + Output only. Resource that is associated with + this finding. + """ + class StateChange(proto.Enum): + r"""The change in state of the finding. + + When querying across two points in time this describes the change in + the finding between the two points: CHANGED, UNCHANGED, ADDED, or + REMOVED. Findings can not be deleted, so REMOVED implies that the + finding at timestamp does not match the filter specified, but it did + at timestamp - compare_duration. If there was no compare_duration + supplied in the request the state change will be: UNUSED + + Values: + UNUSED (0): + State change is unused, this is the canonical + default for this enum. + CHANGED (1): + The finding has changed state in some way + between the points in time and existed at both + points. + UNCHANGED (2): + The finding has not changed state between the + points in time and existed at both points. + ADDED (3): + The finding was created between the points in + time. + REMOVED (4): + The finding at timestamp does not match the filter + specified, but it did at timestamp - compare_duration. + """ + UNUSED = 0 + CHANGED = 1 + UNCHANGED = 2 + ADDED = 3 + REMOVED = 4 + + class Resource(proto.Message): + r"""Information related to the Google Cloud resource that is + associated with this finding. + + 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): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + display_name (str): + The human readable name of the resource. + type_ (str): + The full resource type of the resource. + project_name (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The project ID that the resource belongs to. + parent_name (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (MutableSequence[google.cloud.securitycenter_v1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. + cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): + Indicates which cloud provider the finding is + from. + organization (str): + Indicates which organization / tenant the + finding is for. + service (str): + The service or resource provider associated + with the resource. + location (str): + The region or location of the service (if + applicable). + aws_metadata (google.cloud.securitycenter_v1.types.AwsMetadata): + The AWS metadata associated with the finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + azure_metadata (google.cloud.securitycenter_v1.types.AzureMetadata): + The Azure metadata associated with the + finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + resource_path (google.cloud.securitycenter_v1.types.ResourcePath): + Provides the path to the resource within the + resource hierarchy. + resource_path_string (str): + A string representation of the resource path. For Google + Cloud, it has the format of + ``org/{organization_id}/folder/{folder_id}/folder/{folder_id}/project/{project_id}`` + where there can be any number of folders. For AWS, it has + the format of + ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` + where there can be any number of organizational units. For + Azure, it has the format of + ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` + where there can be any number of management groups. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=8, + ) + type_: str = proto.Field( + proto.STRING, + number=6, + ) + project_name: str = proto.Field( + proto.STRING, + number=2, + ) + project_display_name: str = proto.Field( + proto.STRING, + number=3, + ) + parent_name: str = proto.Field( + proto.STRING, + number=4, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=5, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=folder.Folder, + ) + cloud_provider: gcs_resource.CloudProvider = proto.Field( + proto.ENUM, + number=9, + enum=gcs_resource.CloudProvider, + ) + organization: str = proto.Field( + proto.STRING, + number=10, + ) + service: str = proto.Field( + proto.STRING, + number=11, + ) + location: str = proto.Field( + proto.STRING, + number=12, + ) + aws_metadata: gcs_resource.AwsMetadata = proto.Field( + proto.MESSAGE, + number=16, + oneof='cloud_provider_metadata', + message=gcs_resource.AwsMetadata, + ) + azure_metadata: gcs_resource.AzureMetadata = proto.Field( + proto.MESSAGE, + number=17, + oneof='cloud_provider_metadata', + message=gcs_resource.AzureMetadata, + ) + resource_path: gcs_resource.ResourcePath = proto.Field( + proto.MESSAGE, + number=18, + message=gcs_resource.ResourcePath, + ) + resource_path_string: str = proto.Field( + proto.STRING, + number=19, + ) + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + state_change: 'ListFindingsResponse.ListFindingsResult.StateChange' = proto.Field( + proto.ENUM, + number=2, + enum='ListFindingsResponse.ListFindingsResult.StateChange', + ) + resource: 'ListFindingsResponse.ListFindingsResult.Resource' = proto.Field( + proto.MESSAGE, + number=3, + message='ListFindingsResponse.ListFindingsResult.Resource', + ) + + @property + def raw_page(self): + return self + + list_findings_results: MutableSequence[ListFindingsResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListFindingsResult, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + + Attributes: + name (str): + Required. The `relative resource + name `__ + of the finding. Example: + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, + ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. + state (google.cloud.securitycenter_v1.types.Finding.State): + Required. The desired State of the finding. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the updated state + takes effect. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: gcs_finding.Finding.State = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.State, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class SetMuteRequest(proto.Message): + r"""Request message for updating a finding's mute status. + + Attributes: + name (str): + Required. The `relative resource + name `__ + of the finding. Example: + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, + ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. + mute (google.cloud.securitycenter_v1.types.Finding.Mute): + Required. The desired state of the Mute. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + mute: gcs_finding.Finding.Mute = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.Mute, + ) + + +class RunAssetDiscoveryRequest(proto.Message): + r"""Request message for running asset discovery for an + organization. + + Attributes: + parent (str): + Required. Name of the organization to run asset discovery + for. Its format is ``organizations/[organization_id]``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class SimulateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): + r"""Request message to simulate a CustomConfig against a given + test resource. Maximum size of the request is 4 MB by default. + + Attributes: + parent (str): + Required. The relative resource name of the organization, + project, or folder. For more information about relative + resource names, see `Relative Resource + Name `__ + Example: ``organizations/{organization_id}`` + custom_config (google.cloud.securitycenter_v1.types.CustomConfig): + Required. The custom configuration that you + need to test. + resource (google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource): + Required. Resource data to simulate custom + module against. + """ + + class SimulatedResource(proto.Message): + r"""Manually constructed resource name. If the custom module evaluates + against only the resource data, you can omit the ``iam_policy_data`` + field. If it evaluates only the ``iam_policy_data`` field, you can + omit the resource data. + + Attributes: + resource_type (str): + Required. The type of the resource, for example, + ``compute.googleapis.com/Disk``. + resource_data (google.protobuf.struct_pb2.Struct): + Optional. A representation of the Google + Cloud resource. Should match the Google Cloud + resource JSON format. + iam_policy_data (google.iam.v1.policy_pb2.Policy): + Optional. A representation of the IAM policy. + """ + + resource_type: str = proto.Field( + proto.STRING, + number=1, + ) + resource_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + iam_policy_data: policy_pb2.Policy = proto.Field( + proto.MESSAGE, + number=3, + message=policy_pb2.Policy, + ) + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + custom_config: security_health_analytics_custom_config.CustomConfig = proto.Field( + proto.MESSAGE, + number=2, + message=security_health_analytics_custom_config.CustomConfig, + ) + resource: SimulatedResource = proto.Field( + proto.MESSAGE, + number=3, + message=SimulatedResource, + ) + + +class SimulateSecurityHealthAnalyticsCustomModuleResponse(proto.Message): + r"""Response message for simulating a + ``SecurityHealthAnalyticsCustomModule`` against a given resource. + + Attributes: + result (google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse.SimulatedResult): + Result for test case in the corresponding + request. + """ + + class SimulatedResult(proto.Message): + r"""Possible test 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: + finding (google.cloud.securitycenter_v1.types.Finding): + Finding that would be published for the test + case, if a violation is detected. + + This field is a member of `oneof`_ ``result``. + no_violation (google.protobuf.empty_pb2.Empty): + Indicates that the test case does not trigger + any violation. + + This field is a member of `oneof`_ ``result``. + error (google.rpc.status_pb2.Status): + Error encountered during the test. + + This field is a member of `oneof`_ ``result``. + """ + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + oneof='result', + message=gcs_finding.Finding, + ) + no_violation: empty_pb2.Empty = proto.Field( + proto.MESSAGE, + number=2, + oneof='result', + message=empty_pb2.Empty, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + oneof='result', + message=status_pb2.Status, + ) + + result: SimulatedResult = proto.Field( + proto.MESSAGE, + number=1, + message=SimulatedResult, + ) + + +class UpdateExternalSystemRequest(proto.Message): + r"""Request message for updating a ExternalSystem resource. + + Attributes: + external_system (google.cloud.securitycenter_v1.types.ExternalSystem): + Required. The external system resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + external system resource. + If empty all mutable fields will be updated. + """ + + external_system: gcs_external_system.ExternalSystem = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_external_system.ExternalSystem, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + + Attributes: + finding (google.cloud.securitycenter_v1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must be alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing source_properties. + Individual source_properties can be added/updated by using + "source_properties." in the field mask. + """ + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateMuteConfigRequest(proto.Message): + r"""Request message for updating a mute config. + + Attributes: + mute_config (google.cloud.securitycenter_v1.types.MuteConfig): + Required. The mute config being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + mute_config: gcs_mute_config.MuteConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_mute_config.MuteConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateNotificationConfigRequest(proto.Message): + r"""Request message for updating a notification config. + + Attributes: + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): + Required. The notification config to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + notification config. + If empty all mutable fields will be updated. + """ + + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + + Attributes: + organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + settings resource. + If empty all mutable fields will be updated. + """ + + organization_settings: gcs_organization_settings.OrganizationSettings = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_organization_settings.OrganizationSettings, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): + r"""Request message for updating Security Health Analytics custom + modules. + + Attributes: + security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): + Required. The SecurityHealthAnalytics custom + module to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. The only fields that can + be updated are ``enablement_state`` and ``custom_config``. + If empty or set to the wildcard value ``*``, both + ``enablement_state`` and ``custom_config`` are updated. + """ + + security_health_analytics_custom_module: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (google.cloud.securitycenter_v1.types.Source): + Required. The source resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the source + resource. + If empty all mutable fields will be updated. + """ + + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): + Required. The security marks resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If empty + or set to "marks", all marks will be replaced. Individual + marks can be updated using "marks.". + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the updated SecurityMarks + take effect. If not set uses current server + time. Updates will be applied to the + SecurityMarks that are active immediately + preceding this time. Must be earlier or equal to + the server time. + """ + + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_marks.SecurityMarks, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class CreateBigQueryExportRequest(proto.Message): + r"""Request message for creating a BigQuery export. + + Attributes: + parent (str): + Required. The name of the parent resource of the new + BigQuery export. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): + Required. The BigQuery export being created. + big_query_export_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must consist + of only lowercase letters, numbers, and hyphens, + must start with a letter, must end with either a + letter or a number, and must be 63 characters or + less. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + big_query_export: bigquery_export.BigQueryExport = proto.Field( + proto.MESSAGE, + number=2, + message=bigquery_export.BigQueryExport, + ) + big_query_export_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateBigQueryExportRequest(proto.Message): + r"""Request message for updating a BigQuery export. + + Attributes: + big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): + Required. The BigQuery export being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + big_query_export: bigquery_export.BigQueryExport = proto.Field( + proto.MESSAGE, + number=1, + message=bigquery_export.BigQueryExport, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListBigQueryExportsRequest(proto.Message): + r"""Request message for listing BigQuery exports at a given scope + e.g. organization, folder or project. + + Attributes: + parent (str): + Required. The parent, which owns the collection of BigQuery + exports. Its format is ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + page_size (int): + The maximum number of configs to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous + ``ListBigQueryExports`` call. Provide this to retrieve the + subsequent page. When paginating, all other parameters + provided to ``ListBigQueryExports`` 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 ListBigQueryExportsResponse(proto.Message): + r"""Response message for listing BigQuery exports. + + Attributes: + big_query_exports (MutableSequence[google.cloud.securitycenter_v1.types.BigQueryExport]): + The BigQuery exports from the specified + parent. + 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 + + big_query_exports: MutableSequence[bigquery_export.BigQueryExport] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=bigquery_export.BigQueryExport, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteBigQueryExportRequest(proto.Message): + r"""Request message for deleting a BigQuery export. + + Attributes: + name (str): + Required. The name of the BigQuery export to delete. Its + format is + ``organizations/{organization}/bigQueryExports/{export_id}``, + ``folders/{folder}/bigQueryExports/{export_id}``, or + ``projects/{project}/bigQueryExports/{export_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEventThreatDetectionCustomModuleRequest(proto.Message): + r"""Request to create an Event Threat Detection custom module. + + Attributes: + parent (str): + Required. The new custom module's parent. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): + Required. The module to create. The + event_threat_detection_custom_module.name will be ignored + and server generated. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + event_threat_detection_custom_module: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, + ) + + +class ValidateEventThreatDetectionCustomModuleRequest(proto.Message): + r"""Request to validate an Event Threat Detection custom module. + + Attributes: + parent (str): + Required. Resource name of the parent to validate the Custom + Module under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + raw_text (str): + Required. The raw text of the module's + contents. Used to generate error messages. + type_ (str): + Required. The type of the module (e.g. CONFIGURABLE_BAD_IP). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + raw_text: str = proto.Field( + proto.STRING, + number=2, + ) + type_: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ValidateEventThreatDetectionCustomModuleResponse(proto.Message): + r"""Response to validating an Event Threat Detection custom + module. + + Attributes: + errors (google.cloud.securitycenter_v1.types.CustomModuleValidationErrors): + A list of errors returned by the validator. + If the list is empty, there were no errors. + """ + + errors: event_threat_detection_custom_module_validation_errors.CustomModuleValidationErrors = proto.Field( + proto.MESSAGE, + number=2, + message=event_threat_detection_custom_module_validation_errors.CustomModuleValidationErrors, + ) + + +class DeleteEventThreatDetectionCustomModuleRequest(proto.Message): + r"""Request to delete an Event Threat Detection custom module. + + Attributes: + name (str): + Required. Name of the custom module to delete. + + Its format is: + + - "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}". + - "folders/{folder}/eventThreatDetectionSettings/customModules/{module}". + - "projects/{project}/eventThreatDetectionSettings/customModules/{module}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEventThreatDetectionCustomModuleRequest(proto.Message): + r"""Request to get an Event Threat Detection custom module. + + Attributes: + name (str): + Required. Name of the custom module to get. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDescendantEventThreatDetectionCustomModulesRequest(proto.Message): + r"""Request to list current and descendant resident Event Threat + Detection custom modules. + + Attributes: + parent (str): + Required. Name of the parent to list custom modules under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + page_token (str): + A page token, received from a previous + ``ListDescendantEventThreatDetectionCustomModules`` call. + Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListDescendantEventThreatDetectionCustomModules`` must + match the call that provided the page token. + page_size (int): + The maximum number of modules to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + """ + + 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 ListDescendantEventThreatDetectionCustomModulesResponse(proto.Message): + r"""Response for listing current and descendant resident + Event Threat Detection custom modules. + + Attributes: + event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule]): + Custom modules belonging to the requested + parent. + 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 + + event_threat_detection_custom_modules: MutableSequence[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListEventThreatDetectionCustomModulesRequest(proto.Message): + r"""Request to list Event Threat Detection custom modules. + + Attributes: + parent (str): + Required. Name of the parent to list custom modules under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + page_token (str): + A page token, received from a previous + ``ListEventThreatDetectionCustomModules`` call. Provide this + to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListEventThreatDetectionCustomModules`` must match the + call that provided the page token. + page_size (int): + The maximum number of modules to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + """ + + 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 ListEventThreatDetectionCustomModulesResponse(proto.Message): + r"""Response for listing Event Threat Detection custom modules. + + Attributes: + event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule]): + Custom modules belonging to the requested + parent. + 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 + + event_threat_detection_custom_modules: MutableSequence[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateEventThreatDetectionCustomModuleRequest(proto.Message): + r"""Request to update an Event Threat Detection custom module. + + Attributes: + event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): + Required. The module being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + event_threat_detection_custom_module: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetEffectiveEventThreatDetectionCustomModuleRequest(proto.Message): + r"""Request to get an EffectiveEventThreatDetectionCustomModule. + + Attributes: + name (str): + Required. The resource name of the effective Event Threat + Detection custom module. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEffectiveEventThreatDetectionCustomModulesRequest(proto.Message): + r"""Request to list effective Event Threat Detection custom + modules. + + Attributes: + parent (str): + Required. Name of the parent to list custom modules for. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + page_token (str): + A page token, received from a previous + ``ListEffectiveEventThreatDetectionCustomModules`` call. + Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListEffectiveEventThreatDetectionCustomModules`` must + match the call that provided the page token. + page_size (int): + The maximum number of modules to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + """ + + 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 ListEffectiveEventThreatDetectionCustomModulesResponse(proto.Message): + r"""Response for listing + EffectiveEventThreatDetectionCustomModules. + + Attributes: + effective_event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule]): + Effective custom modules belonging to the + requested parent. + 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 + + effective_event_threat_detection_custom_modules: MutableSequence[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py new file mode 100644 index 000000000000..941b7452d7e0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1.types import resource +from google.cloud.securitycenter_v1.types import valued_resource +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Simulation', + }, +) + + +class Simulation(proto.Message): + r"""Attack path simulation + + Attributes: + name (str): + Full resource name of the Simulation: + ``organizations/123/simulations/456`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time simulation was created + resource_value_configs_metadata (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfigMetadata]): + Resource value configurations' metadata used + in this simulation. Maximum of 100. + cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): + Indicates which cloud provider was used in + this simulation. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + resource_value_configs_metadata: MutableSequence[valued_resource.ResourceValueConfigMetadata] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=valued_resource.ResourceValueConfigMetadata, + ) + cloud_provider: resource.CloudProvider = proto.Field( + proto.ENUM, + number=4, + enum=resource.CloudProvider, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.py new file mode 100644 index 000000000000..e1c53a7c05a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Source', + }, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, and other tools. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and outdated or + insecure libraries.". + canonical_name (str): + The canonical name of the finding source. It's either + "organizations/{organization_id}/sources/{source_id}", + "folders/{folder_id}/sources/{source_id}", or + "projects/{project_number}/sources/{source_id}", depending + on the closest CRM ancestor of the resource associated with + the finding. + """ + + 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, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=14, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.py new file mode 100644 index 000000000000..77f790f8d5f6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'ToxicCombination', + }, +) + + +class ToxicCombination(proto.Message): + r"""Contains details about a group of security issues that, when + the issues occur together, represent a greater risk than when + the issues occur independently. A group of such issues is + referred to as a toxic combination. + + Attributes: + attack_exposure_score (float): + The `Attack exposure + score `__ + of this toxic combination. The score is a measure of how + much this toxic combination exposes one or more high-value + resources to potential attack. + related_findings (MutableSequence[str]): + List of resource names of findings associated with this + toxic combination. For example, + ``organizations/123/sources/456/findings/789``. + """ + + attack_exposure_score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + related_findings: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.py new file mode 100644 index 000000000000..5d48f6fabfa1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'ValuedResource', + 'ResourceValueConfigMetadata', + }, +) + + +class ValuedResource(proto.Message): + r"""A resource that is determined to have value to a user's + system + + Attributes: + name (str): + Valued resource name, for example, e.g.: + ``organizations/123/simulations/456/valuedResources/789`` + resource (str): + The `full resource + name `__ + of the valued resource. + resource_type (str): + The `resource + type `__ + of the valued resource. + display_name (str): + Human-readable name of the valued resource. + resource_value (google.cloud.securitycenter_v1.types.ValuedResource.ResourceValue): + How valuable this resource is. + exposed_score (float): + Exposed score for this valued resource. A + value of 0 means no exposure was detected + exposure. + resource_value_configs_used (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfigMetadata]): + List of resource value configurations' + metadata used to determine the value of this + resource. Maximum of 100. + """ + class ResourceValue(proto.Enum): + r"""How valuable the resource is. + + Values: + RESOURCE_VALUE_UNSPECIFIED (0): + The resource value isn't specified. + RESOURCE_VALUE_LOW (1): + This is a low-value resource. + RESOURCE_VALUE_MEDIUM (2): + This is a medium-value resource. + RESOURCE_VALUE_HIGH (3): + This is a high-value resource. + """ + RESOURCE_VALUE_UNSPECIFIED = 0 + RESOURCE_VALUE_LOW = 1 + RESOURCE_VALUE_MEDIUM = 2 + RESOURCE_VALUE_HIGH = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource: str = proto.Field( + proto.STRING, + number=2, + ) + resource_type: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + resource_value: ResourceValue = proto.Field( + proto.ENUM, + number=5, + enum=ResourceValue, + ) + exposed_score: float = proto.Field( + proto.DOUBLE, + number=6, + ) + resource_value_configs_used: MutableSequence['ResourceValueConfigMetadata'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='ResourceValueConfigMetadata', + ) + + +class ResourceValueConfigMetadata(proto.Message): + r"""Metadata about a ResourceValueConfig. For example, id and + name. + + Attributes: + name (str): + Resource value config name + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py new file mode 100644 index 000000000000..5dbae9a7832c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py @@ -0,0 +1,538 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.securitycenter.v1', + manifest={ + 'Vulnerability', + 'Cve', + 'Reference', + 'Cvssv3', + 'Package', + 'SecurityBulletin', + }, +) + + +class Vulnerability(proto.Message): + r"""Refers to common vulnerability fields e.g. cve, cvss, cwe + etc. + + Attributes: + cve (google.cloud.securitycenter_v1.types.Cve): + CVE stands for Common Vulnerabilities and + Exposures (https://cve.mitre.org/about/) + offending_package (google.cloud.securitycenter_v1.types.Package): + The offending package is relevant to the + finding. + fixed_package (google.cloud.securitycenter_v1.types.Package): + The fixed package is relevant to the finding. + security_bulletin (google.cloud.securitycenter_v1.types.SecurityBulletin): + The security bulletin is relevant to this + finding. + """ + + cve: 'Cve' = proto.Field( + proto.MESSAGE, + number=1, + message='Cve', + ) + offending_package: 'Package' = proto.Field( + proto.MESSAGE, + number=2, + message='Package', + ) + fixed_package: 'Package' = proto.Field( + proto.MESSAGE, + number=3, + message='Package', + ) + security_bulletin: 'SecurityBulletin' = proto.Field( + proto.MESSAGE, + number=4, + message='SecurityBulletin', + ) + + +class Cve(proto.Message): + r"""CVE stands for Common Vulnerabilities and Exposures. Information + from the `CVE + record `__ that + describes this vulnerability. + + Attributes: + id (str): + The unique identifier for the vulnerability. + e.g. CVE-2021-34527 + references (MutableSequence[google.cloud.securitycenter_v1.types.Reference]): + Additional information about the CVE. + e.g. + https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527 + cvssv3 (google.cloud.securitycenter_v1.types.Cvssv3): + Describe Common Vulnerability Scoring System + specified at + https://www.first.org/cvss/v3.1/specification-document + upstream_fix_available (bool): + Whether upstream fix is available for the + CVE. + impact (google.cloud.securitycenter_v1.types.Cve.RiskRating): + The potential impact of the vulnerability if + it was to be exploited. + exploitation_activity (google.cloud.securitycenter_v1.types.Cve.ExploitationActivity): + The exploitation activity of the + vulnerability in the wild. + observed_in_the_wild (bool): + Whether or not the vulnerability has been + observed in the wild. + zero_day (bool): + Whether or not the vulnerability was zero day + when the finding was published. + """ + class RiskRating(proto.Enum): + r"""The possible values of impact of the vulnerability if it was + to be exploited. + + Values: + RISK_RATING_UNSPECIFIED (0): + Invalid or empty value. + LOW (1): + Exploitation would have little to no security + impact. + MEDIUM (2): + Exploitation would enable attackers to + perform activities, or could allow attackers to + have a direct impact, but would require + additional steps. + HIGH (3): + Exploitation would enable attackers to have a + notable direct impact without needing to + overcome any major mitigating factors. + CRITICAL (4): + Exploitation would fundamentally undermine + the security of affected systems, enable actors + to perform significant attacks with minimal + effort, with little to no mitigating factors to + overcome. + """ + RISK_RATING_UNSPECIFIED = 0 + LOW = 1 + MEDIUM = 2 + HIGH = 3 + CRITICAL = 4 + + class ExploitationActivity(proto.Enum): + r"""The possible values of exploitation activity of the + vulnerability in the wild. + + Values: + EXPLOITATION_ACTIVITY_UNSPECIFIED (0): + Invalid or empty value. + WIDE (1): + Exploitation has been reported or confirmed + to widely occur. + CONFIRMED (2): + Limited reported or confirmed exploitation + activities. + AVAILABLE (3): + Exploit is publicly available. + ANTICIPATED (4): + No known exploitation activity, but has a + high potential for exploitation. + NO_KNOWN (5): + No known exploitation activity. + """ + EXPLOITATION_ACTIVITY_UNSPECIFIED = 0 + WIDE = 1 + CONFIRMED = 2 + AVAILABLE = 3 + ANTICIPATED = 4 + NO_KNOWN = 5 + + id: str = proto.Field( + proto.STRING, + number=1, + ) + references: MutableSequence['Reference'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Reference', + ) + cvssv3: 'Cvssv3' = proto.Field( + proto.MESSAGE, + number=3, + message='Cvssv3', + ) + upstream_fix_available: bool = proto.Field( + proto.BOOL, + number=4, + ) + impact: RiskRating = proto.Field( + proto.ENUM, + number=5, + enum=RiskRating, + ) + exploitation_activity: ExploitationActivity = proto.Field( + proto.ENUM, + number=6, + enum=ExploitationActivity, + ) + observed_in_the_wild: bool = proto.Field( + proto.BOOL, + number=7, + ) + zero_day: bool = proto.Field( + proto.BOOL, + number=8, + ) + + +class Reference(proto.Message): + r"""Additional Links + + Attributes: + source (str): + Source of the reference e.g. NVD + uri (str): + Uri for the mentioned source e.g. + https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527. + """ + + source: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Cvssv3(proto.Message): + r"""Common Vulnerability Scoring System version 3. + + Attributes: + base_score (float): + The base score is a function of the base + metric scores. + attack_vector (google.cloud.securitycenter_v1.types.Cvssv3.AttackVector): + Base Metrics + Represents the intrinsic characteristics of a + vulnerability that are constant over time and + across user environments. This metric reflects + the context by which vulnerability exploitation + is possible. + attack_complexity (google.cloud.securitycenter_v1.types.Cvssv3.AttackComplexity): + This metric describes the conditions beyond + the attacker's control that must exist in order + to exploit the vulnerability. + privileges_required (google.cloud.securitycenter_v1.types.Cvssv3.PrivilegesRequired): + This metric describes the level of privileges + an attacker must possess before successfully + exploiting the vulnerability. + user_interaction (google.cloud.securitycenter_v1.types.Cvssv3.UserInteraction): + This metric captures the requirement for a + human user, other than the attacker, to + participate in the successful compromise of the + vulnerable component. + scope (google.cloud.securitycenter_v1.types.Cvssv3.Scope): + The Scope metric captures whether a + vulnerability in one vulnerable component + impacts resources in components beyond its + security scope. + confidentiality_impact (google.cloud.securitycenter_v1.types.Cvssv3.Impact): + This metric measures the impact to the + confidentiality of the information resources + managed by a software component due to a + successfully exploited vulnerability. + integrity_impact (google.cloud.securitycenter_v1.types.Cvssv3.Impact): + This metric measures the impact to integrity + of a successfully exploited vulnerability. + availability_impact (google.cloud.securitycenter_v1.types.Cvssv3.Impact): + This metric measures the impact to the + availability of the impacted component resulting + from a successfully exploited vulnerability. + """ + class AttackVector(proto.Enum): + r"""This metric reflects the context by which vulnerability + exploitation is possible. + + Values: + ATTACK_VECTOR_UNSPECIFIED (0): + Invalid value. + ATTACK_VECTOR_NETWORK (1): + The vulnerable component is bound to the + network stack and the set of possible attackers + extends beyond the other options listed below, + up to and including the entire Internet. + ATTACK_VECTOR_ADJACENT (2): + The vulnerable component is bound to the + network stack, but the attack is limited at the + protocol level to a logically adjacent topology. + ATTACK_VECTOR_LOCAL (3): + The vulnerable component is not bound to the + network stack and the attacker's path is via + read/write/execute capabilities. + ATTACK_VECTOR_PHYSICAL (4): + The attack requires the attacker to + physically touch or manipulate the vulnerable + component. + """ + ATTACK_VECTOR_UNSPECIFIED = 0 + ATTACK_VECTOR_NETWORK = 1 + ATTACK_VECTOR_ADJACENT = 2 + ATTACK_VECTOR_LOCAL = 3 + ATTACK_VECTOR_PHYSICAL = 4 + + class AttackComplexity(proto.Enum): + r"""This metric describes the conditions beyond the attacker's + control that must exist in order to exploit the vulnerability. + + Values: + ATTACK_COMPLEXITY_UNSPECIFIED (0): + Invalid value. + ATTACK_COMPLEXITY_LOW (1): + Specialized access conditions or extenuating + circumstances do not exist. An attacker can + expect repeatable success when attacking the + vulnerable component. + ATTACK_COMPLEXITY_HIGH (2): + A successful attack depends on conditions + beyond the attacker's control. That is, a + successful attack cannot be accomplished at + will, but requires the attacker to invest in + some measurable amount of effort in preparation + or execution against the vulnerable component + before a successful attack can be expected. + """ + ATTACK_COMPLEXITY_UNSPECIFIED = 0 + ATTACK_COMPLEXITY_LOW = 1 + ATTACK_COMPLEXITY_HIGH = 2 + + class PrivilegesRequired(proto.Enum): + r"""This metric describes the level of privileges an attacker + must possess before successfully exploiting the vulnerability. + + Values: + PRIVILEGES_REQUIRED_UNSPECIFIED (0): + Invalid value. + PRIVILEGES_REQUIRED_NONE (1): + The attacker is unauthorized prior to attack, + and therefore does not require any access to + settings or files of the vulnerable system to + carry out an attack. + PRIVILEGES_REQUIRED_LOW (2): + The attacker requires privileges that provide + basic user capabilities that could normally + affect only settings and files owned by a user. + Alternatively, an attacker with Low privileges + has the ability to access only non-sensitive + resources. + PRIVILEGES_REQUIRED_HIGH (3): + The attacker requires privileges that provide + significant (e.g., administrative) control over + the vulnerable component allowing access to + component-wide settings and files. + """ + PRIVILEGES_REQUIRED_UNSPECIFIED = 0 + PRIVILEGES_REQUIRED_NONE = 1 + PRIVILEGES_REQUIRED_LOW = 2 + PRIVILEGES_REQUIRED_HIGH = 3 + + class UserInteraction(proto.Enum): + r"""This metric captures the requirement for a human user, other + than the attacker, to participate in the successful compromise + of the vulnerable component. + + Values: + USER_INTERACTION_UNSPECIFIED (0): + Invalid value. + USER_INTERACTION_NONE (1): + The vulnerable system can be exploited + without interaction from any user. + USER_INTERACTION_REQUIRED (2): + Successful exploitation of this vulnerability + requires a user to take some action before the + vulnerability can be exploited. + """ + USER_INTERACTION_UNSPECIFIED = 0 + USER_INTERACTION_NONE = 1 + USER_INTERACTION_REQUIRED = 2 + + class Scope(proto.Enum): + r"""The Scope metric captures whether a vulnerability in one + vulnerable component impacts resources in components beyond its + security scope. + + Values: + SCOPE_UNSPECIFIED (0): + Invalid value. + SCOPE_UNCHANGED (1): + An exploited vulnerability can only affect + resources managed by the same security + authority. + SCOPE_CHANGED (2): + An exploited vulnerability can affect + resources beyond the security scope managed by + the security authority of the vulnerable + component. + """ + SCOPE_UNSPECIFIED = 0 + SCOPE_UNCHANGED = 1 + SCOPE_CHANGED = 2 + + class Impact(proto.Enum): + r"""The Impact metrics capture the effects of a successfully + exploited vulnerability on the component that suffers the worst + outcome that is most directly and predictably associated with + the attack. + + Values: + IMPACT_UNSPECIFIED (0): + Invalid value. + IMPACT_HIGH (1): + High impact. + IMPACT_LOW (2): + Low impact. + IMPACT_NONE (3): + No impact. + """ + IMPACT_UNSPECIFIED = 0 + IMPACT_HIGH = 1 + IMPACT_LOW = 2 + IMPACT_NONE = 3 + + base_score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + attack_vector: AttackVector = proto.Field( + proto.ENUM, + number=5, + enum=AttackVector, + ) + attack_complexity: AttackComplexity = proto.Field( + proto.ENUM, + number=6, + enum=AttackComplexity, + ) + privileges_required: PrivilegesRequired = proto.Field( + proto.ENUM, + number=7, + enum=PrivilegesRequired, + ) + user_interaction: UserInteraction = proto.Field( + proto.ENUM, + number=8, + enum=UserInteraction, + ) + scope: Scope = proto.Field( + proto.ENUM, + number=9, + enum=Scope, + ) + confidentiality_impact: Impact = proto.Field( + proto.ENUM, + number=10, + enum=Impact, + ) + integrity_impact: Impact = proto.Field( + proto.ENUM, + number=11, + enum=Impact, + ) + availability_impact: Impact = proto.Field( + proto.ENUM, + number=12, + enum=Impact, + ) + + +class Package(proto.Message): + r"""Package is a generic definition of a package. + + Attributes: + package_name (str): + The name of the package where the + vulnerability was detected. + cpe_uri (str): + The CPE URI where the vulnerability was + detected. + package_type (str): + Type of package, for example, os, maven, or + go. + package_version (str): + The version of the package. + """ + + package_name: str = proto.Field( + proto.STRING, + number=1, + ) + cpe_uri: str = proto.Field( + proto.STRING, + number=2, + ) + package_type: str = proto.Field( + proto.STRING, + number=3, + ) + package_version: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SecurityBulletin(proto.Message): + r"""SecurityBulletin are notifications of vulnerabilities of + Google products. + + Attributes: + bulletin_id (str): + ID of the bulletin corresponding to the + vulnerability. + submission_time (google.protobuf.timestamp_pb2.Timestamp): + Submission time of this Security Bulletin. + suggested_upgrade_version (str): + This represents a version that the cluster + receiving this notification should be upgraded + to, based on its current version. For example, + 1.15.0 + """ + + bulletin_id: str = proto.Field( + proto.STRING, + number=1, + ) + submission_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + suggested_upgrade_version: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v1/noxfile.py new file mode 100644 index 000000000000..c30f405f3ad8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-securitycenter' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +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"): + 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/securitycenter_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"): + 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", + "grpcio", + "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/securitycenter_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( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): + # Ignore release of mypy 1.11.0 which may have a regression + 'mypy!=1.11.0', + '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-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py new file mode 100644 index 000000000000..e404756019e2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + requests = securitycenter_v1.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + requests.resource_value_config.resource_value = "NONE" + requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py new file mode 100644 index 000000000000..3723f44be2cb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + requests = securitycenter_v1.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + requests.resource_value_config.resource_value = "NONE" + requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_async.py new file mode 100644 index 000000000000..c0d550405cbd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_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 BulkMuteFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py new file mode 100644 index 000000000000..39611042828f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_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 BulkMuteFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_async.py new file mode 100644 index 000000000000..6f27ee2174b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_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 CreateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = await client.create_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_sync.py new file mode 100644 index 000000000000..48ddbf103dea --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_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 CreateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = client.create_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py new file mode 100644 index 000000000000..196255a15a29 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_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 CreateEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py new file mode 100644 index 000000000000..2544f1d14706 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_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 CreateEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_async.py new file mode 100644 index 000000000000..84c10d4bf3f8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_sync.py new file mode 100644 index 000000000000..3c594dcc28cb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_async.py new file mode 100644 index 000000000000..aa47e9565150 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_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 CreateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = await client.create_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_sync.py new file mode 100644 index 000000000000..aa64e4c92f71 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_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 CreateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = client.create_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_async.py new file mode 100644 index 000000000000..c1e37d27979b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_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 CreateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_sync.py new file mode 100644 index 000000000000..f313379f2bda --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_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 CreateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py new file mode 100644 index 000000000000..20431387d14e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_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 CreateSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py new file mode 100644 index 000000000000..cc70b8c77485 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_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 CreateSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_async.py new file mode 100644 index 000000000000..5a9938f4f606 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_source(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_sync.py new file mode 100644 index 000000000000..d79924fc941f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_source(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_async.py new file mode 100644 index 000000000000..990cd91d3f2f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + await client.delete_big_query_export(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_sync.py new file mode 100644 index 000000000000..7b8a0710a6b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + client.delete_big_query_export(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py new file mode 100644 index 000000000000..6fd5fad55d83 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_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 DeleteEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_delete_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + await client.delete_event_threat_detection_custom_module(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py new file mode 100644 index 000000000000..4126fb7da0d3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_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 DeleteEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_delete_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + client.delete_event_threat_detection_custom_module(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_async.py new file mode 100644 index 000000000000..c4f1c8484a6e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_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 DeleteMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_delete_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_mute_config(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_sync.py new file mode 100644 index 000000000000..04a1241d4610 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_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 DeleteMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_delete_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_mute_config(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_async.py new file mode 100644 index 000000000000..a2ea5ed9a93d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_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 DeleteNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_sync.py new file mode 100644 index 000000000000..bb408a4637e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_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 DeleteNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_async.py new file mode 100644 index 000000000000..42d63c083d6a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_resource_value_config(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py new file mode 100644 index 000000000000..a84b69405090 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_resource_value_config(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py new file mode 100644 index 000000000000..9e2c550b018b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_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 DeleteSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_delete_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + await client.delete_security_health_analytics_custom_module(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py new file mode 100644 index 000000000000..44d1b7765a20 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_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 DeleteSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_delete_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + client.delete_security_health_analytics_custom_module(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_async.py new file mode 100644 index 000000000000..2d3a4e11966a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_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 GetBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_sync.py new file mode 100644 index 000000000000..f3754570b866 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_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 GetBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = client.get_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py new file mode 100644 index 000000000000..fe81fc63fb30 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_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 GetEffectiveEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_effective_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_effective_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py new file mode 100644 index 000000000000..1d4d49fff5bd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_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 GetEffectiveEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_effective_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_effective_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py new file mode 100644 index 000000000000..fe87fa09b31f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_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 GetEffectiveSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_effective_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_effective_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py new file mode 100644 index 000000000000..bfa2f6f00642 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_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 GetEffectiveSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_effective_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_effective_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py new file mode 100644 index 000000000000..62c809c57f6f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_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 GetEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py new file mode 100644 index 000000000000..cbde7132fb16 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_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 GetEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_async.py new file mode 100644 index 000000000000..3884cd78982e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_sync.py new file mode 100644 index 000000000000..04461d2bd874 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_async.py new file mode 100644 index 000000000000..cd5077ce53bb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_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 GetMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_sync.py new file mode 100644 index 000000000000..0794d6d0a981 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_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 GetMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_async.py new file mode 100644 index 000000000000..4ca94a312da4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_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 GetNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_sync.py new file mode 100644 index 000000000000..a9fdde5359f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_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 GetNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_async.py new file mode 100644 index 000000000000..5cf5ce3a26d2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_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 GetOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_sync.py new file mode 100644 index 000000000000..fb45a62aeafa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_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 GetOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_async.py new file mode 100644 index 000000000000..30fb9d9c366b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_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 GetResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_sync.py new file mode 100644 index 000000000000..0b453f060803 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_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 GetResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py new file mode 100644 index 000000000000..4f3caf3a11bd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_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 GetSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py new file mode 100644 index 000000000000..55bae4951d45 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_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 GetSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_async.py new file mode 100644 index 000000000000..1b99150b7442 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_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 GetSimulation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetSimulation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_simulation(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_simulation(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetSimulation_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_sync.py new file mode 100644 index 000000000000..083acba19009 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_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 GetSimulation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetSimulation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_simulation(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = client.get_simulation(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetSimulation_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_async.py new file mode 100644 index 000000000000..3b09eb27dfef --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_source(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_sync.py new file mode 100644 index 000000000000..ae5d605951c4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_source(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_async.py new file mode 100644 index 000000000000..ba715be17d9c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_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 GetValuedResource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetValuedResource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_valued_resource(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_valued_resource(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetValuedResource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_sync.py new file mode 100644 index 000000000000..b3aa5036453d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_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 GetValuedResource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetValuedResource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_valued_resource(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_valued_resource(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetValuedResource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_async.py new file mode 100644 index 000000000000..972ab2a30dc1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_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 GroupAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GroupAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_group_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GroupAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_sync.py new file mode 100644 index 000000000000..85fa08c63683 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_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 GroupAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GroupAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_group_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GroupAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_async.py new file mode 100644 index 000000000000..8277a2723cc7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GroupFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_group_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_sync.py new file mode 100644 index 000000000000..501397bb2a26 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GroupFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_group_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_async.py new file mode 100644 index 000000000000..d7eb57f6976c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_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 ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_sync.py new file mode 100644 index 000000000000..129d168899aa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_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 ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_async.py new file mode 100644 index 000000000000..1fd2c65f76c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_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 ListAttackPaths +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListAttackPaths_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_attack_paths(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListAttackPaths_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_sync.py new file mode 100644 index 000000000000..ceea93417e1d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_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 ListAttackPaths +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListAttackPaths_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_attack_paths(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListAttackPaths_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_async.py new file mode 100644 index 000000000000..438df71d9c0c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_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 ListBigQueryExports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_sync.py new file mode 100644 index 000000000000..b967f0a3cc2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_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 ListBigQueryExports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py new file mode 100644 index 000000000000..7b214a5e3786 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_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 ListDescendantEventThreatDetectionCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_descendant_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py new file mode 100644 index 000000000000..764f1cbe9905 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_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 ListDescendantEventThreatDetectionCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_descendant_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py new file mode 100644 index 000000000000..4f577cf8f0e1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_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 ListDescendantSecurityHealthAnalyticsCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_descendant_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py new file mode 100644 index 000000000000..44aacf778aaa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_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 ListDescendantSecurityHealthAnalyticsCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_descendant_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py new file mode 100644 index 000000000000..40ac4b1fae7f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_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 ListEffectiveEventThreatDetectionCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_effective_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_event_threat_detection_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py new file mode 100644 index 000000000000..d339fb184b9f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_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 ListEffectiveEventThreatDetectionCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_effective_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_event_threat_detection_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py new file mode 100644 index 000000000000..2ddb1fdf50a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_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 ListEffectiveSecurityHealthAnalyticsCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_effective_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_security_health_analytics_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py new file mode 100644 index 000000000000..a6d1e35fe7a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_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 ListEffectiveSecurityHealthAnalyticsCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_effective_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_security_health_analytics_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py new file mode 100644 index 000000000000..053e3047b38a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_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 ListEventThreatDetectionCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_event_threat_detection_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py new file mode 100644 index 000000000000..8216523320e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_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 ListEventThreatDetectionCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_event_threat_detection_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_async.py new file mode 100644 index 000000000000..f2fc2cc4e0e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_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 securitycenter_v1 + + +async def sample_list_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_sync.py new file mode 100644 index 000000000000..574c0709c259 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_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 securitycenter_v1 + + +def sample_list_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_async.py new file mode 100644 index 000000000000..b4984b693810 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_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 ListMuteConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_mute_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_sync.py new file mode 100644 index 000000000000..451cf050e43b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_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 ListMuteConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_mute_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_async.py new file mode 100644 index 000000000000..9b8132cda94b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_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 ListNotificationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_sync.py new file mode 100644 index 000000000000..27e3721c377d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_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 ListNotificationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_async.py new file mode 100644 index 000000000000..6d2ebd0e1a1e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_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 ListResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py new file mode 100644 index 000000000000..a34c9520517f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_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 ListResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py new file mode 100644 index 000000000000..b6d94d40eb3e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_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 ListSecurityHealthAnalyticsCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_health_analytics_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py new file mode 100644 index 000000000000..d352446e7eed --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_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 ListSecurityHealthAnalyticsCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_health_analytics_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_async.py new file mode 100644 index 000000000000..6e653789098a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListSources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_sources(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_sync.py new file mode 100644 index 000000000000..3d73c443003d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListSources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_sources(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_async.py new file mode 100644 index 000000000000..09db5a4658e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_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 ListValuedResources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListValuedResources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_valued_resources(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListValuedResources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_sync.py new file mode 100644 index 000000000000..0c4289dd7f65 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_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 ListValuedResources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListValuedResources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_valued_resources(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListValuedResources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_async.py new file mode 100644 index 000000000000..3e126713c3e2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_sync.py new file mode 100644 index 000000000000..de045eb9e950 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_async.py new file mode 100644 index 000000000000..83c439f5e761 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SetFindingState_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_set_finding_state(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_sync.py new file mode 100644 index 000000000000..b6c47c7d5405 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SetFindingState_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_set_finding_state(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_async.py new file mode 100644 index 000000000000..d0828598e4ea --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_sync.py new file mode 100644 index 000000000000..9592707e3a59 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_async.py new file mode 100644 index 000000000000..1d2631a20453 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_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 SetMute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SetMute_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_set_mute(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = await client.set_mute(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SetMute_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_sync.py new file mode 100644 index 000000000000..10b240d03f92 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_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 SetMute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SetMute_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_set_mute(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = client.set_mute(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SetMute_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py new file mode 100644 index 000000000000..8f323db2f936 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_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 SimulateSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_simulate_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + resource = securitycenter_v1.SimulatedResource() + resource.resource_type = "resource_type_value" + + request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + resource=resource, + ) + + # Make the request + response = await client.simulate_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py new file mode 100644 index 000000000000..81d436d78385 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_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 SimulateSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_simulate_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + resource = securitycenter_v1.SimulatedResource() + resource.resource_type = "resource_type_value" + + request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + resource=resource, + ) + + # Make the request + response = client.simulate_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_async.py new file mode 100644 index 000000000000..479364cbe039 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_sync.py new file mode 100644 index 000000000000..d39b8072621c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_async.py new file mode 100644 index 000000000000..e07c6c16bb47 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_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 UpdateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateBigQueryExportRequest( + ) + + # Make the request + response = await client.update_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_sync.py new file mode 100644 index 000000000000..0569a012c3bc --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_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 UpdateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateBigQueryExportRequest( + ) + + # Make the request + response = client.update_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py new file mode 100644 index 000000000000..fd503424dd75 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_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 UpdateEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( + ) + + # Make the request + response = await client.update_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py new file mode 100644 index 000000000000..05ca8e32603f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_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 UpdateEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( + ) + + # Make the request + response = client.update_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_async.py new file mode 100644 index 000000000000..dd917f4ac903 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_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 UpdateExternalSystem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_external_system(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateExternalSystemRequest( + ) + + # Make the request + response = await client.update_external_system(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_sync.py new file mode 100644 index 000000000000..fc184d7026aa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_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 UpdateExternalSystem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_external_system(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateExternalSystemRequest( + ) + + # Make the request + response = client.update_external_system(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_async.py new file mode 100644 index 000000000000..fb05f8e20bdf --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_sync.py new file mode 100644 index 000000000000..3c4fe5bc7ec5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_async.py new file mode 100644 index 000000000000..39d5f038be44 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_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 UpdateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = await client.update_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_sync.py new file mode 100644 index 000000000000..245f3c802a09 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_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 UpdateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = client.update_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_async.py new file mode 100644 index 000000000000..6dfffbef6f93 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_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 UpdateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_sync.py new file mode 100644 index 000000000000..a8ca94d09985 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_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 UpdateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_async.py new file mode 100644 index 000000000000..b88b1aa0af5e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = await client.update_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_sync.py new file mode 100644 index 000000000000..c897ad8cdba4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = client.update_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_async.py new file mode 100644 index 000000000000..2b7526207b34 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_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 UpdateResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + resource_value_config = securitycenter_v1.ResourceValueConfig() + resource_value_config.resource_value = "NONE" + resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.UpdateResourceValueConfigRequest( + resource_value_config=resource_value_config, + ) + + # Make the request + response = await client.update_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_sync.py new file mode 100644 index 000000000000..fe7fb7c93f87 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_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 UpdateResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + resource_value_config = securitycenter_v1.ResourceValueConfig() + resource_value_config.resource_value = "NONE" + resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.UpdateResourceValueConfigRequest( + resource_value_config=resource_value_config, + ) + + # Make the request + response = client.update_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py new file mode 100644 index 000000000000..66f5cd744979 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_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 UpdateSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( + ) + + # Make the request + response = await client.update_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py new file mode 100644 index 000000000000..ed56eba54e03 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_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 UpdateSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( + ) + + # Make the request + response = client.update_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_async.py new file mode 100644 index 000000000000..1b69e29a2d37 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_security_marks(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_sync.py new file mode 100644 index 000000000000..b0c6a29d705b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_security_marks(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_async.py new file mode 100644 index 000000000000..659495e1c73f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_source(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_sync.py new file mode 100644 index 000000000000..80ac8afaabd7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_source(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py new file mode 100644 index 000000000000..38c6309258a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_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 ValidateEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_validate_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + raw_text="raw_text_value", + type_="type__value", + ) + + # Make the request + response = await client.validate_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py new file mode 100644 index 000000000000..dbcc6d5f0f5c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_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 ValidateEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_validate_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + raw_text="raw_text_value", + type_="type__value", + ) + + # Make the request + response = client.validate_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json new file mode 100644 index 000000000000..176395462f39 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json @@ -0,0 +1,10298 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.securitycenter.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-securitycenter", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.batch_create_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BatchCreateResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BatchCreateResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse", + "shortName": "batch_create_resource_value_configs" + }, + "description": "Sample for BatchCreateResourceValueConfigs", + "file": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.batch_create_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BatchCreateResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BatchCreateResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse", + "shortName": "batch_create_resource_value_configs" + }, + "description": "Sample for BatchCreateResourceValueConfigs", + "file": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.bulk_mute_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BulkMuteFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BulkMuteFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "bulk_mute_findings" + }, + "description": "Sample for BulkMuteFindings", + "file": "securitycenter_v1_generated_security_center_bulk_mute_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v1_generated_security_center_bulk_mute_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.bulk_mute_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BulkMuteFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BulkMuteFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "bulk_mute_findings" + }, + "description": "Sample for BulkMuteFindings", + "file": "securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v1.types.BigQueryExport" + }, + { + "name": "big_query_export_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.BigQueryExport", + "shortName": "create_big_query_export" + }, + "description": "Sample for CreateBigQueryExport", + "file": "securitycenter_v1_generated_security_center_create_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v1_generated_security_center_create_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v1.types.BigQueryExport" + }, + { + "name": "big_query_export_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.BigQueryExport", + "shortName": "create_big_query_export" + }, + "description": "Sample for CreateBigQueryExport", + "file": "securitycenter_v1_generated_security_center_create_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v1_generated_security_center_create_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "event_threat_detection_custom_module", + "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule", + "shortName": "create_event_threat_detection_custom_module" + }, + "description": "Sample for CreateEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "event_threat_detection_custom_module", + "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule", + "shortName": "create_event_threat_detection_custom_module" + }, + "description": "Sample for CreateEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v1_generated_security_center_create_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1_generated_security_center_create_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v1_generated_security_center_create_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1_generated_security_center_create_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateMuteConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v1.types.MuteConfig" + }, + { + "name": "mute_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.cloud.securitycenter_v1.types.MuteConfig", + "shortName": "create_mute_config" + }, + "description": "Sample for CreateMuteConfig", + "file": "securitycenter_v1_generated_security_center_create_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v1_generated_security_center_create_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateMuteConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v1.types.MuteConfig" + }, + { + "name": "mute_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.cloud.securitycenter_v1.types.MuteConfig", + "shortName": "create_mute_config" + }, + "description": "Sample for CreateMuteConfig", + "file": "securitycenter_v1_generated_security_center_create_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v1_generated_security_center_create_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "config_id", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1.types.NotificationConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v1_generated_security_center_create_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1_generated_security_center_create_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "config_id", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1.types.NotificationConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v1_generated_security_center_create_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1_generated_security_center_create_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "security_health_analytics_custom_module", + "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", + "shortName": "create_security_health_analytics_custom_module" + }, + "description": "Sample for CreateSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "security_health_analytics_custom_module", + "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", + "shortName": "create_security_health_analytics_custom_module" + }, + "description": "Sample for CreateSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v1_generated_security_center_create_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_create_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v1_generated_security_center_create_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_create_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest" + }, + { + "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_big_query_export" + }, + "description": "Sample for DeleteBigQueryExport", + "file": "securitycenter_v1_generated_security_center_delete_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v1_generated_security_center_delete_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest" + }, + { + "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_big_query_export" + }, + "description": "Sample for DeleteBigQueryExport", + "file": "securitycenter_v1_generated_security_center_delete_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v1_generated_security_center_delete_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest" + }, + { + "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_event_threat_detection_custom_module" + }, + "description": "Sample for DeleteEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest" + }, + { + "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_event_threat_detection_custom_module" + }, + "description": "Sample for DeleteEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest" + }, + { + "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_mute_config" + }, + "description": "Sample for DeleteMuteConfig", + "file": "securitycenter_v1_generated_security_center_delete_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v1_generated_security_center_delete_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest" + }, + { + "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_mute_config" + }, + "description": "Sample for DeleteMuteConfig", + "file": "securitycenter_v1_generated_security_center_delete_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v1_generated_security_center_delete_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest" + }, + { + "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_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v1_generated_security_center_delete_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1_generated_security_center_delete_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest" + }, + { + "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_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v1_generated_security_center_delete_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1_generated_security_center_delete_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest" + }, + { + "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_resource_value_config" + }, + "description": "Sample for DeleteResourceValueConfig", + "file": "securitycenter_v1_generated_security_center_delete_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v1_generated_security_center_delete_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest" + }, + { + "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_resource_value_config" + }, + "description": "Sample for DeleteResourceValueConfig", + "file": "securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "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_security_health_analytics_custom_module" + }, + "description": "Sample for DeleteSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "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_security_health_analytics_custom_module" + }, + "description": "Sample for DeleteSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetBigQueryExportRequest" + }, + { + "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.securitycenter_v1.types.BigQueryExport", + "shortName": "get_big_query_export" + }, + "description": "Sample for GetBigQueryExport", + "file": "securitycenter_v1_generated_security_center_get_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetBigQueryExportRequest" + }, + { + "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.securitycenter_v1.types.BigQueryExport", + "shortName": "get_big_query_export" + }, + "description": "Sample for GetBigQueryExport", + "file": "securitycenter_v1_generated_security_center_get_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_effective_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetEffectiveEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule", + "shortName": "get_effective_event_threat_detection_custom_module" + }, + "description": "Sample for GetEffectiveEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_effective_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetEffectiveEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule", + "shortName": "get_effective_event_threat_detection_custom_module" + }, + "description": "Sample for GetEffectiveEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_effective_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetEffectiveSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule", + "shortName": "get_effective_security_health_analytics_custom_module" + }, + "description": "Sample for GetEffectiveSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_effective_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetEffectiveSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule", + "shortName": "get_effective_security_health_analytics_custom_module" + }, + "description": "Sample for GetEffectiveSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.EventThreatDetectionCustomModule", + "shortName": "get_event_threat_detection_custom_module" + }, + "description": "Sample for GetEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.EventThreatDetectionCustomModule", + "shortName": "get_event_threat_detection_custom_module" + }, + "description": "Sample for GetEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v1_generated_security_center_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v1_generated_security_center_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetMuteConfigRequest" + }, + { + "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.securitycenter_v1.types.MuteConfig", + "shortName": "get_mute_config" + }, + "description": "Sample for GetMuteConfig", + "file": "securitycenter_v1_generated_security_center_get_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetMuteConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetMuteConfigRequest" + }, + { + "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.securitycenter_v1.types.MuteConfig", + "shortName": "get_mute_config" + }, + "description": "Sample for GetMuteConfig", + "file": "securitycenter_v1_generated_security_center_get_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetMuteConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v1.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v1_generated_security_center_get_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v1.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v1_generated_security_center_get_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest" + }, + { + "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.securitycenter_v1.types.OrganizationSettings", + "shortName": "get_organization_settings" + }, + "description": "Sample for GetOrganizationSettings", + "file": "securitycenter_v1_generated_security_center_get_organization_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_organization_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest" + }, + { + "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.securitycenter_v1.types.OrganizationSettings", + "shortName": "get_organization_settings" + }, + "description": "Sample for GetOrganizationSettings", + "file": "securitycenter_v1_generated_security_center_get_organization_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_organization_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest" + }, + { + "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.securitycenter_v1.types.ResourceValueConfig", + "shortName": "get_resource_value_config" + }, + "description": "Sample for GetResourceValueConfig", + "file": "securitycenter_v1_generated_security_center_get_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest" + }, + { + "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.securitycenter_v1.types.ResourceValueConfig", + "shortName": "get_resource_value_config" + }, + "description": "Sample for GetResourceValueConfig", + "file": "securitycenter_v1_generated_security_center_get_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", + "shortName": "get_security_health_analytics_custom_module" + }, + "description": "Sample for GetSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", + "shortName": "get_security_health_analytics_custom_module" + }, + "description": "Sample for GetSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_simulation", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSimulation", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSimulation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetSimulationRequest" + }, + { + "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.securitycenter_v1.types.Simulation", + "shortName": "get_simulation" + }, + "description": "Sample for GetSimulation", + "file": "securitycenter_v1_generated_security_center_get_simulation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSimulation_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_simulation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_simulation", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSimulation", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSimulation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetSimulationRequest" + }, + { + "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.securitycenter_v1.types.Simulation", + "shortName": "get_simulation" + }, + "description": "Sample for GetSimulation", + "file": "securitycenter_v1_generated_security_center_get_simulation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSimulation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_simulation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetSourceRequest" + }, + { + "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.securitycenter_v1.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v1_generated_security_center_get_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetSourceRequest" + }, + { + "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.securitycenter_v1.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v1_generated_security_center_get_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_valued_resource", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetValuedResource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetValuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetValuedResourceRequest" + }, + { + "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.securitycenter_v1.types.ValuedResource", + "shortName": "get_valued_resource" + }, + "description": "Sample for GetValuedResource", + "file": "securitycenter_v1_generated_security_center_get_valued_resource_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetValuedResource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_valued_resource_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_valued_resource", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetValuedResource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetValuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetValuedResourceRequest" + }, + { + "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.securitycenter_v1.types.ValuedResource", + "shortName": "get_valued_resource" + }, + "description": "Sample for GetValuedResource", + "file": "securitycenter_v1_generated_security_center_get_valued_resource_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetValuedResource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_valued_resource_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.group_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GroupAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsAsyncPager", + "shortName": "group_assets" + }, + "description": "Sample for GroupAssets", + "file": "securitycenter_v1_generated_security_center_group_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1_generated_security_center_group_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.group_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GroupAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsPager", + "shortName": "group_assets" + }, + "description": "Sample for GroupAssets", + "file": "securitycenter_v1_generated_security_center_group_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1_generated_security_center_group_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsAsyncPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v1_generated_security_center_group_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1_generated_security_center_group_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v1_generated_security_center_group_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1_generated_security_center_group_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsAsyncPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "securitycenter_v1_generated_security_center_list_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1_generated_security_center_list_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "securitycenter_v1_generated_security_center_list_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1_generated_security_center_list_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_attack_paths", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAttackPaths", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAttackPaths" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListAttackPathsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListAttackPathsAsyncPager", + "shortName": "list_attack_paths" + }, + "description": "Sample for ListAttackPaths", + "file": "securitycenter_v1_generated_security_center_list_attack_paths_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v1_generated_security_center_list_attack_paths_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_attack_paths", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAttackPaths", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAttackPaths" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListAttackPathsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListAttackPathsPager", + "shortName": "list_attack_paths" + }, + "description": "Sample for ListAttackPaths", + "file": "securitycenter_v1_generated_security_center_list_attack_paths_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v1_generated_security_center_list_attack_paths_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_big_query_exports", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListBigQueryExports", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListBigQueryExports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsAsyncPager", + "shortName": "list_big_query_exports" + }, + "description": "Sample for ListBigQueryExports", + "file": "securitycenter_v1_generated_security_center_list_big_query_exports_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v1_generated_security_center_list_big_query_exports_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_big_query_exports", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListBigQueryExports", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListBigQueryExports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsPager", + "shortName": "list_big_query_exports" + }, + "description": "Sample for ListBigQueryExports", + "file": "securitycenter_v1_generated_security_center_list_big_query_exports_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v1_generated_security_center_list_big_query_exports_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_descendant_event_threat_detection_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantEventThreatDetectionCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListDescendantEventThreatDetectionCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager", + "shortName": "list_descendant_event_threat_detection_custom_modules" + }, + "description": "Sample for ListDescendantEventThreatDetectionCustomModules", + "file": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_descendant_event_threat_detection_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantEventThreatDetectionCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListDescendantEventThreatDetectionCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesPager", + "shortName": "list_descendant_event_threat_detection_custom_modules" + }, + "description": "Sample for ListDescendantEventThreatDetectionCustomModules", + "file": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_descendant_security_health_analytics_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantSecurityHealthAnalyticsCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListDescendantSecurityHealthAnalyticsCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager", + "shortName": "list_descendant_security_health_analytics_custom_modules" + }, + "description": "Sample for ListDescendantSecurityHealthAnalyticsCustomModules", + "file": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_descendant_security_health_analytics_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantSecurityHealthAnalyticsCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListDescendantSecurityHealthAnalyticsCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager", + "shortName": "list_descendant_security_health_analytics_custom_modules" + }, + "description": "Sample for ListDescendantSecurityHealthAnalyticsCustomModules", + "file": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_effective_event_threat_detection_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveEventThreatDetectionCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListEffectiveEventThreatDetectionCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesAsyncPager", + "shortName": "list_effective_event_threat_detection_custom_modules" + }, + "description": "Sample for ListEffectiveEventThreatDetectionCustomModules", + "file": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_effective_event_threat_detection_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveEventThreatDetectionCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListEffectiveEventThreatDetectionCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesPager", + "shortName": "list_effective_event_threat_detection_custom_modules" + }, + "description": "Sample for ListEffectiveEventThreatDetectionCustomModules", + "file": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_effective_security_health_analytics_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveSecurityHealthAnalyticsCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListEffectiveSecurityHealthAnalyticsCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager", + "shortName": "list_effective_security_health_analytics_custom_modules" + }, + "description": "Sample for ListEffectiveSecurityHealthAnalyticsCustomModules", + "file": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_effective_security_health_analytics_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveSecurityHealthAnalyticsCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListEffectiveSecurityHealthAnalyticsCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager", + "shortName": "list_effective_security_health_analytics_custom_modules" + }, + "description": "Sample for ListEffectiveSecurityHealthAnalyticsCustomModules", + "file": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_event_threat_detection_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEventThreatDetectionCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListEventThreatDetectionCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesAsyncPager", + "shortName": "list_event_threat_detection_custom_modules" + }, + "description": "Sample for ListEventThreatDetectionCustomModules", + "file": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_event_threat_detection_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEventThreatDetectionCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListEventThreatDetectionCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesPager", + "shortName": "list_event_threat_detection_custom_modules" + }, + "description": "Sample for ListEventThreatDetectionCustomModules", + "file": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_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.securitycenter_v1.services.security_center.pagers.ListFindingsAsyncPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v1_generated_security_center_list_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1_generated_security_center_list_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_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.securitycenter_v1.services.security_center.pagers.ListFindingsPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v1_generated_security_center_list_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1_generated_security_center_list_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_mute_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListMuteConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListMuteConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListMuteConfigsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsAsyncPager", + "shortName": "list_mute_configs" + }, + "description": "Sample for ListMuteConfigs", + "file": "securitycenter_v1_generated_security_center_list_mute_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v1_generated_security_center_list_mute_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_mute_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListMuteConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListMuteConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListMuteConfigsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsPager", + "shortName": "list_mute_configs" + }, + "description": "Sample for ListMuteConfigs", + "file": "securitycenter_v1_generated_security_center_list_mute_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v1_generated_security_center_list_mute_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsAsyncPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v1_generated_security_center_list_notification_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1_generated_security_center_list_notification_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v1_generated_security_center_list_notification_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1_generated_security_center_list_notification_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsAsyncPager", + "shortName": "list_resource_value_configs" + }, + "description": "Sample for ListResourceValueConfigs", + "file": "securitycenter_v1_generated_security_center_list_resource_value_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v1_generated_security_center_list_resource_value_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsPager", + "shortName": "list_resource_value_configs" + }, + "description": "Sample for ListResourceValueConfigs", + "file": "securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_security_health_analytics_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSecurityHealthAnalyticsCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSecurityHealthAnalyticsCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager", + "shortName": "list_security_health_analytics_custom_modules" + }, + "description": "Sample for ListSecurityHealthAnalyticsCustomModules", + "file": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_security_health_analytics_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSecurityHealthAnalyticsCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSecurityHealthAnalyticsCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesPager", + "shortName": "list_security_health_analytics_custom_modules" + }, + "description": "Sample for ListSecurityHealthAnalyticsCustomModules", + "file": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListSourcesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListSourcesAsyncPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v1_generated_security_center_list_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSources_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": "securitycenter_v1_generated_security_center_list_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListSourcesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListSourcesPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v1_generated_security_center_list_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSources_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": "securitycenter_v1_generated_security_center_list_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_valued_resources", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListValuedResources", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListValuedResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListValuedResourcesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesAsyncPager", + "shortName": "list_valued_resources" + }, + "description": "Sample for ListValuedResources", + "file": "securitycenter_v1_generated_security_center_list_valued_resources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v1_generated_security_center_list_valued_resources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_valued_resources", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListValuedResources", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListValuedResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListValuedResourcesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesPager", + "shortName": "list_valued_resources" + }, + "description": "Sample for ListValuedResources", + "file": "securitycenter_v1_generated_security_center_list_valued_resources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v1_generated_security_center_list_valued_resources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.run_asset_discovery", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.RunAssetDiscovery", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "RunAssetDiscovery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "run_asset_discovery" + }, + "description": "Sample for RunAssetDiscovery", + "file": "securitycenter_v1_generated_security_center_run_asset_discovery_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1_generated_security_center_run_asset_discovery_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.run_asset_discovery", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.RunAssetDiscovery", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "RunAssetDiscovery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "run_asset_discovery" + }, + "description": "Sample for RunAssetDiscovery", + "file": "securitycenter_v1_generated_security_center_run_asset_discovery_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1_generated_security_center_run_asset_discovery_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v1.types.Finding.State" + }, + { + "name": "start_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v1_generated_security_center_set_finding_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1_generated_security_center_set_finding_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v1.types.Finding.State" + }, + { + "name": "start_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v1_generated_security_center_set_finding_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1_generated_security_center_set_finding_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v1_generated_security_center_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v1_generated_security_center_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.set_mute", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetMute", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetMute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.SetMuteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "mute", + "type": "google.cloud.securitycenter_v1.types.Finding.Mute" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "set_mute" + }, + "description": "Sample for SetMute", + "file": "securitycenter_v1_generated_security_center_set_mute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SetMute_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": "securitycenter_v1_generated_security_center_set_mute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.set_mute", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetMute", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetMute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.SetMuteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "mute", + "type": "google.cloud.securitycenter_v1.types.Finding.Mute" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "set_mute" + }, + "description": "Sample for SetMute", + "file": "securitycenter_v1_generated_security_center_set_mute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SetMute_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": "securitycenter_v1_generated_security_center_set_mute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.simulate_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SimulateSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SimulateSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "custom_config", + "type": "google.cloud.securitycenter_v1.types.CustomConfig" + }, + { + "name": "resource", + "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse", + "shortName": "simulate_security_health_analytics_custom_module" + }, + "description": "Sample for SimulateSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.simulate_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SimulateSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SimulateSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "custom_config", + "type": "google.cloud.securitycenter_v1.types.CustomConfig" + }, + { + "name": "resource", + "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse", + "shortName": "simulate_security_health_analytics_custom_module" + }, + "description": "Sample for SimulateSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v1_generated_security_center_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v1_generated_security_center_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v1.types.BigQueryExport" + }, + { + "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.securitycenter_v1.types.BigQueryExport", + "shortName": "update_big_query_export" + }, + "description": "Sample for UpdateBigQueryExport", + "file": "securitycenter_v1_generated_security_center_update_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v1_generated_security_center_update_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v1.types.BigQueryExport" + }, + { + "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.securitycenter_v1.types.BigQueryExport", + "shortName": "update_big_query_export" + }, + "description": "Sample for UpdateBigQueryExport", + "file": "securitycenter_v1_generated_security_center_update_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v1_generated_security_center_update_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest" + }, + { + "name": "event_threat_detection_custom_module", + "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" + }, + { + "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.securitycenter_v1.types.EventThreatDetectionCustomModule", + "shortName": "update_event_threat_detection_custom_module" + }, + "description": "Sample for UpdateEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest" + }, + { + "name": "event_threat_detection_custom_module", + "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" + }, + { + "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.securitycenter_v1.types.EventThreatDetectionCustomModule", + "shortName": "update_event_threat_detection_custom_module" + }, + "description": "Sample for UpdateEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_external_system", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateExternalSystem", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateExternalSystem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest" + }, + { + "name": "external_system", + "type": "google.cloud.securitycenter_v1.types.ExternalSystem" + }, + { + "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.securitycenter_v1.types.ExternalSystem", + "shortName": "update_external_system" + }, + "description": "Sample for UpdateExternalSystem", + "file": "securitycenter_v1_generated_security_center_update_external_system_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v1_generated_security_center_update_external_system_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_external_system", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateExternalSystem", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateExternalSystem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest" + }, + { + "name": "external_system", + "type": "google.cloud.securitycenter_v1.types.ExternalSystem" + }, + { + "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.securitycenter_v1.types.ExternalSystem", + "shortName": "update_external_system" + }, + "description": "Sample for UpdateExternalSystem", + "file": "securitycenter_v1_generated_security_center_update_external_system_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v1_generated_security_center_update_external_system_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v1_generated_security_center_update_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1_generated_security_center_update_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v1_generated_security_center_update_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1_generated_security_center_update_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v1.types.MuteConfig" + }, + { + "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.securitycenter_v1.types.MuteConfig", + "shortName": "update_mute_config" + }, + "description": "Sample for UpdateMuteConfig", + "file": "securitycenter_v1_generated_security_center_update_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v1_generated_security_center_update_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v1.types.MuteConfig" + }, + { + "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.securitycenter_v1.types.MuteConfig", + "shortName": "update_mute_config" + }, + "description": "Sample for UpdateMuteConfig", + "file": "securitycenter_v1_generated_security_center_update_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v1_generated_security_center_update_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1.types.NotificationConfig" + }, + { + "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.securitycenter_v1.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v1_generated_security_center_update_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1_generated_security_center_update_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1.types.NotificationConfig" + }, + { + "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.securitycenter_v1.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v1_generated_security_center_update_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1_generated_security_center_update_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest" + }, + { + "name": "organization_settings", + "type": "google.cloud.securitycenter_v1.types.OrganizationSettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.OrganizationSettings", + "shortName": "update_organization_settings" + }, + "description": "Sample for UpdateOrganizationSettings", + "file": "securitycenter_v1_generated_security_center_update_organization_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1_generated_security_center_update_organization_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest" + }, + { + "name": "organization_settings", + "type": "google.cloud.securitycenter_v1.types.OrganizationSettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.OrganizationSettings", + "shortName": "update_organization_settings" + }, + "description": "Sample for UpdateOrganizationSettings", + "file": "securitycenter_v1_generated_security_center_update_organization_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1_generated_security_center_update_organization_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest" + }, + { + "name": "resource_value_config", + "type": "google.cloud.securitycenter_v1.types.ResourceValueConfig" + }, + { + "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.securitycenter_v1.types.ResourceValueConfig", + "shortName": "update_resource_value_config" + }, + "description": "Sample for UpdateResourceValueConfig", + "file": "securitycenter_v1_generated_security_center_update_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v1_generated_security_center_update_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest" + }, + { + "name": "resource_value_config", + "type": "google.cloud.securitycenter_v1.types.ResourceValueConfig" + }, + { + "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.securitycenter_v1.types.ResourceValueConfig", + "shortName": "update_resource_value_config" + }, + "description": "Sample for UpdateResourceValueConfig", + "file": "securitycenter_v1_generated_security_center_update_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v1_generated_security_center_update_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "name": "security_health_analytics_custom_module", + "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" + }, + { + "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", + "shortName": "update_security_health_analytics_custom_module" + }, + "description": "Sample for UpdateSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "name": "security_health_analytics_custom_module", + "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" + }, + { + "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", + "shortName": "update_security_health_analytics_custom_module" + }, + "description": "Sample for UpdateSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v1.types.SecurityMarks" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v1_generated_security_center_update_security_marks_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1_generated_security_center_update_security_marks_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v1.types.SecurityMarks" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v1_generated_security_center_update_security_marks_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1_generated_security_center_update_security_marks_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v1_generated_security_center_update_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1_generated_security_center_update_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v1_generated_security_center_update_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1_generated_security_center_update_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.validate_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ValidateEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ValidateEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse", + "shortName": "validate_event_threat_detection_custom_module" + }, + "description": "Sample for ValidateEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.validate_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ValidateEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ValidateEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse", + "shortName": "validate_event_threat_detection_custom_module" + }, + "description": "Sample for ValidateEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py new file mode 100644 index 000000000000..f99f1a291b7b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py @@ -0,0 +1,238 @@ +#! /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 securitycenterCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_create_resource_value_configs': ('parent', 'requests', ), + 'bulk_mute_findings': ('parent', 'filter', 'mute_annotation', ), + 'create_big_query_export': ('parent', 'big_query_export', 'big_query_export_id', ), + 'create_event_threat_detection_custom_module': ('parent', 'event_threat_detection_custom_module', ), + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_mute_config': ('parent', 'mute_config', 'mute_config_id', ), + 'create_notification_config': ('parent', 'config_id', 'notification_config', ), + 'create_security_health_analytics_custom_module': ('parent', 'security_health_analytics_custom_module', ), + 'create_source': ('parent', 'source', ), + 'delete_big_query_export': ('name', ), + 'delete_event_threat_detection_custom_module': ('name', ), + 'delete_mute_config': ('name', ), + 'delete_notification_config': ('name', ), + 'delete_resource_value_config': ('name', ), + 'delete_security_health_analytics_custom_module': ('name', ), + 'get_big_query_export': ('name', ), + 'get_effective_event_threat_detection_custom_module': ('name', ), + 'get_effective_security_health_analytics_custom_module': ('name', ), + 'get_event_threat_detection_custom_module': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_mute_config': ('name', ), + 'get_notification_config': ('name', ), + 'get_organization_settings': ('name', ), + 'get_resource_value_config': ('name', ), + 'get_security_health_analytics_custom_module': ('name', ), + 'get_simulation': ('name', ), + 'get_source': ('name', ), + 'get_valued_resource': ('name', ), + 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), + 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), + 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_attack_paths': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_big_query_exports': ('parent', 'page_size', 'page_token', ), + 'list_descendant_event_threat_detection_custom_modules': ('parent', 'page_token', 'page_size', ), + 'list_descendant_security_health_analytics_custom_modules': ('parent', 'page_size', 'page_token', ), + 'list_effective_event_threat_detection_custom_modules': ('parent', 'page_token', 'page_size', ), + 'list_effective_security_health_analytics_custom_modules': ('parent', 'page_size', 'page_token', ), + 'list_event_threat_detection_custom_modules': ('parent', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_mute_configs': ('parent', 'page_size', 'page_token', ), + 'list_notification_configs': ('parent', 'page_token', 'page_size', ), + 'list_resource_value_configs': ('parent', 'page_size', 'page_token', ), + 'list_security_health_analytics_custom_modules': ('parent', 'page_size', 'page_token', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'list_valued_resources': ('parent', 'filter', 'page_token', 'page_size', 'order_by', ), + 'run_asset_discovery': ('parent', ), + 'set_finding_state': ('name', 'state', 'start_time', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'set_mute': ('name', 'mute', ), + 'simulate_security_health_analytics_custom_module': ('parent', 'custom_config', 'resource', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_big_query_export': ('big_query_export', 'update_mask', ), + 'update_event_threat_detection_custom_module': ('event_threat_detection_custom_module', 'update_mask', ), + 'update_external_system': ('external_system', 'update_mask', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_mute_config': ('mute_config', 'update_mask', ), + 'update_notification_config': ('notification_config', 'update_mask', ), + 'update_organization_settings': ('organization_settings', 'update_mask', ), + 'update_resource_value_config': ('resource_value_config', 'update_mask', ), + 'update_security_health_analytics_custom_module': ('security_health_analytics_custom_module', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), + 'update_source': ('source', 'update_mask', ), + 'validate_event_threat_detection_custom_module': ('parent', 'raw_text', 'type_', ), + } + + 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=securitycenterCallTransformer(), +): + """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 securitycenter 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-securitycenter/v1/setup.py b/owl-bot-staging/google-cloud-securitycenter/v1/setup.py new file mode 100644 index 000000000000..c4538ec101f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/setup.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. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-securitycenter' + + +description = "Google Cloud Securitycenter API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/securitycenter/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", + "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", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/unit/gapic/securitycenter_v1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_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-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py new file mode 100644 index 000000000000..7d5099f2f3cd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py @@ -0,0 +1,48250 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +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 + +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.securitycenter_v1.services.security_center import SecurityCenterAsyncClient +from google.cloud.securitycenter_v1.services.security_center import SecurityCenterClient +from google.cloud.securitycenter_v1.services.security_center import pagers +from google.cloud.securitycenter_v1.services.security_center import transports +from google.cloud.securitycenter_v1.types import access +from google.cloud.securitycenter_v1.types import application +from google.cloud.securitycenter_v1.types import attack_exposure +from google.cloud.securitycenter_v1.types import attack_path +from google.cloud.securitycenter_v1.types import backup_disaster_recovery +from google.cloud.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import cloud_armor +from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile +from google.cloud.securitycenter_v1.types import cloud_dlp_inspection +from google.cloud.securitycenter_v1.types import compliance +from google.cloud.securitycenter_v1.types import connection +from google.cloud.securitycenter_v1.types import contact_details +from google.cloud.securitycenter_v1.types import container +from google.cloud.securitycenter_v1.types import database +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors +from google.cloud.securitycenter_v1.types import exfiltration +from google.cloud.securitycenter_v1.types import external_system +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import file +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import group_membership +from google.cloud.securitycenter_v1.types import iam_binding +from google.cloud.securitycenter_v1.types import indicator +from google.cloud.securitycenter_v1.types import kernel_rootkit +from google.cloud.securitycenter_v1.types import kubernetes +from google.cloud.securitycenter_v1.types import label +from google.cloud.securitycenter_v1.types import load_balancer +from google.cloud.securitycenter_v1.types import log_entry +from google.cloud.securitycenter_v1.types import mitre_attack +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notebook +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import org_policy +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import process +from google.cloud.securitycenter_v1.types import resource +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import security_posture +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import toxic_combination +from google.cloud.securitycenter_v1.types import valued_resource +from google.cloud.securitycenter_v1.types import vulnerability +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 duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None + assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SecurityCenterClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SecurityCenterGrpcTransport, "grpc"), + (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + 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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + available_transports = [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterRestTransport, + ] + assert transport in available_transports + + transport = SecurityCenterClient.get_transport_class("grpc") + assert transport == transports.SecurityCenterGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, 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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), +]) +def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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_security_center_client_client_options_from_dict(): + with mock.patch('google.cloud.securitycenter_v1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.BulkMuteFindingsRequest, + dict, +]) +def test_bulk_mute_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BulkMuteFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_bulk_mute_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.bulk_mute_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest() + + +def test_bulk_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.BulkMuteFindingsRequest( + parent='parent_value', + filter='filter_value', + mute_annotation='mute_annotation_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.bulk_mute_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest( + parent='parent_value', + filter='filter_value', + mute_annotation='mute_annotation_value', + ) + +def test_bulk_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc + request = {} + client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest() + +@pytest.mark.asyncio +async def test_bulk_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.bulk_mute_findings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.bulk_mute_findings] = mock_object + + request = {} + await client.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.bulk_mute_findings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_bulk_mute_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BulkMuteFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BulkMuteFindingsRequest() + 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_bulk_mute_findings_async_from_dict(): + await test_bulk_mute_findings_async(request_type=dict) + + +def test_bulk_mute_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BulkMuteFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.bulk_mute_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_bulk_mute_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BulkMuteFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.bulk_mute_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_bulk_mute_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings( + 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_bulk_mute_findings_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_bulk_mute_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings( + 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_bulk_mute_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_create_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + ) + response = client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + + +def test_create_security_health_analytics_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + + +def test_create_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_security_health_analytics_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest( + parent='parent_value', + ) + +def test_create_security_health_analytics_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc + request = {} + client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_security_health_analytics_custom_module(request) + + # Establish that a new wrapper 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_security_health_analytics_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + )) + response = await client.create_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + +@pytest.mark.asyncio +async def test_create_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_security_health_analytics_custom_module] = mock_object + + request = {} + await client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + )) + response = await client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + + +@pytest.mark.asyncio +async def test_create_security_health_analytics_custom_module_async_from_dict(): + await test_create_security_health_analytics_custom_module_async(request_type=dict) + + +def test_create_security_health_analytics_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_security_health_analytics_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + await client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_security_health_analytics_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_security_health_analytics_custom_module( + parent='parent_value', + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + ) + + # Establish that the 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].security_health_analytics_custom_module + mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value') + assert arg == mock_val + + +def test_create_security_health_analytics_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_health_analytics_custom_module( + securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(), + parent='parent_value', + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_security_health_analytics_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_security_health_analytics_custom_module( + parent='parent_value', + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + ) + + # Establish that 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].security_health_analytics_custom_module + mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_security_health_analytics_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_security_health_analytics_custom_module( + securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(), + parent='parent_value', + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_create_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object + + request = {} + await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_create_source_async_from_dict(): + await test_create_source_async(request_type=dict) + + +def test_create_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.create_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.create_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + + +def test_create_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_create_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.create_finding] = mock_rpc + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object + + request = {} + await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_create_finding_async_from_dict(): + await test_create_finding_async(request_type=dict) + + +def test_create_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + arg = args[0].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + + +def test_create_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + arg = args[0].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateMuteConfigRequest, + dict, +]) +def test_create_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + ) + response = client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + + +def test_create_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest() + + +def test_create_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateMuteConfigRequest( + parent='parent_value', + mute_config_id='mute_config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest( + parent='parent_value', + mute_config_id='mute_config_id_value', + ) + +def test_create_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + request = {} + client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + )) + response = await client.create_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest() + +@pytest.mark.asyncio +async def test_create_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_mute_config] = mock_object + + request = {} + await client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + )) + response = await client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + + +@pytest.mark.asyncio +async def test_create_mute_config_async_from_dict(): + await test_create_mute_config_async(request_type=dict) + + +def test_create_mute_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateMuteConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.create_mute_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_mute_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateMuteConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) + await client.create_mute_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_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_mute_config( + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_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].mute_config + mock_val = gcs_mute_config.MuteConfig(name='name_value') + assert arg == mock_val + arg = args[0].mute_config_id + mock_val = 'mute_config_id_value' + assert arg == mock_val + + +def test_create_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_mute_config( + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_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].mute_config + mock_val = gcs_mute_config.MuteConfig(name='name_value') + assert arg == mock_val + arg = args[0].mute_config_id + mock_val = 'mute_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateNotificationConfigRequest, + dict, +]) +def test_create_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_create_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateNotificationConfigRequest( + parent='parent_value', + config_id='config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest( + parent='parent_value', + config_id='config_id_value', + ) + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_create_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_notification_config] = mock_object + + request = {} + await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_create_notification_config_async_from_dict(): + await test_create_notification_config_async(request_type=dict) + + +def test_create_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.create_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.create_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_notification_config( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + # Establish that the 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].config_id + mock_val = 'config_id_value' + assert arg == mock_val + arg = args[0].notification_config + mock_val = gcs_notification_config.NotificationConfig(name='name_value') + assert arg == mock_val + + +def test_create_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_notification_config( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + # Establish that 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].config_id + mock_val = 'config_id_value' + assert arg == mock_val + arg = args[0].notification_config + mock_val = gcs_notification_config.NotificationConfig(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_notification_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteMuteConfigRequest, + dict, +]) +def test_delete_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest() + + +def test_delete_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteMuteConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest( + name='name_value', + ) + +def test_delete_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + request = {} + client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest() + +@pytest.mark.asyncio +async def test_delete_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_mute_config] = mock_object + + request = {} + await client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteMuteConfigRequest() + 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_mute_config_async_from_dict(): + await test_delete_mute_config_async(request_type=dict) + + +def test_delete_mute_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteMuteConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value = None + client.delete_mute_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_mute_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteMuteConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_mute_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_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, +]) +def test_delete_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteNotificationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest( + name='name_value', + ) + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_delete_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_notification_config] = mock_object + + request = {} + await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteNotificationConfigRequest() + 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_config_async_from_dict(): + await test_delete_notification_config_async(request_type=dict) + + +def test_delete_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = None + client.delete_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_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_notification_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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_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_notification_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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_notification_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_delete_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_security_health_analytics_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + + +def test_delete_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_security_health_analytics_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest( + name='name_value', + ) + +def test_delete_security_health_analytics_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc + request = {} + client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_security_health_analytics_custom_module(request) + + # Establish that a new wrapper 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_security_health_analytics_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + +@pytest.mark.asyncio +async def test_delete_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_security_health_analytics_custom_module] = mock_object + + request = {} + await client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + 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_security_health_analytics_custom_module_async_from_dict(): + await test_delete_security_health_analytics_custom_module_async(request_type=dict) + + +def test_delete_security_health_analytics_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = None + client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_security_health_analytics_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_security_health_analytics_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__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_security_health_analytics_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_security_health_analytics_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_health_analytics_custom_module( + securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_security_health_analytics_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__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_security_health_analytics_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_security_health_analytics_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_security_health_analytics_custom_module( + securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSimulationRequest, + dict, +]) +def test_get_simulation(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + response = client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSimulationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == 'name_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +def test_get_simulation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_simulation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest() + + +def test_get_simulation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSimulationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_simulation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest( + name='name_value', + ) + +def test_get_simulation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_simulation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc + request = {} + client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_simulation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_simulation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_simulation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest() + +@pytest.mark.asyncio +async def test_get_simulation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_simulation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_simulation] = mock_object + + request = {} + await client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_simulation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_simulation_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSimulationRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSimulationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == 'name_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +@pytest.mark.asyncio +async def test_get_simulation_async_from_dict(): + await test_get_simulation_async(request_type=dict) + + +def test_get_simulation_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSimulationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value = simulation.Simulation() + client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_simulation_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSimulationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) + await client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_simulation_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_simulation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_simulation_flattened_error(): + client = SecurityCenterClient( + credentials=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_simulation( + securitycenter_service.GetSimulationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_simulation_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_simulation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_simulation_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_simulation( + securitycenter_service.GetSimulationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetValuedResourceRequest, + dict, +]) +def test_get_valued_resource(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + ) + response = client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetValuedResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == 'name_value' + assert response.resource == 'resource_value' + assert response.resource_type == 'resource_type_value' + assert response.display_name == 'display_name_value' + assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + + +def test_get_valued_resource_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_valued_resource() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest() + + +def test_get_valued_resource_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetValuedResourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_valued_resource(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest( + name='name_value', + ) + +def test_get_valued_resource_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_valued_resource in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc + request = {} + client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_valued_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_valued_resource_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + )) + response = await client.get_valued_resource() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest() + +@pytest.mark.asyncio +async def test_get_valued_resource_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_valued_resource in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_valued_resource] = mock_object + + request = {} + await client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_valued_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_valued_resource_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetValuedResourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + )) + response = await client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetValuedResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == 'name_value' + assert response.resource == 'resource_value' + assert response.resource_type == 'resource_type_value' + assert response.display_name == 'display_name_value' + assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + + +@pytest.mark.asyncio +async def test_get_valued_resource_async_from_dict(): + await test_get_valued_resource_async(request_type=dict) + + +def test_get_valued_resource_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetValuedResourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value = valued_resource.ValuedResource() + client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_valued_resource_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetValuedResourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) + await client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_valued_resource_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_valued_resource( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_valued_resource_flattened_error(): + client = SecurityCenterClient( + credentials=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_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_valued_resource_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_valued_resource( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_valued_resource_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetBigQueryExportRequest, + dict, +]) +def test_get_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + response = client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +def test_get_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest() + + +def test_get_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetBigQueryExportRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest( + name='name_value', + ) + +def test_get_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc + request = {} + client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.get_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_get_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_big_query_export] = mock_object + + request = {} + await client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +@pytest.mark.asyncio +async def test_get_big_query_export_async_from_dict(): + await test_get_big_query_export_async(request_type=dict) + + +def test_get_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value = bigquery_export.BigQueryExport() + client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + await client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.GetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest( + resource='resource_value', + ) + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object + + request = {} + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetMuteConfigRequest, + dict, +]) +def test_get_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + ) + response = client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + + +def test_get_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest() + + +def test_get_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetMuteConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest( + name='name_value', + ) + +def test_get_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_mute_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_mute_config] = mock_rpc + request = {} + client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + )) + response = await client.get_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest() + +@pytest.mark.asyncio +async def test_get_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_mute_config] = mock_object + + request = {} + await client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + )) + response = await client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + + +@pytest.mark.asyncio +async def test_get_mute_config_async_from_dict(): + await test_get_mute_config_async(request_type=dict) + + +def test_get_mute_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetMuteConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value = mute_config.MuteConfig() + client.get_mute_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_mute_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetMuteConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig()) + await client.get_mute_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_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_mute_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_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_mute_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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetNotificationConfigRequest, + dict, +]) +def test_get_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_get_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetNotificationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest( + name='name_value', + ) + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_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_notification_config] = mock_rpc + request = {} + client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_get_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_notification_config] = mock_object + + request = {} + await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_get_notification_config_async_from_dict(): + await test_get_notification_config_async(request_type=dict) + + +def test_get_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = notification_config.NotificationConfig() + client.get_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + await client.get_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_notification_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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_notification_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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_notification_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetOrganizationSettingsRequest, + dict, +]) +def test_get_organization_settings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_get_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetOrganizationSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_organization_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest( + name='name_value', + ) + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_organization_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_organization_settings] = mock_rpc + request = {} + client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_organization_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_organization_settings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + +@pytest.mark.asyncio +async def test_get_organization_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_organization_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_organization_settings] = mock_object + + request = {} + await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_organization_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_get_organization_settings_async_from_dict(): + await test_get_organization_settings_async(request_type=dict) + + +def test_get_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = organization_settings.OrganizationSettings() + client.get_organization_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_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + await client.get_organization_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_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_organization_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_organization_settings_flattened_error(): + client = SecurityCenterClient( + credentials=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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_organization_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_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_get_effective_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( + name='name_value', + enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + display_name='display_name_value', + ) + response = client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.enablement_state == effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.display_name == 'display_name_value' + + +def test_get_effective_security_health_analytics_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_effective_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + + +def test_get_effective_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_effective_security_health_analytics_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( + name='name_value', + ) + +def test_get_effective_security_health_analytics_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_effective_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_effective_security_health_analytics_custom_module] = mock_rpc + request = {} + client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_effective_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_effective_security_health_analytics_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( + name='name_value', + enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + display_name='display_name_value', + )) + response = await client.get_effective_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + +@pytest.mark.asyncio +async def test_get_effective_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_effective_security_health_analytics_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_effective_security_health_analytics_custom_module] = mock_object + + request = {} + await client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_effective_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_effective_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( + name='name_value', + enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + display_name='display_name_value', + )) + response = await client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.enablement_state == effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_get_effective_security_health_analytics_custom_module_async_from_dict(): + await test_get_effective_security_health_analytics_custom_module_async(request_type=dict) + + +def test_get_effective_security_health_analytics_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_effective_security_health_analytics_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule()) + await client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_effective_security_health_analytics_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_effective_security_health_analytics_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_effective_security_health_analytics_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_effective_security_health_analytics_custom_module( + securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_effective_security_health_analytics_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_effective_security_health_analytics_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_effective_security_health_analytics_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_effective_security_health_analytics_custom_module( + securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_get_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + ) + response = client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + + +def test_get_security_health_analytics_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + + +def test_get_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_security_health_analytics_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest( + name='name_value', + ) + +def test_get_security_health_analytics_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_security_health_analytics_custom_module] = mock_rpc + request = {} + client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_security_health_analytics_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + )) + response = await client.get_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + +@pytest.mark.asyncio +async def test_get_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_security_health_analytics_custom_module] = mock_object + + request = {} + await client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + )) + response = await client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + + +@pytest.mark.asyncio +async def test_get_security_health_analytics_custom_module_async_from_dict(): + await test_get_security_health_analytics_custom_module_async(request_type=dict) + + +def test_get_security_health_analytics_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_security_health_analytics_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + await client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_security_health_analytics_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_security_health_analytics_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_security_health_analytics_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_health_analytics_custom_module( + securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_security_health_analytics_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_security_health_analytics_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_security_health_analytics_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_security_health_analytics_custom_module( + securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_get_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest( + name='name_value', + ) + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + +@pytest.mark.asyncio +async def test_get_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object + + request = {} + await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_get_source_async_from_dict(): + await test_get_source_async(request_type=dict) + + +def test_get_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = source.Source() + client.get_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + await client.get_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_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_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupAssetsRequest, + dict, +]) +def test_group_assets(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_assets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + +def test_group_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupAssetsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc + request = {} + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_group_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + +@pytest.mark.asyncio +async def test_group_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_assets] = mock_object + + request = {} + await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_assets_async_from_dict(): + await test_group_assets_async(request_type=dict) + + +def test_group_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = securitycenter_service.GroupAssetsResponse() + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_group_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) + await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_group_assets_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_assets(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, securitycenter_service.GroupResult) + for i in results) +def test_group_assets_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_assets(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_group_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_assets(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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_assets(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", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + +@pytest.mark.asyncio +async def test_group_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_findings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object + + request = {} + await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_findings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_findings_async_from_dict(): + await test_group_findings_async(request_type=dict) + + +def test_group_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = securitycenter_service.GroupFindingsResponse() + client.group_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_group_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + await client.group_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_group_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that the 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + + +def test_group_findings_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + +@pytest.mark.asyncio +async def test_group_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_group_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_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, securitycenter_service.GroupResult) + for i in results) +def test_group_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_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_group_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_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", [ + securitycenter_service.ListAssetsRequest, + dict, +]) +def test_list_assets(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_assets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + +def test_list_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListAssetsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_value', + page_token='page_token_value', + ) + +def test_list_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + +@pytest.mark.asyncio +async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object + + request = {} + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + + +def test_list_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = securitycenter_service.ListAssetsResponse() + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_assets_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) +def test_list_assets_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(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_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + 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_assets(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", [ + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, + dict, +]) +def test_list_descendant_security_health_analytics_custom_modules(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_descendant_security_health_analytics_custom_modules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_descendant_security_health_analytics_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + + +def test_list_descendant_security_health_analytics_custom_modules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( + 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_descendant_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_descendant_security_health_analytics_custom_modules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_descendant_security_health_analytics_custom_modules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_descendant_security_health_analytics_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_descendant_security_health_analytics_custom_modules] = mock_rpc + request = {} + client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_descendant_security_health_analytics_custom_modules_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_descendant_security_health_analytics_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + +@pytest.mark.asyncio +async def test_list_descendant_security_health_analytics_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_descendant_security_health_analytics_custom_modules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_descendant_security_health_analytics_custom_modules] = mock_object + + request = {} + await client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_descendant_security_health_analytics_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_descendant_security_health_analytics_custom_modules_async_from_dict(): + await test_list_descendant_security_health_analytics_custom_modules_async(request_type=dict) + + +def test_list_descendant_security_health_analytics_custom_modules_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_descendant_security_health_analytics_custom_modules_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse()) + await client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_descendant_security_health_analytics_custom_modules_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_descendant_security_health_analytics_custom_modules( + 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_descendant_security_health_analytics_custom_modules_flattened_error(): + client = SecurityCenterClient( + credentials=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_descendant_security_health_analytics_custom_modules( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_descendant_security_health_analytics_custom_modules_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_descendant_security_health_analytics_custom_modules( + 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_descendant_security_health_analytics_custom_modules_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_descendant_security_health_analytics_custom_modules( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_descendant_security_health_analytics_custom_modules_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_descendant_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + for i in results) +def test_list_descendant_security_health_analytics_custom_modules_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_descendant_security_health_analytics_custom_modules(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_descendant_security_health_analytics_custom_modules_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_descendant_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_descendant_security_health_analytics_custom_modules_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + 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_descendant_security_health_analytics_custom_modules(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", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +def test_list_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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] == securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + +@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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object + + request = {} + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +@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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in results) +def test_list_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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 = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_findings_async_pages(): + client = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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", [ + securitycenter_service.ListMuteConfigsRequest, + dict, +]) +def test_list_mute_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListMuteConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_mute_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_mute_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest() + + +def test_list_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListMuteConfigsRequest( + 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_mute_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_mute_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_mute_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_mute_configs] = mock_rpc + request = {} + client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_mute_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_mute_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_mute_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest() + +@pytest.mark.asyncio +async def test_list_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_mute_configs] = mock_object + + request = {} + await client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_mute_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_mute_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListMuteConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListMuteConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_mute_configs_async_from_dict(): + await test_list_mute_configs_async(request_type=dict) + + +def test_list_mute_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListMuteConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListMuteConfigsResponse() + client.list_mute_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_mute_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListMuteConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse()) + await client.list_mute_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_mute_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_mute_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_mute_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_mute_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_mute_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_mute_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent='parent_value', + ) + + +def test_list_mute_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_mute_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, mute_config.MuteConfig) + for i in results) +def test_list_mute_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_mute_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_mute_configs_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_mute_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, mute_config.MuteConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_mute_configs_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + 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_mute_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", [ + securitycenter_service.ListNotificationConfigsRequest, + dict, +]) +def test_list_notification_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListNotificationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_notification_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListNotificationConfigsRequest( + 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_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notification_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_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_notification_configs] = mock_rpc + request = {} + client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_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_notification_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + +@pytest.mark.asyncio +async def test_list_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_notification_configs] = mock_object + + request = {} + await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_notification_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListNotificationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_from_dict(): + await test_list_notification_configs_async(request_type=dict) + + +def test_list_notification_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + 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_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + client.list_notification_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_notification_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + 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_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + await client.list_notification_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_notification_configs_flattened(): + client = SecurityCenterClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_notification_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_notification_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_notification_configs_flattened_async(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_notification_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_notification_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_notification_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + 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_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, notification_config.NotificationConfig) + for i in results) +def test_list_notification_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_notification_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_notification_configs_async_pager(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_notification_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, notification_config.NotificationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_pages(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + 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_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", [ + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, + dict, +]) +def test_list_effective_security_health_analytics_custom_modules(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_effective_security_health_analytics_custom_modules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_effective_security_health_analytics_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + + +def test_list_effective_security_health_analytics_custom_modules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( + 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_effective_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_effective_security_health_analytics_custom_modules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_effective_security_health_analytics_custom_modules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_effective_security_health_analytics_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_effective_security_health_analytics_custom_modules] = mock_rpc + request = {} + client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_effective_security_health_analytics_custom_modules_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_effective_security_health_analytics_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + +@pytest.mark.asyncio +async def test_list_effective_security_health_analytics_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_effective_security_health_analytics_custom_modules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_effective_security_health_analytics_custom_modules] = mock_object + + request = {} + await client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_effective_security_health_analytics_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_effective_security_health_analytics_custom_modules_async_from_dict(): + await test_list_effective_security_health_analytics_custom_modules_async(request_type=dict) + + +def test_list_effective_security_health_analytics_custom_modules_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_effective_security_health_analytics_custom_modules_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse()) + await client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_effective_security_health_analytics_custom_modules_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_effective_security_health_analytics_custom_modules( + 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_effective_security_health_analytics_custom_modules_flattened_error(): + client = SecurityCenterClient( + credentials=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_effective_security_health_analytics_custom_modules( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_effective_security_health_analytics_custom_modules_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_effective_security_health_analytics_custom_modules( + 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_effective_security_health_analytics_custom_modules_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_effective_security_health_analytics_custom_modules( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_effective_security_health_analytics_custom_modules_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_effective_security_health_analytics_custom_modules(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, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) + for i in results) +def test_list_effective_security_health_analytics_custom_modules_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_effective_security_health_analytics_custom_modules(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_effective_security_health_analytics_custom_modules_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_effective_security_health_analytics_custom_modules(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, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_effective_security_health_analytics_custom_modules_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + ), + 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_effective_security_health_analytics_custom_modules(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", [ + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, + dict, +]) +def test_list_security_health_analytics_custom_modules(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecurityHealthAnalyticsCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_security_health_analytics_custom_modules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_security_health_analytics_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + + +def test_list_security_health_analytics_custom_modules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest( + 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_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_security_health_analytics_custom_modules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_security_health_analytics_custom_modules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_security_health_analytics_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_security_health_analytics_custom_modules] = mock_rpc + request = {} + client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_security_health_analytics_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_security_health_analytics_custom_modules_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_security_health_analytics_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + +@pytest.mark.asyncio +async def test_list_security_health_analytics_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_health_analytics_custom_modules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_security_health_analytics_custom_modules] = mock_object + + request = {} + await client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_security_health_analytics_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_security_health_analytics_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_security_health_analytics_custom_modules_async_from_dict(): + await test_list_security_health_analytics_custom_modules_async(request_type=dict) + + +def test_list_security_health_analytics_custom_modules_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_security_health_analytics_custom_modules_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse()) + await client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_security_health_analytics_custom_modules_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_security_health_analytics_custom_modules( + 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_security_health_analytics_custom_modules_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_health_analytics_custom_modules( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_security_health_analytics_custom_modules_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_security_health_analytics_custom_modules( + 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_security_health_analytics_custom_modules_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_security_health_analytics_custom_modules( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_security_health_analytics_custom_modules_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + for i in results) +def test_list_security_health_analytics_custom_modules_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_security_health_analytics_custom_modules(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_security_health_analytics_custom_modules_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_security_health_analytics_custom_modules_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + 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_security_health_analytics_custom_modules(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", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListSourcesRequest( + 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_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + +@pytest.mark.asyncio +async def test_list_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_sources in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object + + request = {} + await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_sources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sources_async_from_dict(): + await test_list_sources_async(request_type=dict) + + +def test_list_sources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = securitycenter_service.ListSourcesResponse() + client.list_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_sources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + await client.list_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_sources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_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_sources_flattened_error(): + client = SecurityCenterClient( + credentials=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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_sources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_sources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_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, source.Source) + for i in results) +def test_list_sources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = list(client.list_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_sources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_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, source.Source) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_sources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + 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_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", [ + securitycenter_service.RunAssetDiscoveryRequest, + dict, +]) +def test_run_asset_discovery(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.RunAssetDiscoveryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_asset_discovery_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + +def test_run_asset_discovery_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.RunAssetDiscoveryRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_asset_discovery(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest( + parent='parent_value', + ) + +def test_run_asset_discovery_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_asset_discovery in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc + request = {} + client.run_asset_discovery(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.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_run_asset_discovery_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + +@pytest.mark.asyncio +async def test_run_asset_discovery_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.run_asset_discovery in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.run_asset_discovery] = mock_object + + request = {} + await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.RunAssetDiscoveryRequest() + 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_run_asset_discovery_async_from_dict(): + await test_run_asset_discovery_async(request_type=dict) + + +def test_run_asset_discovery_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_asset_discovery_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_run_asset_discovery_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery( + 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_run_asset_discovery_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_run_asset_discovery_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery( + 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_run_asset_discovery_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_set_finding_state_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + +@pytest.mark.asyncio +async def test_set_finding_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object + + request = {} + await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_finding_state(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_set_finding_state_async_from_dict(): + await test_set_finding_state_async(request_type=dict) + + +def test_set_finding_state_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = finding.Finding() + client.set_finding_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_set_finding_state_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_finding_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_set_finding_state_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetMuteRequest, + dict, +]) +def test_set_mute(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetMuteRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_set_mute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_mute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest() + + +def test_set_mute_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SetMuteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_mute(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest( + name='name_value', + ) + +def test_set_mute_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_mute in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc + request = {} + client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_mute(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_set_mute_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_mute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest() + +@pytest.mark.asyncio +async def test_set_mute_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_mute in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_mute] = mock_object + + request = {} + await client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_mute(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_mute_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetMuteRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetMuteRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_set_mute_async_from_dict(): + await test_set_mute_async(request_type=dict) + + +def test_set_mute_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetMuteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value = finding.Finding() + client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_mute_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetMuteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_set_mute_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__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.set_mute( + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].mute + mock_val = finding.Finding.Mute.MUTED + assert arg == mock_val + + +def test_set_mute_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_mute( + securitycenter_service.SetMuteRequest(), + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + +@pytest.mark.asyncio +async def test_set_mute_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__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.set_mute( + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].mute + mock_val = finding.Finding.Mute.MUTED + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_mute_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_mute( + securitycenter_service.SetMuteRequest(), + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.SetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest( + resource='resource_value', + ) + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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( + version=774, + etag=b'etag_blob', + )) + response = await client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object + + request = {} + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = SecurityCenterClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.TestIamPermissionsRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( + resource='resource_value', + ) + +def test_test_iam_permissions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object + + request = {} + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_simulate_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( + ) + response = client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) + + +def test_simulate_security_health_analytics_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.simulate_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + + +def test_simulate_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.simulate_security_health_analytics_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest( + parent='parent_value', + ) + +def test_simulate_security_health_analytics_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.simulate_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.simulate_security_health_analytics_custom_module] = mock_rpc + request = {} + client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.simulate_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( + )) + response = await client.simulate_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.simulate_security_health_analytics_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.simulate_security_health_analytics_custom_module] = mock_object + + request = {} + await client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.simulate_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( + )) + response = await client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) + + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_async_from_dict(): + await test_simulate_security_health_analytics_custom_module_async(request_type=dict) + + +def test_simulate_security_health_analytics_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse()) + await client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_simulate_security_health_analytics_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.simulate_security_health_analytics_custom_module( + parent='parent_value', + custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), + resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), + ) + + # Establish that the 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].custom_config + mock_val = security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')) + assert arg == mock_val + arg = args[0].resource + mock_val = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value') + assert arg == mock_val + + +def test_simulate_security_health_analytics_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.simulate_security_health_analytics_custom_module( + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(), + parent='parent_value', + custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), + resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), + ) + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.simulate_security_health_analytics_custom_module( + parent='parent_value', + custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), + resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), + ) + + # Establish that 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].custom_config + mock_val = security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')) + assert arg == mock_val + arg = args[0].resource + mock_val = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.simulate_security_health_analytics_custom_module( + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(), + parent='parent_value', + custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), + resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateExternalSystemRequest, + dict, +]) +def test_update_external_system(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + ) + response = client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateExternalSystemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == 'name_value' + assert response.assignees == ['assignees_value'] + assert response.external_uid == 'external_uid_value' + assert response.status == 'status_value' + assert response.case_uri == 'case_uri_value' + assert response.case_priority == 'case_priority_value' + + +def test_update_external_system_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_external_system() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest() + + +def test_update_external_system_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateExternalSystemRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_external_system(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest( + ) + +def test_update_external_system_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_external_system in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc + request = {} + client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_external_system(request) + + # Establish that a new wrapper 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_external_system_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + )) + response = await client.update_external_system() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest() + +@pytest.mark.asyncio +async def test_update_external_system_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_external_system in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_external_system] = mock_object + + request = {} + await client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_external_system(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_external_system_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateExternalSystemRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + )) + response = await client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateExternalSystemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == 'name_value' + assert response.assignees == ['assignees_value'] + assert response.external_uid == 'external_uid_value' + assert response.status == 'status_value' + assert response.case_uri == 'case_uri_value' + assert response.case_priority == 'case_priority_value' + + +@pytest.mark.asyncio +async def test_update_external_system_async_from_dict(): + await test_update_external_system_async(request_type=dict) + + +def test_update_external_system_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateExternalSystemRequest() + + request.external_system.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value = gcs_external_system.ExternalSystem() + client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'external_system.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_external_system_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateExternalSystemRequest() + + request.external_system.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) + await client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'external_system.name=name_value', + ) in kw['metadata'] + + +def test_update_external_system_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_external_system( + external_system=gcs_external_system.ExternalSystem(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].external_system + mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error(): + client = SecurityCenterClient( + credentials=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_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_external_system_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_external_system( + external_system=gcs_external_system.ExternalSystem(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].external_system + mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_update_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateFindingRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.update_finding] = mock_rpc + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object + + request = {} + await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_update_finding_async_from_dict(): + await test_update_finding_async(request_type=dict) + + +def test_update_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +def test_update_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_finding( + finding=gcs_finding.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].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + + +def test_update_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_finding( + finding=gcs_finding.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].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateMuteConfigRequest, + dict, +]) +def test_update_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + ) + response = client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + + +def test_update_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest() + + +def test_update_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateMuteConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest( + ) + +def test_update_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + request = {} + client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + )) + response = await client.update_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest() + +@pytest.mark.asyncio +async def test_update_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_mute_config] = mock_object + + request = {} + await client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + )) + response = await client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + + +@pytest.mark.asyncio +async def test_update_mute_config_async_from_dict(): + await test_update_mute_config_async(request_type=dict) + + +def test_update_mute_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateMuteConfigRequest() + + request.mute_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.update_mute_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', + 'mute_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_mute_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateMuteConfigRequest() + + request.mute_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) + await client.update_mute_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', + 'mute_config.name=name_value', + ) in kw['metadata'] + + +def test_update_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_mute_config( + mute_config=gcs_mute_config.MuteConfig(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].mute_config + mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_mute_config( + mute_config=gcs_mute_config.MuteConfig(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].mute_config + mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, +]) +def test_update_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_update_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateNotificationConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest( + ) + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_update_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_notification_config] = mock_object + + request = {} + await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_update_notification_config_async_from_dict(): + await test_update_notification_config_async(request_type=dict) + + +def test_update_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.update_notification_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', + 'notification_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.update_notification_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', + 'notification_config.name=name_value', + ) in kw['metadata'] + + +def test_update_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_notification_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateOrganizationSettingsRequest, + dict, +]) +def test_update_organization_settings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_update_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateOrganizationSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_organization_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest( + ) + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_organization_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_organization_settings] = mock_rpc + request = {} + client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_organization_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_organization_settings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + +@pytest.mark.asyncio +async def test_update_organization_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_organization_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_organization_settings] = mock_object + + request = {} + await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_organization_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_update_organization_settings_async_from_dict(): + await test_update_organization_settings_async(request_type=dict) + + +def test_update_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = gcs_organization_settings.OrganizationSettings() + client.update_organization_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', + 'organization_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + await client.update_organization_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', + 'organization_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].organization_settings + mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') + assert arg == mock_val + + +def test_update_organization_settings_flattened_error(): + client = SecurityCenterClient( + credentials=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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].organization_settings + mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_update_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + ) + response = client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + + +def test_update_security_health_analytics_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + + +def test_update_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_health_analytics_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest( + ) + +def test_update_security_health_analytics_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_health_analytics_custom_module] = mock_rpc + request = {} + client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_health_analytics_custom_module(request) + + # Establish that a new wrapper 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_security_health_analytics_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + )) + response = await client.update_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + +@pytest.mark.asyncio +async def test_update_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_security_health_analytics_custom_module] = mock_object + + request = {} + await client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + )) + response = await client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + + +@pytest.mark.asyncio +async def test_update_security_health_analytics_custom_module_async_from_dict(): + await test_update_security_health_analytics_custom_module_async(request_type=dict) + + +def test_update_security_health_analytics_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + + request.security_health_analytics_custom_module.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_health_analytics_custom_module.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_health_analytics_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + + request.security_health_analytics_custom_module.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + await client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_health_analytics_custom_module.name=name_value', + ) in kw['metadata'] + + +def test_update_security_health_analytics_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_health_analytics_custom_module( + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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].security_health_analytics_custom_module + mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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_security_health_analytics_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_health_analytics_custom_module( + securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(), + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_security_health_analytics_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_health_analytics_custom_module( + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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].security_health_analytics_custom_module + mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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_security_health_analytics_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_security_health_analytics_custom_module( + securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(), + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSourceRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object + + request = {} + await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_source_async_from_dict(): + await test_update_source_async(request_type=dict) + + +def test_update_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +def test_update_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_source( + source=gcs_source.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].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + + +def test_update_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_source( + source=gcs_source.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].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + response = client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_security_marks_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + +def test_update_security_marks_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSecurityMarksRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( + ) + +def test_update_security_marks_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish that a new wrapper 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_security_marks_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + +@pytest.mark.asyncio +async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_marks in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object + + request = {} + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_security_marks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_security_marks_async_from_dict(): + await test_update_security_marks_async(request_type=dict) + + +def test_update_security_marks_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = gcs_security_marks.SecurityMarks() + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_marks_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +def test_update_security_marks_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].security_marks + mock_val = gcs_security_marks.SecurityMarks(name='name_value') + assert arg == mock_val + + +def test_update_security_marks_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].security_marks + mock_val = gcs_security_marks.SecurityMarks(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateBigQueryExportRequest, + dict, +]) +def test_create_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + response = client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +def test_create_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest() + + +def test_create_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateBigQueryExportRequest( + parent='parent_value', + big_query_export_id='big_query_export_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest( + parent='parent_value', + big_query_export_id='big_query_export_id_value', + ) + +def test_create_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + request = {} + client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_big_query_export(request) + + # Establish that a new wrapper 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_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.create_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_create_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_big_query_export] = mock_object + + request = {} + await client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +@pytest.mark.asyncio +async def test_create_big_query_export_async_from_dict(): + await test_create_big_query_export_async(request_type=dict) + + +def test_create_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateBigQueryExportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value = bigquery_export.BigQueryExport() + client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateBigQueryExportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + await client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_big_query_export( + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_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].big_query_export + mock_val = bigquery_export.BigQueryExport(name='name_value') + assert arg == mock_val + arg = args[0].big_query_export_id + mock_val = 'big_query_export_id_value' + assert arg == mock_val + + +def test_create_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_id_value', + ) + +@pytest.mark.asyncio +async def test_create_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_big_query_export( + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_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].big_query_export + mock_val = bigquery_export.BigQueryExport(name='name_value') + assert arg == mock_val + arg = args[0].big_query_export_id + mock_val = 'big_query_export_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteBigQueryExportRequest, + dict, +]) +def test_delete_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() + + +def test_delete_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteBigQueryExportRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest( + name='name_value', + ) + +def test_delete_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + request = {} + client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_big_query_export(request) + + # Establish that a new wrapper 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_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_delete_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_big_query_export] = mock_object + + request = {} + await client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteBigQueryExportRequest() + 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_big_query_export_async_from_dict(): + await test_delete_big_query_export_async(request_type=dict) + + +def test_delete_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value = None + client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__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_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__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_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateBigQueryExportRequest, + dict, +]) +def test_update_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + response = client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +def test_update_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() + + +def test_update_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateBigQueryExportRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest( + ) + +def test_update_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc + request = {} + client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_big_query_export(request) + + # Establish that a new wrapper 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_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.update_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_update_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_big_query_export] = mock_object + + request = {} + await client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +@pytest.mark.asyncio +async def test_update_big_query_export_async_from_dict(): + await test_update_big_query_export_async(request_type=dict) + + +def test_update_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateBigQueryExportRequest() + + request.big_query_export.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value = bigquery_export.BigQueryExport() + client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'big_query_export.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateBigQueryExportRequest() + + request.big_query_export.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + await client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'big_query_export.name=name_value', + ) in kw['metadata'] + + +def test_update_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_big_query_export( + big_query_export=bigquery_export.BigQueryExport(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].big_query_export + mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_big_query_export( + big_query_export=bigquery_export.BigQueryExport(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].big_query_export + mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListBigQueryExportsRequest, + dict, +]) +def test_list_big_query_exports(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListBigQueryExportsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_big_query_exports_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_big_query_exports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest() + + +def test_list_big_query_exports_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListBigQueryExportsRequest( + 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_big_query_exports), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_big_query_exports(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_big_query_exports_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_big_query_exports in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc + request = {} + client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_big_query_exports(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_big_query_exports_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_big_query_exports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest() + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_exports in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_big_query_exports] = mock_object + + request = {} + await client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_big_query_exports(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_big_query_exports_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListBigQueryExportsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListBigQueryExportsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_from_dict(): + await test_list_big_query_exports_async(request_type=dict) + + +def test_list_big_query_exports_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListBigQueryExportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_exports_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListBigQueryExportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) + await client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_exports_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_big_query_exports( + 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_big_query_exports_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_big_query_exports_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_big_query_exports( + 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_big_query_exports_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent='parent_value', + ) + + +def test_list_big_query_exports_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_big_query_exports(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, bigquery_export.BigQueryExport) + for i in results) +def test_list_big_query_exports_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + pages = list(client.list_big_query_exports(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_big_query_exports_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_big_query_exports(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, bigquery_export.BigQueryExport) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + 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_big_query_exports(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", [ + securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_create_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + ) + response = client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + + +def test_create_event_threat_detection_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + + +def test_create_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_event_threat_detection_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateEventThreatDetectionCustomModuleRequest( + parent='parent_value', + ) + +def test_create_event_threat_detection_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc + request = {} + client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_event_threat_detection_custom_module(request) + + # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + )) + response = await client.create_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + +@pytest.mark.asyncio +async def test_create_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_event_threat_detection_custom_module] = mock_object + + request = {} + await client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + )) + response = await client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + + +@pytest.mark.asyncio +async def test_create_event_threat_detection_custom_module_async_from_dict(): + await test_create_event_threat_detection_custom_module_async(request_type=dict) + + +def test_create_event_threat_detection_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_event_threat_detection_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + await client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_event_threat_detection_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_event_threat_detection_custom_module( + parent='parent_value', + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + ) + + # Establish that the 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].event_threat_detection_custom_module + mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value') + assert arg == mock_val + + +def test_create_event_threat_detection_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_event_threat_detection_custom_module( + securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(), + parent='parent_value', + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_event_threat_detection_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_event_threat_detection_custom_module( + parent='parent_value', + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + ) + + # Establish that 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].event_threat_detection_custom_module + mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_event_threat_detection_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_event_threat_detection_custom_module( + securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(), + parent='parent_value', + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_delete_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_event_threat_detection_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + + +def test_delete_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_event_threat_detection_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest( + name='name_value', + ) + +def test_delete_event_threat_detection_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc + request = {} + client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_event_threat_detection_custom_module(request) + + # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + +@pytest.mark.asyncio +async def test_delete_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_event_threat_detection_custom_module] = mock_object + + request = {} + await client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + 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_event_threat_detection_custom_module_async_from_dict(): + await test_delete_event_threat_detection_custom_module_async(request_type=dict) + + +def test_delete_event_threat_detection_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = None + client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_event_threat_detection_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_event_threat_detection_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__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_event_threat_detection_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_event_threat_detection_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_event_threat_detection_custom_module( + securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_event_threat_detection_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__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_event_threat_detection_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_event_threat_detection_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_event_threat_detection_custom_module( + securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_get_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + ) + response = client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + + +def test_get_event_threat_detection_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + + +def test_get_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_event_threat_detection_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEventThreatDetectionCustomModuleRequest( + name='name_value', + ) + +def test_get_event_threat_detection_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_event_threat_detection_custom_module] = mock_rpc + request = {} + client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_event_threat_detection_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + )) + response = await client.get_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + +@pytest.mark.asyncio +async def test_get_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_event_threat_detection_custom_module] = mock_object + + request = {} + await client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetEventThreatDetectionCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + )) + response = await client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + + +@pytest.mark.asyncio +async def test_get_event_threat_detection_custom_module_async_from_dict(): + await test_get_event_threat_detection_custom_module_async(request_type=dict) + + +def test_get_event_threat_detection_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_event_threat_detection_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + await client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_event_threat_detection_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_event_threat_detection_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_event_threat_detection_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_event_threat_detection_custom_module( + securitycenter_service.GetEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_event_threat_detection_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_event_threat_detection_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_event_threat_detection_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_event_threat_detection_custom_module( + securitycenter_service.GetEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, + dict, +]) +def test_list_descendant_event_threat_detection_custom_modules(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDescendantEventThreatDetectionCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_descendant_event_threat_detection_custom_modules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_descendant_event_threat_detection_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + + +def test_list_descendant_event_threat_detection_custom_modules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest( + 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_descendant_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_descendant_event_threat_detection_custom_modules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_descendant_event_threat_detection_custom_modules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_descendant_event_threat_detection_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_descendant_event_threat_detection_custom_modules] = mock_rpc + request = {} + client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_descendant_event_threat_detection_custom_modules_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_descendant_event_threat_detection_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + +@pytest.mark.asyncio +async def test_list_descendant_event_threat_detection_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_descendant_event_threat_detection_custom_modules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_descendant_event_threat_detection_custom_modules] = mock_object + + request = {} + await client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_descendant_event_threat_detection_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_descendant_event_threat_detection_custom_modules_async_from_dict(): + await test_list_descendant_event_threat_detection_custom_modules_async(request_type=dict) + + +def test_list_descendant_event_threat_detection_custom_modules_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_descendant_event_threat_detection_custom_modules_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse()) + await client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_descendant_event_threat_detection_custom_modules_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_descendant_event_threat_detection_custom_modules( + 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_descendant_event_threat_detection_custom_modules_flattened_error(): + client = SecurityCenterClient( + credentials=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_descendant_event_threat_detection_custom_modules( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_descendant_event_threat_detection_custom_modules_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_descendant_event_threat_detection_custom_modules( + 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_descendant_event_threat_detection_custom_modules_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_descendant_event_threat_detection_custom_modules( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_descendant_event_threat_detection_custom_modules_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_descendant_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + for i in results) +def test_list_descendant_event_threat_detection_custom_modules_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_descendant_event_threat_detection_custom_modules(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_descendant_event_threat_detection_custom_modules_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_descendant_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_descendant_event_threat_detection_custom_modules_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + 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_descendant_event_threat_detection_custom_modules(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", [ + securitycenter_service.ListEventThreatDetectionCustomModulesRequest, + dict, +]) +def test_list_event_threat_detection_custom_modules(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventThreatDetectionCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_event_threat_detection_custom_modules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_event_threat_detection_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + + +def test_list_event_threat_detection_custom_modules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest( + 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_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_event_threat_detection_custom_modules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEventThreatDetectionCustomModulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_event_threat_detection_custom_modules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_event_threat_detection_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_event_threat_detection_custom_modules] = mock_rpc + request = {} + client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_event_threat_detection_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_event_threat_detection_custom_modules_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_event_threat_detection_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + +@pytest.mark.asyncio +async def test_list_event_threat_detection_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_event_threat_detection_custom_modules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_event_threat_detection_custom_modules] = mock_object + + request = {} + await client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_event_threat_detection_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_event_threat_detection_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListEventThreatDetectionCustomModulesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventThreatDetectionCustomModulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_event_threat_detection_custom_modules_async_from_dict(): + await test_list_event_threat_detection_custom_modules_async(request_type=dict) + + +def test_list_event_threat_detection_custom_modules_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_event_threat_detection_custom_modules_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse()) + await client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_event_threat_detection_custom_modules_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_event_threat_detection_custom_modules( + 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_event_threat_detection_custom_modules_flattened_error(): + client = SecurityCenterClient( + credentials=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_event_threat_detection_custom_modules( + securitycenter_service.ListEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_event_threat_detection_custom_modules_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_event_threat_detection_custom_modules( + 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_event_threat_detection_custom_modules_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_event_threat_detection_custom_modules( + securitycenter_service.ListEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_event_threat_detection_custom_modules_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + for i in results) +def test_list_event_threat_detection_custom_modules_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_event_threat_detection_custom_modules(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_event_threat_detection_custom_modules_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_event_threat_detection_custom_modules_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + 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_event_threat_detection_custom_modules(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", [ + securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_update_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + ) + response = client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + + +def test_update_event_threat_detection_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + + +def test_update_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_event_threat_detection_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest( + ) + +def test_update_event_threat_detection_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_event_threat_detection_custom_module] = mock_rpc + request = {} + client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_event_threat_detection_custom_module(request) + + # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + )) + response = await client.update_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + +@pytest.mark.asyncio +async def test_update_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_event_threat_detection_custom_module] = mock_object + + request = {} + await client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + )) + response = await client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + + +@pytest.mark.asyncio +async def test_update_event_threat_detection_custom_module_async_from_dict(): + await test_update_event_threat_detection_custom_module_async(request_type=dict) + + +def test_update_event_threat_detection_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + + request.event_threat_detection_custom_module.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'event_threat_detection_custom_module.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_event_threat_detection_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + + request.event_threat_detection_custom_module.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + await client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'event_threat_detection_custom_module.name=name_value', + ) in kw['metadata'] + + +def test_update_event_threat_detection_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_event_threat_detection_custom_module( + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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].event_threat_detection_custom_module + mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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_event_threat_detection_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_event_threat_detection_custom_module( + securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(), + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_event_threat_detection_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_event_threat_detection_custom_module( + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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].event_threat_detection_custom_module + mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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_event_threat_detection_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_event_threat_detection_custom_module( + securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(), + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_validate_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( + ) + response = client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) + + +def test_validate_event_threat_detection_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.validate_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + + +def test_validate_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest( + parent='parent_value', + raw_text='raw_text_value', + type_='type__value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.validate_event_threat_detection_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest( + parent='parent_value', + raw_text='raw_text_value', + type_='type__value', + ) + +def test_validate_event_threat_detection_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc + request = {} + client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.validate_event_threat_detection_custom_module(request) + + # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( + )) + response = await client.validate_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + +@pytest.mark.asyncio +async def test_validate_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.validate_event_threat_detection_custom_module] = mock_object + + request = {} + await client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.validate_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_validate_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( + )) + response = await client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) + + +@pytest.mark.asyncio +async def test_validate_event_threat_detection_custom_module_async_from_dict(): + await test_validate_event_threat_detection_custom_module_async(request_type=dict) + + +def test_validate_event_threat_detection_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() + client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_validate_event_threat_detection_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse()) + await client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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", [ + securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_get_effective_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( + name='name_value', + enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + ) + response = client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.enablement_state == effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_effective_event_threat_detection_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_effective_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + + +def test_get_effective_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_effective_event_threat_detection_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest( + name='name_value', + ) + +def test_get_effective_event_threat_detection_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_effective_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_effective_event_threat_detection_custom_module] = mock_rpc + request = {} + client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_effective_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_effective_event_threat_detection_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( + name='name_value', + enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_effective_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + +@pytest.mark.asyncio +async def test_get_effective_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_effective_event_threat_detection_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_effective_event_threat_detection_custom_module] = mock_object + + request = {} + await client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_effective_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_effective_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( + name='name_value', + enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.enablement_state == effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_effective_event_threat_detection_custom_module_async_from_dict(): + await test_get_effective_event_threat_detection_custom_module_async(request_type=dict) + + +def test_get_effective_event_threat_detection_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_effective_event_threat_detection_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule()) + await client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_effective_event_threat_detection_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_effective_event_threat_detection_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_effective_event_threat_detection_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_effective_event_threat_detection_custom_module( + securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_effective_event_threat_detection_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_effective_event_threat_detection_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_effective_event_threat_detection_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_effective_event_threat_detection_custom_module( + securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, + dict, +]) +def test_list_effective_event_threat_detection_custom_modules(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEffectiveEventThreatDetectionCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_effective_event_threat_detection_custom_modules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_effective_event_threat_detection_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + + +def test_list_effective_event_threat_detection_custom_modules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest( + 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_effective_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_effective_event_threat_detection_custom_modules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_effective_event_threat_detection_custom_modules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_effective_event_threat_detection_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_effective_event_threat_detection_custom_modules] = mock_rpc + request = {} + client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_effective_event_threat_detection_custom_modules_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_effective_event_threat_detection_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + +@pytest.mark.asyncio +async def test_list_effective_event_threat_detection_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_effective_event_threat_detection_custom_modules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_effective_event_threat_detection_custom_modules] = mock_object + + request = {} + await client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_effective_event_threat_detection_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEffectiveEventThreatDetectionCustomModulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_effective_event_threat_detection_custom_modules_async_from_dict(): + await test_list_effective_event_threat_detection_custom_modules_async(request_type=dict) + + +def test_list_effective_event_threat_detection_custom_modules_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_effective_event_threat_detection_custom_modules_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse()) + await client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_effective_event_threat_detection_custom_modules_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_effective_event_threat_detection_custom_modules( + 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_effective_event_threat_detection_custom_modules_flattened_error(): + client = SecurityCenterClient( + credentials=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_effective_event_threat_detection_custom_modules( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_effective_event_threat_detection_custom_modules_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_effective_event_threat_detection_custom_modules( + 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_effective_event_threat_detection_custom_modules_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_effective_event_threat_detection_custom_modules( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_effective_event_threat_detection_custom_modules_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_effective_event_threat_detection_custom_modules(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, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) + for i in results) +def test_list_effective_event_threat_detection_custom_modules_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_effective_event_threat_detection_custom_modules(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_effective_event_threat_detection_custom_modules_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_effective_event_threat_detection_custom_modules(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, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_effective_event_threat_detection_custom_modules_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + ), + 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_effective_event_threat_detection_custom_modules(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", [ + securitycenter_service.BatchCreateResourceValueConfigsRequest, + dict, +]) +def test_batch_create_resource_value_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse( + ) + response = client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) + + +def test_batch_create_resource_value_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_create_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() + + +def test_batch_create_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.BatchCreateResourceValueConfigsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_create_resource_value_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest( + parent='parent_value', + ) + +def test_batch_create_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc + request = {} + client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_resource_value_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_batch_create_resource_value_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( + )) + response = await client.batch_create_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() + +@pytest.mark.asyncio +async def test_batch_create_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.batch_create_resource_value_configs] = mock_object + + request = {} + await client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.batch_create_resource_value_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( + )) + response = await client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) + + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_async_from_dict(): + await test_batch_create_resource_value_configs_async(request_type=dict) + + +def test_batch_create_resource_value_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + client.batch_create_resource_value_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_batch_create_resource_value_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) + await client.batch_create_resource_value_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_batch_create_resource_value_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_resource_value_configs( + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(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 + arg = args[0].requests + mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] + assert arg == mock_val + + +def test_batch_create_resource_value_configs_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], + ) + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_resource_value_configs( + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(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 + arg = args[0].requests + mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteResourceValueConfigRequest, + dict, +]) +def test_delete_resource_value_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() + + +def test_delete_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteResourceValueConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_resource_value_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest( + name='name_value', + ) + +def test_delete_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + request = {} + client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_resource_value_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_resource_value_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() + +@pytest.mark.asyncio +async def test_delete_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_resource_value_config] = mock_object + + request = {} + await client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_resource_value_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteResourceValueConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteResourceValueConfigRequest() + 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_resource_value_config_async_from_dict(): + await test_delete_resource_value_config_async(request_type=dict) + + +def test_delete_resource_value_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value = None + client.delete_resource_value_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_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_resource_value_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_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetResourceValueConfigRequest, + dict, +]) +def test_get_resource_value_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + response = client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +def test_get_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest() + + +def test_get_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetResourceValueConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_resource_value_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest( + name='name_value', + ) + +def test_get_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc + request = {} + client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_resource_value_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_resource_value_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest() + +@pytest.mark.asyncio +async def test_get_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_resource_value_config] = mock_object + + request = {} + await client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_resource_value_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetResourceValueConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +@pytest.mark.asyncio +async def test_get_resource_value_config_async_from_dict(): + await test_get_resource_value_config_async(request_type=dict) + + +def test_get_resource_value_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value = resource_value_config.ResourceValueConfig() + client.get_resource_value_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_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) + await client.get_resource_value_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_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_resource_value_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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_resource_value_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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListResourceValueConfigsRequest, + dict, +]) +def test_list_resource_value_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_resource_value_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() + + +def test_list_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListResourceValueConfigsRequest( + 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_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_resource_value_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc + request = {} + client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_value_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_resource_value_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() + +@pytest.mark.asyncio +async def test_list_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_resource_value_configs] = mock_object + + request = {} + await client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_resource_value_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListResourceValueConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async_from_dict(): + await test_list_resource_value_configs_async(request_type=dict) + + +def test_list_resource_value_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + client.list_resource_value_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_resource_value_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) + await client.list_resource_value_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_resource_value_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_resource_value_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_resource_value_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_resource_value_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_resource_value_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_resource_value_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent='parent_value', + ) + + +def test_list_resource_value_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_resource_value_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, resource_value_config.ResourceValueConfig) + for i in results) +def test_list_resource_value_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_resource_value_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_resource_value_configs_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_resource_value_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, resource_value_config.ResourceValueConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + 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_resource_value_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", [ + securitycenter_service.UpdateResourceValueConfigRequest, + dict, +]) +def test_update_resource_value_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + response = client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +def test_update_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() + + +def test_update_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateResourceValueConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_resource_value_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest( + ) + +def test_update_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + request = {} + client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_resource_value_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_resource_value_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.update_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() + +@pytest.mark.asyncio +async def test_update_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_resource_value_config] = mock_object + + request = {} + await client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_resource_value_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateResourceValueConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +@pytest.mark.asyncio +async def test_update_resource_value_config_async_from_dict(): + await test_update_resource_value_config_async(request_type=dict) + + +def test_update_resource_value_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateResourceValueConfigRequest() + + request.resource_value_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value = gcs_resource_value_config.ResourceValueConfig() + client.update_resource_value_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', + 'resource_value_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateResourceValueConfigRequest() + + request.resource_value_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) + await client.update_resource_value_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', + 'resource_value_config.name=name_value', + ) in kw['metadata'] + + +def test_update_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_resource_value_config( + resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config + mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_resource_value_config( + resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config + mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListValuedResourcesRequest, + dict, +]) +def test_list_valued_resources(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListValuedResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_valued_resources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_valued_resources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest() + + +def test_list_valued_resources_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListValuedResourcesRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_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_valued_resources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_valued_resources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_value', + order_by='order_by_value', + ) + +def test_list_valued_resources_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_valued_resources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc + request = {} + client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_valued_resources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_valued_resources_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_valued_resources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest() + +@pytest.mark.asyncio +async def test_list_valued_resources_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_valued_resources in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_valued_resources] = mock_object + + request = {} + await client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_valued_resources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_valued_resources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListValuedResourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListValuedResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_valued_resources_async_from_dict(): + await test_list_valued_resources_async(request_type=dict) + + +def test_list_valued_resources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListValuedResourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + call.return_value = securitycenter_service.ListValuedResourcesResponse() + client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_valued_resources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListValuedResourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) + await client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_valued_resources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_valued_resources( + 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_valued_resources_flattened_error(): + client = SecurityCenterClient( + credentials=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_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_valued_resources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_valued_resources( + 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_valued_resources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent='parent_value', + ) + + +def test_list_valued_resources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_valued_resources(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, valued_resource.ValuedResource) + for i in results) +def test_list_valued_resources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_valued_resources(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_valued_resources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_valued_resources(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, valued_resource.ValuedResource) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_valued_resources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + 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_valued_resources(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", [ + securitycenter_service.ListAttackPathsRequest, + dict, +]) +def test_list_attack_paths(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAttackPathsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_attack_paths_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_attack_paths() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest() + + +def test_list_attack_paths_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListAttackPathsRequest( + 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_attack_paths), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_attack_paths(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_attack_paths_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_attack_paths in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc + request = {} + client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_attack_paths(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_attack_paths_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_attack_paths() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest() + +@pytest.mark.asyncio +async def test_list_attack_paths_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_attack_paths in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_attack_paths] = mock_object + + request = {} + await client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_attack_paths(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_attack_paths_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAttackPathsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAttackPathsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_attack_paths_async_from_dict(): + await test_list_attack_paths_async(request_type=dict) + + +def test_list_attack_paths_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAttackPathsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + call.return_value = securitycenter_service.ListAttackPathsResponse() + client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_attack_paths_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAttackPathsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) + await client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_attack_paths_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_attack_paths( + 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_attack_paths_flattened_error(): + client = SecurityCenterClient( + credentials=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_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_attack_paths_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_attack_paths( + 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_attack_paths_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent='parent_value', + ) + + +def test_list_attack_paths_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_attack_paths(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, attack_path.AttackPath) + for i in results) +def test_list_attack_paths_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + pages = list(client.list_attack_paths(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_attack_paths_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_attack_paths(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, attack_path.AttackPath) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_attack_paths_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + 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_attack_paths(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", [ + securitycenter_service.BulkMuteFindingsRequest, + dict, +]) +def test_bulk_mute_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') + + # 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 + response = client.bulk_mute_findings(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_bulk_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc + + request = {} + client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_rest_required_fields(request_type=securitycenter_service.BulkMuteFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).bulk_mute_findings._get_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()).bulk_mute_findings._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 = SecurityCenterClient( + 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.bulk_mute_findings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_bulk_mute_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.bulk_mute_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_bulk_mute_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_bulk_mute_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_bulk_mute_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.BulkMuteFindingsRequest.pb(securitycenter_service.BulkMuteFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = securitycenter_service.BulkMuteFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.bulk_mute_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_bulk_mute_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BulkMuteFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.bulk_mute_findings(request) + + +def test_bulk_mute_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.bulk_mute_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/v1/{parent=organizations/*}/findings:bulkMute" % client.transport._host, args[1]) + + +def test_bulk_mute_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent='parent_value', + ) + + +def test_bulk_mute_findings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_create_security_health_analytics_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request_init["security_health_analytics_custom_module"] = {'name': 'name_value', 'display_name': 'display_name_value', 'enablement_state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_value', 'ancestor_module': 'ancestor_module_value', 'custom_config': {'predicate': {'expression': 'expression_value', 'title': 'title_value', 'description': 'description_value', 'location': 'location_value'}, 'custom_output': {'properties': [{'name': 'name_value', 'value_expression': {}}]}, 'resource_selector': {'resource_types': ['resource_types_value1', 'resource_types_value2']}, 'severity': 1, 'description': 'description_value', 'recommendation': 'recommendation_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 = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.meta.fields["security_health_analytics_custom_module"] + + 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["security_health_analytics_custom_module"].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["security_health_analytics_custom_module"][field])): + del request_init["security_health_analytics_custom_module"][field][i][subfield] + else: + del request_init["security_health_analytics_custom_module"][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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) + 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_security_health_analytics_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + +def test_create_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc + + request = {} + client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_security_health_analytics_custom_module(request) + + # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_security_health_analytics_custom_module._get_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_security_health_analytics_custom_module._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) + 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_security_health_analytics_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_security_health_analytics_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_security_health_analytics_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "securityHealthAnalyticsCustomModule", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_security_health_analytics_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_security_health_analytics_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_security_health_analytics_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.to_json(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + client.create_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_security_health_analytics_custom_module(request) + + +def test_create_security_health_analytics_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(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_security_health_analytics_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules" % client.transport._host, args[1]) + + +def test_create_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_health_analytics_custom_module( + securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(), + parent='parent_value', + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + ) + + +def test_create_security_health_analytics_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.CreateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_source(request) + + +def test_create_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_create_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +def test_create_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request_init["finding"] = {'name': 'name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_value', 'mute': 1, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.create_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.create_finding] = mock_rpc + + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["finding_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 "findingId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "findingId" in jsonified_request + assert jsonified_request["findingId"] == request_init["finding_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["findingId"] = 'finding_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request + assert jsonified_request["findingId"] == 'finding_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.create_finding(request) + + expected_params = [ + ( + "findingId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.CreateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_finding(request) + + +def test_create_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(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 = gcs_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.create_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/v1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) + + +def test_create_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_create_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateMuteConfigRequest, + dict, +]) +def test_create_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["mute_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_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 = securitycenter_service.CreateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): + del request_init["mute_config"][field][i][subfield] + else: + del request_init["mute_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 = gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + +def test_create_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + + request = {} + client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.CreateMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["mute_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 "muteConfigId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "muteConfigId" in jsonified_request + assert jsonified_request["muteConfigId"] == request_init["mute_config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["muteConfigId"] = 'mute_config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("mute_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 "muteConfigId" in jsonified_request + assert jsonified_request["muteConfigId"] == 'mute_config_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + expected_params = [ + ( + "muteConfigId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("muteConfigId", )) & set(("parent", "muteConfig", "muteConfigId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_mute_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_mute_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateMuteConfigRequest.pb(securitycenter_service.CreateMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) + + request = securitycenter_service.CreateMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_mute_config.MuteConfig() + + client.create_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_mute_config(request) + + +def test_create_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_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 = gcs_mute_config.MuteConfig.pb(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_mute_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=organizations/*}/muteConfigs" % client.transport._host, args[1]) + + +def test_create_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_id_value', + ) + + +def test_create_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateNotificationConfigRequest, + dict, +]) +def test_create_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["notification_config"] = {'name': 'name_value', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.CreateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.CreateNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["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 "configId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "configId" in jsonified_request + assert jsonified_request["configId"] == request_init["config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["configId"] = 'config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("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 "configId" in jsonified_request + assert jsonified_request["configId"] == 'config_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ( + "configId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("configId", )) & set(("parent", "configId", "notificationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateNotificationConfigRequest.pb(securitycenter_service.CreateNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) + + request = securitycenter_service.CreateNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.create_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_notification_config(request) + + +def test_create_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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=organizations/*}/notificationConfigs" % client.transport._host, args[1]) + + +def test_create_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + +def test_create_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteMuteConfigRequest, + dict, +]) +def test_delete_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/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 = 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + + request = {} + client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.DeleteMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( + 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_mute_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_mute_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteMuteConfigRequest.pb(securitycenter_service.DeleteMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_mute_config(request) + + +def test_delete_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/muteConfigs/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_mute_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=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name='name_value', + ) + + +def test_delete_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, +]) +def test_delete_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/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 = 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_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.DeleteNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_notification_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteNotificationConfigRequest.pb(securitycenter_service.DeleteNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_notification_config(request) + + +def test_delete_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/notificationConfigs/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_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=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +def test_delete_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_delete_security_health_analytics_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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 = 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_security_health_analytics_custom_module(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc + + request = {} + client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_security_health_analytics_custom_module(request) + + # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + 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_security_health_analytics_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_security_health_analytics_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_security_health_analytics_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_security_health_analytics_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_security_health_analytics_custom_module") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_security_health_analytics_custom_module(request) + + +def test_delete_security_health_analytics_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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_security_health_analytics_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings/customModules/*}" % client.transport._host, args[1]) + + +def test_delete_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_health_analytics_custom_module( + securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + + +def test_delete_security_health_analytics_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSimulationRequest, + dict, +]) +def test_get_simulation_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = simulation.Simulation.pb(return_value) + 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_simulation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == 'name_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + +def test_get_simulation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_simulation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc + + request = {} + client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_simulation(request) + + # Establish 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_simulation_rest_required_fields(request_type=securitycenter_service.GetSimulationRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_simulation._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_simulation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = simulation.Simulation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = simulation.Simulation.pb(return_value) + 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_simulation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_simulation_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_simulation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_simulation_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_simulation") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_simulation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSimulationRequest.pb(securitycenter_service.GetSimulationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = simulation.Simulation.to_json(simulation.Simulation()) + + request = securitycenter_service.GetSimulationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = simulation.Simulation() + + client.get_simulation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_simulation_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSimulationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_simulation(request) + + +def test_get_simulation_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = simulation.Simulation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation.pb(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_simulation(**mock_args) + + # Establish that the underlying call 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=organizations/*/simulations/*}" % client.transport._host, args[1]) + + +def test_get_simulation_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_simulation( + securitycenter_service.GetSimulationRequest(), + name='name_value', + ) + + +def test_get_simulation_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetValuedResourceRequest, + dict, +]) +def test_get_valued_resource_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = valued_resource.ValuedResource.pb(return_value) + 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_valued_resource(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == 'name_value' + assert response.resource == 'resource_value' + assert response.resource_type == 'resource_type_value' + assert response.display_name == 'display_name_value' + assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + +def test_get_valued_resource_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_valued_resource in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc + + request = {} + client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_valued_resource(request) + + # Establish 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_valued_resource_rest_required_fields(request_type=securitycenter_service.GetValuedResourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_valued_resource._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_valued_resource._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = valued_resource.ValuedResource() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = valued_resource.ValuedResource.pb(return_value) + 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_valued_resource(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_valued_resource_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_valued_resource._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_valued_resource_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_valued_resource") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_valued_resource") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetValuedResourceRequest.pb(securitycenter_service.GetValuedResourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = valued_resource.ValuedResource.to_json(valued_resource.ValuedResource()) + + request = securitycenter_service.GetValuedResourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = valued_resource.ValuedResource() + + client.get_valued_resource(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_valued_resource_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetValuedResourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_valued_resource(request) + + +def test_get_valued_resource_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = valued_resource.ValuedResource() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource.pb(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_valued_resource(**mock_args) + + # Establish that the underlying call 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=organizations/*/simulations/*/valuedResources/*}" % client.transport._host, args[1]) + + +def test_get_valued_resource_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name='name_value', + ) + + +def test_get_valued_resource_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetBigQueryExportRequest, + dict, +]) +def test_get_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/bigQueryExports/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 = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + +def test_get_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc + + request = {} + client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.GetBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_big_query_export") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_big_query_export") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetBigQueryExportRequest.pb(securitycenter_service.GetBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) + + request = securitycenter_service.GetBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.get_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/bigQueryExports/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_big_query_export(request) + + +def test_get_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/bigQueryExports/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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) + + # Establish that the underlying call 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=organizations/*/bigQueryExports/*}" % client.transport._host, args[1]) + + +def test_get_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name='name_value', + ) + + +def test_get_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.get_iam_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/v1/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetMuteConfigRequest, + dict, +]) +def test_get_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + +def test_get_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_mute_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_mute_config] = mock_rpc + + request = {} + client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.GetMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = mute_config.MuteConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_mute_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_mute_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetMuteConfigRequest.pb(securitycenter_service.GetMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = mute_config.MuteConfig.to_json(mute_config.MuteConfig()) + + request = securitycenter_service.GetMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = mute_config.MuteConfig() + + client.get_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_mute_config(request) + + +def test_get_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig.pb(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_mute_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=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) + + +def test_get_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name='name_value', + ) + + +def test_get_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetNotificationConfigRequest, + dict, +]) +def test_get_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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_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_notification_config] = mock_rpc + + request = {} + client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.GetNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetNotificationConfigRequest.pb(securitycenter_service.GetNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = notification_config.NotificationConfig.to_json(notification_config.NotificationConfig()) + + request = securitycenter_service.GetNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = notification_config.NotificationConfig() + + client.get_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_notification_config(request) + + +def test_get_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig.pb(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_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=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_get_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +def test_get_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetOrganizationSettingsRequest, + dict, +]) +def test_get_organization_settings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/organizationSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_organization_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_organization_settings] = mock_rpc + + request = {} + client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.GetOrganizationSettingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_organization_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_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_organization_settings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_organization_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_organization_settings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_organization_settings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_organization_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetOrganizationSettingsRequest.pb(securitycenter_service.GetOrganizationSettingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = organization_settings.OrganizationSettings.to_json(organization_settings.OrganizationSettings()) + + request = securitycenter_service.GetOrganizationSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = organization_settings.OrganizationSettings() + + client.get_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/organizationSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_organization_settings(request) + + +def test_get_organization_settings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/organizationSettings'} + + # get truthy value for each flattened field + mock_args = dict( + 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 = organization_settings.OrganizationSettings.pb(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_organization_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/v1/{name=organizations/*/organizationSettings}" % client.transport._host, args[1]) + + +def test_get_organization_settings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +def test_get_organization_settings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_get_effective_security_health_analytics_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/effectiveCustomModules/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 = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( + name='name_value', + enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + display_name='display_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(return_value) + 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_effective_security_health_analytics_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.enablement_state == effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.display_name == 'display_name_value' + +def test_get_effective_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_effective_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_effective_security_health_analytics_custom_module] = mock_rpc + + request = {} + client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_effective_security_health_analytics_custom_module(request) + + # Establish 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_effective_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_effective_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_effective_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(return_value) + 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_effective_security_health_analytics_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_effective_security_health_analytics_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_effective_security_health_analytics_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_effective_security_health_analytics_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_effective_security_health_analytics_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_effective_security_health_analytics_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.to_json(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule()) + + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + + client.get_effective_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_effective_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/effectiveCustomModules/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_effective_security_health_analytics_custom_module(request) + + +def test_get_effective_security_health_analytics_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/effectiveCustomModules/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 = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(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_effective_security_health_analytics_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}" % client.transport._host, args[1]) + + +def test_get_effective_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_effective_security_health_analytics_custom_module( + securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + + +def test_get_effective_security_health_analytics_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_get_security_health_analytics_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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 = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) + 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_security_health_analytics_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + +def test_get_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_security_health_analytics_custom_module] = mock_rpc + + request = {} + client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_security_health_analytics_custom_module(request) + + # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) + 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_security_health_analytics_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_security_health_analytics_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_security_health_analytics_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_security_health_analytics_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_security_health_analytics_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_security_health_analytics_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.to_json(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + client.get_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_security_health_analytics_custom_module(request) + + +def test_get_security_health_analytics_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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 = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(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_security_health_analytics_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings/customModules/*}" % client.transport._host, args[1]) + + +def test_get_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_health_analytics_custom_module( + securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + + +def test_get_security_health_analytics_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/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 = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = source.Source.to_json(source.Source()) + + request = securitycenter_service.GetSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = source.Source() + + client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_source(request) + + +def test_get_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v1/{name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_get_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +def test_get_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupAssetsRequest, + dict, +]) +def test_group_assets_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_group_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc + + request = {} + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_group_assets_rest_required_fields(request_type=securitycenter_service.GroupAssetsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_assets_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_assets_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_assets") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupAssetsRequest.pb(securitycenter_service.GroupAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupAssetsResponse.to_json(securitycenter_service.GroupAssetsResponse()) + + request = securitycenter_service.GroupAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupAssetsResponse() + + client.group_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_assets(request) + + +def test_group_assets_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupAssetsResponse.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': 'organizations/sample1'} + + pager = client.group_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_findings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) + + request = securitycenter_service.GroupFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupFindingsResponse() + + client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_findings(request) + + +def test_group_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + group_by='group_by_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v1/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) + + +def test_group_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} + + pager = client.group_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_findings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListAssetsRequest, + dict, +]) +def test_list_assets_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListAssetsResponse.pb(return_value) + 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_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_list_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish 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_assets_rest_required_fields(request_type=securitycenter_service.ListAssetsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_assets._get_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_assets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) + jsonified_request.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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListAssetsResponse.pb(return_value) + 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_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_assets_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_assets_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_assets") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListAssetsRequest.pb(securitycenter_service.ListAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListAssetsResponse.to_json(securitycenter_service.ListAssetsResponse()) + + request = securitycenter_service.ListAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListAssetsResponse() + + client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_assets(request) + + +def test_list_assets_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListAssetsResponse.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': 'organizations/sample1'} + + pager = client.list_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) + + pages = list(client.list_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, + dict, +]) +def test_list_descendant_security_health_analytics_custom_modules_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) + 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_descendant_security_health_analytics_custom_modules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_descendant_security_health_analytics_custom_modules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_descendant_security_health_analytics_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_descendant_security_health_analytics_custom_modules] = mock_rpc + + request = {} + client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish 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_descendant_security_health_analytics_custom_modules_rest_required_fields(request_type=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_descendant_security_health_analytics_custom_modules._get_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_descendant_security_health_analytics_custom_modules._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) + 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_descendant_security_health_analytics_custom_modules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_descendant_security_health_analytics_custom_modules_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_descendant_security_health_analytics_custom_modules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_descendant_security_health_analytics_custom_modules_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_descendant_security_health_analytics_custom_modules") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_descendant_security_health_analytics_custom_modules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.pb(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.to_json(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse()) + + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + + client.list_descendant_security_health_analytics_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_descendant_security_health_analytics_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_descendant_security_health_analytics_custom_modules(request) + + +def test_list_descendant_security_health_analytics_custom_modules_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + + # 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 = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(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_descendant_security_health_analytics_custom_modules(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules:listDescendant" % client.transport._host, args[1]) + + +def test_list_descendant_security_health_analytics_custom_modules_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_descendant_security_health_analytics_custom_modules( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_descendant_security_health_analytics_custom_modules_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.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': 'organizations/sample1/securityHealthAnalyticsSettings'} + + pager = client.list_descendant_security_health_analytics_custom_modules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + for i in results) + + pages = list(client.list_descendant_security_health_analytics_custom_modules(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.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' + assert response.total_size == 1086 + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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=securitycenter_service.ListFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) + jsonified_request.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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.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 = securitycenter_service.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 = [ + ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) + + request = securitycenter_service.ListFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListFindingsResponse() + + client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_findings(request) + + +def test_list_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} + + pager = client.list_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) + 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 + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListMuteConfigsRequest, + dict, +]) +def test_list_mute_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) + 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_mute_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_mute_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_mute_configs] = mock_rpc + + request = {} + client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_mute_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_mute_configs_rest_required_fields(request_type=securitycenter_service.ListMuteConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListMuteConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) + 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_mute_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_mute_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_mute_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_mute_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_mute_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_mute_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListMuteConfigsRequest.pb(securitycenter_service.ListMuteConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListMuteConfigsResponse.to_json(securitycenter_service.ListMuteConfigsResponse()) + + request = securitycenter_service.ListMuteConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListMuteConfigsResponse() + + client.list_mute_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_mute_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListMuteConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_mute_configs(request) + + +def test_list_mute_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListMuteConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse.pb(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_mute_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=organizations/*}/muteConfigs" % client.transport._host, args[1]) + + +def test_list_mute_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent='parent_value', + ) + + +def test_list_mute_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListMuteConfigsResponse.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': 'organizations/sample1'} + + pager = client.list_mute_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, mute_config.MuteConfig) + for i in results) + + pages = list(client.list_mute_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListNotificationConfigsRequest, + dict, +]) +def test_list_notification_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) + 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_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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_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_notification_configs] = mock_rpc + + request = {} + client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_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_notification_configs_rest_required_fields(request_type=securitycenter_service.ListNotificationConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListNotificationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) + 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_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_notification_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_notification_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_notification_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_notification_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_notification_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListNotificationConfigsRequest.pb(securitycenter_service.ListNotificationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListNotificationConfigsResponse.to_json(securitycenter_service.ListNotificationConfigsResponse()) + + request = securitycenter_service.ListNotificationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListNotificationConfigsResponse() + + client.list_notification_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_notification_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_notification_configs(request) + + +def test_list_notification_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListNotificationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse.pb(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_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=organizations/*}/notificationConfigs" % client.transport._host, args[1]) + + +def test_list_notification_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListNotificationConfigsResponse.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': 'organizations/sample1'} + + pager = client.list_notification_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, notification_config.NotificationConfig) + for i in results) + + pages = list(client.list_notification_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, + dict, +]) +def test_list_effective_security_health_analytics_custom_modules_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) + 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_effective_security_health_analytics_custom_modules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_effective_security_health_analytics_custom_modules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_effective_security_health_analytics_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_effective_security_health_analytics_custom_modules] = mock_rpc + + request = {} + client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_effective_security_health_analytics_custom_modules(request) + + # Establish 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_effective_security_health_analytics_custom_modules_rest_required_fields(request_type=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_effective_security_health_analytics_custom_modules._get_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_effective_security_health_analytics_custom_modules._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) + 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_effective_security_health_analytics_custom_modules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_effective_security_health_analytics_custom_modules_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_effective_security_health_analytics_custom_modules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_effective_security_health_analytics_custom_modules_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_effective_security_health_analytics_custom_modules") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_effective_security_health_analytics_custom_modules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.pb(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.to_json(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse()) + + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + + client.list_effective_security_health_analytics_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_effective_security_health_analytics_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_effective_security_health_analytics_custom_modules(request) + + +def test_list_effective_security_health_analytics_custom_modules_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + + # 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 = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(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_effective_security_health_analytics_custom_modules(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/effectiveCustomModules" % client.transport._host, args[1]) + + +def test_list_effective_security_health_analytics_custom_modules_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_effective_security_health_analytics_custom_modules( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_effective_security_health_analytics_custom_modules_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.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': 'organizations/sample1/securityHealthAnalyticsSettings'} + + pager = client.list_effective_security_health_analytics_custom_modules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) + for i in results) + + pages = list(client.list_effective_security_health_analytics_custom_modules(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, + dict, +]) +def test_list_security_health_analytics_custom_modules_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) + 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_security_health_analytics_custom_modules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecurityHealthAnalyticsCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_security_health_analytics_custom_modules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_security_health_analytics_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_security_health_analytics_custom_modules] = mock_rpc + + request = {} + client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_security_health_analytics_custom_modules(request) + + # Establish 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_security_health_analytics_custom_modules_rest_required_fields(request_type=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_security_health_analytics_custom_modules._get_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_security_health_analytics_custom_modules._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) + 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_security_health_analytics_custom_modules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_security_health_analytics_custom_modules_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_security_health_analytics_custom_modules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_security_health_analytics_custom_modules_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_security_health_analytics_custom_modules") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_security_health_analytics_custom_modules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.pb(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.to_json(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse()) + + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + + client.list_security_health_analytics_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_security_health_analytics_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_security_health_analytics_custom_modules(request) + + +def test_list_security_health_analytics_custom_modules_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + + # 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 = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(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_security_health_analytics_custom_modules(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules" % client.transport._host, args[1]) + + +def test_list_security_health_analytics_custom_modules_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_health_analytics_custom_modules( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_security_health_analytics_custom_modules_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.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': 'organizations/sample1/securityHealthAnalyticsSettings'} + + pager = client.list_security_health_analytics_custom_modules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + for i in results) + + pages = list(client.list_security_health_analytics_custom_modules(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_sources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_sources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) + + request = securitycenter_service.ListSourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListSourcesResponse() + + client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_sources(request) + + +def test_list_sources_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v1/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_list_sources_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} + + pager = client.list_sources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, source.Source) + for i in results) + + pages = list(client.list_sources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.RunAssetDiscoveryRequest, + dict, +]) +def test_run_asset_discovery_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') + + # 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 + response = client.run_asset_discovery(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_run_asset_discovery_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_asset_discovery in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc + + request = {} + client.run_asset_discovery(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.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_run_asset_discovery_rest_required_fields(request_type=securitycenter_service.RunAssetDiscoveryRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_asset_discovery._get_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()).run_asset_discovery._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 = SecurityCenterClient( + 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.run_asset_discovery(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_run_asset_discovery_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.run_asset_discovery._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_asset_discovery_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_run_asset_discovery") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_run_asset_discovery") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.RunAssetDiscoveryRequest.pb(securitycenter_service.RunAssetDiscoveryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = securitycenter_service.RunAssetDiscoveryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.run_asset_discovery(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_asset_discovery_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.run_asset_discovery(request) + + +def test_run_asset_discovery_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.run_asset_discovery(**mock_args) + + # Establish that the underlying call 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=organizations/*}/assets:runDiscovery" % client.transport._host, args[1]) + + +def test_run_asset_discovery_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +def test_run_asset_discovery_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # 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 + response = client.set_finding_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( + 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': "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 = 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.set_finding_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_finding_state_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_finding_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "state", "startTime", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_finding_state_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetFindingStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_finding_state(request) + + +def test_set_finding_state_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + mock_args.update(sample_request) + + # 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.set_finding_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/v1/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) + + +def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +def test_set_finding_state_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetMuteRequest, + dict, +]) +def test_set_mute_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # 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 + response = client.set_mute(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_set_mute_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_mute in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc + + request = {} + client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_mute(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_set_mute_rest_required_fields(request_type=securitycenter_service.SetMuteRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + 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': "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 = 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.set_mute(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_mute_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_mute._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "mute", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_mute_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_mute") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_mute") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetMuteRequest.pb(securitycenter_service.SetMuteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetMuteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_mute(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_mute_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetMuteRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_mute(request) + + +def test_set_mute_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + mock_args.update(sample_request) + + # 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.set_mute(**mock_args) + + # Establish that the underlying call 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=organizations/*/sources/*/findings/*}:setMute" % client.transport._host, args[1]) + + +def test_set_mute_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_mute( + securitycenter_service.SetMuteRequest(), + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + +def test_set_mute_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.set_iam_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/v1/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # 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 + response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_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.test_iam_permissions(**mock_args) + + # Establish that the underlying call 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/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_simulate_security_health_analytics_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.simulate_security_health_analytics_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) + +def test_simulate_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.simulate_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.simulate_security_health_analytics_custom_module] = mock_rpc + + request = {} + client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.simulate_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_simulate_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).simulate_security_health_analytics_custom_module._get_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()).simulate_security_health_analytics_custom_module._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.simulate_security_health_analytics_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_simulate_security_health_analytics_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.simulate_security_health_analytics_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "customConfig", "resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_simulate_security_health_analytics_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_simulate_security_health_analytics_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_simulate_security_health_analytics_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.to_json(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse()) + + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + + client.simulate_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_simulate_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.simulate_security_health_analytics_custom_module(request) + + +def test_simulate_security_health_analytics_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), + resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(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.simulate_security_health_analytics_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules:simulate" % client.transport._host, args[1]) + + +def test_simulate_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.simulate_security_health_analytics_custom_module( + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(), + parent='parent_value', + custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), + resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), + ) + + +def test_simulate_security_health_analytics_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateExternalSystemRequest, + dict, +]) +def test_update_external_system_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} + request_init["external_system"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4', 'assignees': ['assignees_value1', 'assignees_value2'], 'external_uid': 'external_uid_value', 'status': 'status_value', 'external_system_update_time': {'seconds': 751, 'nanos': 543}, 'case_uri': 'case_uri_value', 'case_priority': 'case_priority_value', 'case_sla': {}, 'case_create_time': {}, 'case_close_time': {}, 'ticket_info': {'id': 'id_value', 'assignee': 'assignee_value', 'description': 'description_value', 'uri': 'uri_value', 'status': 'status_value', 'update_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 = securitycenter_service.UpdateExternalSystemRequest.meta.fields["external_system"] + + 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["external_system"].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["external_system"][field])): + del request_init["external_system"][field][i][subfield] + else: + del request_init["external_system"][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 = gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_external_system.ExternalSystem.pb(return_value) + 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_external_system(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == 'name_value' + assert response.assignees == ['assignees_value'] + assert response.external_uid == 'external_uid_value' + assert response.status == 'status_value' + assert response.case_uri == 'case_uri_value' + assert response.case_priority == 'case_priority_value' + +def test_update_external_system_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_external_system in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc + + request = {} + client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_external_system(request) + + # Establish 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_external_system_rest_required_fields(request_type=securitycenter_service.UpdateExternalSystemRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_external_system._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_external_system._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_external_system.ExternalSystem() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_external_system.ExternalSystem.pb(return_value) + 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_external_system(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_external_system_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_external_system._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("externalSystem", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_external_system_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_external_system") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_external_system") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateExternalSystemRequest.pb(securitycenter_service.UpdateExternalSystemRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_external_system.ExternalSystem.to_json(gcs_external_system.ExternalSystem()) + + request = securitycenter_service.UpdateExternalSystemRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_external_system.ExternalSystem() + + client.update_external_system(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_external_system_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateExternalSystemRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_external_system(request) + + +def test_update_external_system_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_external_system.ExternalSystem() + + # get arguments that satisfy an http rule for this method + sample_request = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + external_system=gcs_external_system.ExternalSystem(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 = gcs_external_system.ExternalSystem.pb(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_external_system(**mock_args) + + # Establish that the underlying call 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/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}" % client.transport._host, args[1]) + + +def test_update_external_system_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_external_system_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_value', 'mute': 1, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.update_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.update_finding] = mock_rpc + + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_finding._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_finding._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.update_finding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.UpdateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_finding(request) + + +def test_update_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + finding=gcs_finding.Finding(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 = gcs_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.update_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/v1/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) + + +def test_update_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_update_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateMuteConfigRequest, + dict, +]) +def test_update_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} + request_init["mute_config"] = {'name': 'organizations/sample1/muteConfigs/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_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 = securitycenter_service.UpdateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): + del request_init["mute_config"][field][i][subfield] + else: + del request_init["mute_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 = gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + +def test_update_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + + request = {} + client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.UpdateMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("muteConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_mute_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_mute_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateMuteConfigRequest.pb(securitycenter_service.UpdateMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) + + request = securitycenter_service.UpdateMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_mute_config.MuteConfig() + + client.update_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_mute_config(request) + + +def test_update_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + mute_config=gcs_mute_config.MuteConfig(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 = gcs_mute_config.MuteConfig.pb(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_mute_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/{mute_config.name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) + + +def test_update_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, +]) +def test_update_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} + request_init["notification_config"] = {'name': 'organizations/sample1/notificationConfigs/sample2', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.UpdateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.UpdateNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("notificationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateNotificationConfigRequest.pb(securitycenter_service.UpdateNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) + + request = securitycenter_service.UpdateNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.update_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_notification_config(request) + + +def test_update_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/{notification_config.name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_update_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateOrganizationSettingsRequest, + dict, +]) +def test_update_organization_settings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + request_init["organization_settings"] = {'name': 'organizations/sample1/organizationSettings', 'enable_asset_discovery': True, 'asset_discovery_config': {'project_ids': ['project_ids_value1', 'project_ids_value2'], 'inclusion_mode': 1, 'folder_ids': ['folder_ids_value1', 'folder_ids_value2']}} + # The version of a generated dependency at test runtime may differ from the version used 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 = securitycenter_service.UpdateOrganizationSettingsRequest.meta.fields["organization_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["organization_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["organization_settings"][field])): + del request_init["organization_settings"][field][i][subfield] + else: + del request_init["organization_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 = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_organization_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_organization_settings] = mock_rpc + + request = {} + client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_organization_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_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_organization_settings.OrganizationSettings() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_organization_settings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_organization_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("organizationSettings", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_organization_settings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_organization_settings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_organization_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateOrganizationSettingsRequest.pb(securitycenter_service.UpdateOrganizationSettingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_organization_settings.OrganizationSettings.to_json(gcs_organization_settings.OrganizationSettings()) + + request = securitycenter_service.UpdateOrganizationSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_organization_settings.OrganizationSettings() + + client.update_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_organization_settings(request) + + +def test_update_organization_settings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_organization_settings.OrganizationSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + organization_settings=gcs_organization_settings.OrganizationSettings(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 = gcs_organization_settings.OrganizationSettings.pb(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_organization_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/v1/{organization_settings.name=organizations/*/organizationSettings}" % client.transport._host, args[1]) + + +def test_update_organization_settings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +def test_update_organization_settings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_update_security_health_analytics_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'security_health_analytics_custom_module': {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'}} + request_init["security_health_analytics_custom_module"] = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2', 'display_name': 'display_name_value', 'enablement_state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_value', 'ancestor_module': 'ancestor_module_value', 'custom_config': {'predicate': {'expression': 'expression_value', 'title': 'title_value', 'description': 'description_value', 'location': 'location_value'}, 'custom_output': {'properties': [{'name': 'name_value', 'value_expression': {}}]}, 'resource_selector': {'resource_types': ['resource_types_value1', 'resource_types_value2']}, 'severity': 1, 'description': 'description_value', 'recommendation': 'recommendation_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 = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.meta.fields["security_health_analytics_custom_module"] + + 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["security_health_analytics_custom_module"].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["security_health_analytics_custom_module"][field])): + del request_init["security_health_analytics_custom_module"][field][i][subfield] + else: + del request_init["security_health_analytics_custom_module"][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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) + 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_security_health_analytics_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + +def test_update_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_health_analytics_custom_module] = mock_rpc + + request = {} + client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_health_analytics_custom_module(request) + + # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_security_health_analytics_custom_module._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_security_health_analytics_custom_module._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) + 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_security_health_analytics_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_security_health_analytics_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_security_health_analytics_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("securityHealthAnalyticsCustomModule", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_security_health_analytics_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_health_analytics_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_health_analytics_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.to_json(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + client.update_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'security_health_analytics_custom_module': {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_security_health_analytics_custom_module(request) + + +def test_update_security_health_analytics_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'security_health_analytics_custom_module': {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(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_security_health_analytics_custom_module(**mock_args) + + # Establish that the underlying call 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/{security_health_analytics_custom_module.name=organizations/*/securityHealthAnalyticsSettings/customModules/*}" % client.transport._host, args[1]) + + +def test_update_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_health_analytics_custom_module( + securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(), + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_security_health_analytics_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.UpdateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_source(request) + + +def test_update_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_update_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + + +def test_update_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + request_init["security_marks"] = {'name': 'organizations/sample1/assets/sample2/securityMarks', 'marks': {}, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] + + 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["security_marks"].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["security_marks"][field])): + del request_init["security_marks"][field][i][subfield] + else: + del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + +def test_update_security_marks_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_security_marks._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_security_marks._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("start_time", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_security_marks_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_security_marks._get_unset_required_fields({}) + assert set(unset_fields) == (set(("startTime", "updateMask", )) & set(("securityMarks", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_security_marks_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) + + request = securitycenter_service.UpdateSecurityMarksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_security_marks.SecurityMarks() + + client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_security_marks(request) + + +def test_update_security_marks_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + + # get arguments that satisfy an http rule for this method + sample_request = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + + # get truthy value for each flattened field + mock_args = dict( + security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) + + # Establish that the underlying call 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/{security_marks.name=organizations/*/assets/*/securityMarks}" % client.transport._host, args[1]) + + +def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + +def test_update_security_marks_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateBigQueryExportRequest, + dict, +]) +def test_create_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["big_query_export"] = {'name': 'name_value', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.CreateBigQueryExportRequest.meta.fields["big_query_export"] + + 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["big_query_export"].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["big_query_export"][field])): + del request_init["big_query_export"][field][i][subfield] + else: + del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + +def test_create_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + + request = {} + client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.CreateBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["big_query_export_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 "bigQueryExportId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "bigQueryExportId" in jsonified_request + assert jsonified_request["bigQueryExportId"] == request_init["big_query_export_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["bigQueryExportId"] = 'big_query_export_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("big_query_export_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 "bigQueryExportId" in jsonified_request + assert jsonified_request["bigQueryExportId"] == 'big_query_export_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + expected_params = [ + ( + "bigQueryExportId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(("bigQueryExportId", )) & set(("parent", "bigQueryExport", "bigQueryExportId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_big_query_export") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_big_query_export") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateBigQueryExportRequest.pb(securitycenter_service.CreateBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) + + request = securitycenter_service.CreateBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.create_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_big_query_export(request) + + +def test_create_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) + + # Establish that the underlying call 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=organizations/*}/bigQueryExports" % client.transport._host, args[1]) + + +def test_create_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_id_value', + ) + + +def test_create_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteBigQueryExportRequest, + dict, +]) +def test_delete_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/bigQueryExports/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 = 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + + request = {} + client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.DeleteBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + 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_big_query_export(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_big_query_export") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteBigQueryExportRequest.pb(securitycenter_service.DeleteBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/bigQueryExports/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_big_query_export(request) + + +def test_delete_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/bigQueryExports/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_big_query_export(**mock_args) + + # Establish that the underlying call 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=organizations/*/bigQueryExports/*}" % client.transport._host, args[1]) + + +def test_delete_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name='name_value', + ) + + +def test_delete_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateBigQueryExportRequest, + dict, +]) +def test_update_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'big_query_export': {'name': 'organizations/sample1/bigQueryExports/sample2'}} + request_init["big_query_export"] = {'name': 'organizations/sample1/bigQueryExports/sample2', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.UpdateBigQueryExportRequest.meta.fields["big_query_export"] + + 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["big_query_export"].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["big_query_export"][field])): + del request_init["big_query_export"][field][i][subfield] + else: + del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + +def test_update_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc + + request = {} + client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.UpdateBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_big_query_export._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_big_query_export._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("bigQueryExport", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_big_query_export") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_big_query_export") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateBigQueryExportRequest.pb(securitycenter_service.UpdateBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) + + request = securitycenter_service.UpdateBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.update_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'big_query_export': {'name': 'organizations/sample1/bigQueryExports/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_big_query_export(request) + + +def test_update_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = {'big_query_export': {'name': 'organizations/sample1/bigQueryExports/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + big_query_export=bigquery_export.BigQueryExport(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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) + + # Establish that the underlying call 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/{big_query_export.name=organizations/*/bigQueryExports/*}" % client.transport._host, args[1]) + + +def test_update_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListBigQueryExportsRequest, + dict, +]) +def test_list_big_query_exports_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) + 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_big_query_exports(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_big_query_exports_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_big_query_exports in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc + + request = {} + client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_big_query_exports(request) + + # Establish 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_big_query_exports_rest_required_fields(request_type=securitycenter_service.ListBigQueryExportsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_big_query_exports._get_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_big_query_exports._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListBigQueryExportsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) + 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_big_query_exports(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_big_query_exports_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_big_query_exports._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_big_query_exports_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_big_query_exports") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_big_query_exports") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListBigQueryExportsRequest.pb(securitycenter_service.ListBigQueryExportsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListBigQueryExportsResponse.to_json(securitycenter_service.ListBigQueryExportsResponse()) + + request = securitycenter_service.ListBigQueryExportsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListBigQueryExportsResponse() + + client.list_big_query_exports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_big_query_exports_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListBigQueryExportsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_big_query_exports(request) + + +def test_list_big_query_exports_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListBigQueryExportsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse.pb(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_big_query_exports(**mock_args) + + # Establish that the underlying call 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=organizations/*}/bigQueryExports" % client.transport._host, args[1]) + + +def test_list_big_query_exports_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent='parent_value', + ) + + +def test_list_big_query_exports_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListBigQueryExportsResponse.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': 'organizations/sample1'} + + pager = client.list_big_query_exports(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, bigquery_export.BigQueryExport) + for i in results) + + pages = list(client.list_big_query_exports(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_create_event_threat_detection_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request_init["event_threat_detection_custom_module"] = {'name': 'name_value', 'config': {'fields': {}}, 'ancestor_module': 'ancestor_module_value', 'enablement_state': 1, 'type_': 'type__value', 'display_name': 'display_name_value', 'description': 'description_value', 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_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 = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.meta.fields["event_threat_detection_custom_module"] + + 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["event_threat_detection_custom_module"].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["event_threat_detection_custom_module"][field])): + del request_init["event_threat_detection_custom_module"][field][i][subfield] + else: + del request_init["event_threat_detection_custom_module"][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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) + 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_event_threat_detection_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + +def test_create_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc + + request = {} + client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_event_threat_detection_custom_module(request) + + # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_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_event_threat_detection_custom_module._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) + 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_event_threat_detection_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_event_threat_detection_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_event_threat_detection_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "eventThreatDetectionCustomModule", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_event_threat_detection_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_event_threat_detection_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_event_threat_detection_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.CreateEventThreatDetectionCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.to_json(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + client.create_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_event_threat_detection_custom_module(request) + + +def test_create_event_threat_detection_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(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_event_threat_detection_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/customModules" % client.transport._host, args[1]) + + +def test_create_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_event_threat_detection_custom_module( + securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(), + parent='parent_value', + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + ) + + +def test_create_event_threat_detection_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_delete_event_threat_detection_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/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 = 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_event_threat_detection_custom_module(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc + + request = {} + client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_event_threat_detection_custom_module(request) + + # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + 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_event_threat_detection_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_event_threat_detection_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_event_threat_detection_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_event_threat_detection_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_event_threat_detection_custom_module") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_event_threat_detection_custom_module(request) + + +def test_delete_event_threat_detection_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/eventThreatDetectionSettings/customModules/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_event_threat_detection_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings/customModules/*}" % client.transport._host, args[1]) + + +def test_delete_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_event_threat_detection_custom_module( + securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + + +def test_delete_event_threat_detection_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_get_event_threat_detection_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/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 = event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) + 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_event_threat_detection_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + +def test_get_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_event_threat_detection_custom_module] = mock_rpc + + request = {} + client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_event_threat_detection_custom_module(request) + + # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.GetEventThreatDetectionCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) + 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_event_threat_detection_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_event_threat_detection_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_event_threat_detection_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_event_threat_detection_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_event_threat_detection_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_event_threat_detection_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.GetEventThreatDetectionCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = event_threat_detection_custom_module.EventThreatDetectionCustomModule.to_json(event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + client.get_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetEventThreatDetectionCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_event_threat_detection_custom_module(request) + + +def test_get_event_threat_detection_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/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 = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(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_event_threat_detection_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings/customModules/*}" % client.transport._host, args[1]) + + +def test_get_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_event_threat_detection_custom_module( + securitycenter_service.GetEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + + +def test_get_event_threat_detection_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, + dict, +]) +def test_list_descendant_event_threat_detection_custom_modules_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(return_value) + 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_descendant_event_threat_detection_custom_modules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDescendantEventThreatDetectionCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_descendant_event_threat_detection_custom_modules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_descendant_event_threat_detection_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_descendant_event_threat_detection_custom_modules] = mock_rpc + + request = {} + client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish 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_descendant_event_threat_detection_custom_modules_rest_required_fields(request_type=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_descendant_event_threat_detection_custom_modules._get_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_descendant_event_threat_detection_custom_modules._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(return_value) + 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_descendant_event_threat_detection_custom_modules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_descendant_event_threat_detection_custom_modules_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_descendant_event_threat_detection_custom_modules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_descendant_event_threat_detection_custom_modules_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_descendant_event_threat_detection_custom_modules") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_descendant_event_threat_detection_custom_modules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.pb(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.to_json(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse()) + + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + + client.list_descendant_event_threat_detection_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_descendant_event_threat_detection_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_descendant_event_threat_detection_custom_modules(request) + + +def test_list_descendant_event_threat_detection_custom_modules_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + + # 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 = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(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_descendant_event_threat_detection_custom_modules(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/customModules:listDescendant" % client.transport._host, args[1]) + + +def test_list_descendant_event_threat_detection_custom_modules_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_descendant_event_threat_detection_custom_modules( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_descendant_event_threat_detection_custom_modules_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.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': 'organizations/sample1/eventThreatDetectionSettings'} + + pager = client.list_descendant_event_threat_detection_custom_modules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + for i in results) + + pages = list(client.list_descendant_event_threat_detection_custom_modules(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListEventThreatDetectionCustomModulesRequest, + dict, +]) +def test_list_event_threat_detection_custom_modules_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(return_value) + 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_event_threat_detection_custom_modules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventThreatDetectionCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_event_threat_detection_custom_modules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_event_threat_detection_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_event_threat_detection_custom_modules] = mock_rpc + + request = {} + client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_event_threat_detection_custom_modules(request) + + # Establish 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_event_threat_detection_custom_modules_rest_required_fields(request_type=securitycenter_service.ListEventThreatDetectionCustomModulesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_event_threat_detection_custom_modules._get_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_event_threat_detection_custom_modules._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(return_value) + 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_event_threat_detection_custom_modules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_event_threat_detection_custom_modules_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_event_threat_detection_custom_modules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_event_threat_detection_custom_modules_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_event_threat_detection_custom_modules") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_event_threat_detection_custom_modules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListEventThreatDetectionCustomModulesRequest.pb(securitycenter_service.ListEventThreatDetectionCustomModulesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.to_json(securitycenter_service.ListEventThreatDetectionCustomModulesResponse()) + + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + + client.list_event_threat_detection_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_event_threat_detection_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListEventThreatDetectionCustomModulesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_event_threat_detection_custom_modules(request) + + +def test_list_event_threat_detection_custom_modules_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + + # 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 = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(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_event_threat_detection_custom_modules(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/customModules" % client.transport._host, args[1]) + + +def test_list_event_threat_detection_custom_modules_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_event_threat_detection_custom_modules( + securitycenter_service.ListEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_event_threat_detection_custom_modules_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListEventThreatDetectionCustomModulesResponse.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': 'organizations/sample1/eventThreatDetectionSettings'} + + pager = client.list_event_threat_detection_custom_modules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + for i in results) + + pages = list(client.list_event_threat_detection_custom_modules(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_update_event_threat_detection_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'event_threat_detection_custom_module': {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'}} + request_init["event_threat_detection_custom_module"] = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2', 'config': {'fields': {}}, 'ancestor_module': 'ancestor_module_value', 'enablement_state': 1, 'type_': 'type__value', 'display_name': 'display_name_value', 'description': 'description_value', 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_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 = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.meta.fields["event_threat_detection_custom_module"] + + 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["event_threat_detection_custom_module"].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["event_threat_detection_custom_module"][field])): + del request_init["event_threat_detection_custom_module"][field][i][subfield] + else: + del request_init["event_threat_detection_custom_module"][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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) + 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_event_threat_detection_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + +def test_update_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_event_threat_detection_custom_module] = mock_rpc + + request = {} + client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_event_threat_detection_custom_module(request) + + # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_event_threat_detection_custom_module._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_event_threat_detection_custom_module._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) + 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_event_threat_detection_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_event_threat_detection_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_event_threat_detection_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("eventThreatDetectionCustomModule", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_event_threat_detection_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_event_threat_detection_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_event_threat_detection_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.to_json(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + client.update_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'event_threat_detection_custom_module': {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_event_threat_detection_custom_module(request) + + +def test_update_event_threat_detection_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'event_threat_detection_custom_module': {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(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_event_threat_detection_custom_module(**mock_args) + + # Establish that the underlying call 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/{event_threat_detection_custom_module.name=organizations/*/eventThreatDetectionSettings/customModules/*}" % client.transport._host, args[1]) + + +def test_update_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_event_threat_detection_custom_module( + securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(), + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_event_threat_detection_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_validate_event_threat_detection_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.pb(return_value) + 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_event_threat_detection_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) + +def test_validate_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc + + request = {} + client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.validate_event_threat_detection_custom_module(request) + + # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["raw_text"] = "" + request_init["type_"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["rawText"] = 'raw_text_value' + jsonified_request["type"] = 'type__value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).validate_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "rawText" in jsonified_request + assert jsonified_request["rawText"] == 'raw_text_value' + assert "type" in jsonified_request + assert jsonified_request["type"] == 'type__value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.pb(return_value) + 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_event_threat_detection_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_validate_event_threat_detection_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.validate_event_threat_detection_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "rawText", "type", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_validate_event_threat_detection_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_validate_event_threat_detection_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_validate_event_threat_detection_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.to_json(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse()) + + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() + + client.validate_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_validate_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.validate_event_threat_detection_custom_module(request) + + +def test_validate_event_threat_detection_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_get_effective_event_threat_detection_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/effectiveCustomModules/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 = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( + name='name_value', + enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(return_value) + 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_effective_event_threat_detection_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.enablement_state == effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_get_effective_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_effective_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_effective_event_threat_detection_custom_module] = mock_rpc + + request = {} + client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_effective_event_threat_detection_custom_module(request) + + # Establish 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_effective_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_effective_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_effective_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(return_value) + 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_effective_event_threat_detection_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_effective_event_threat_detection_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_effective_event_threat_detection_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_effective_event_threat_detection_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_effective_event_threat_detection_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_effective_event_threat_detection_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.to_json(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule()) + + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + + client.get_effective_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_effective_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/effectiveCustomModules/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_effective_event_threat_detection_custom_module(request) + + +def test_get_effective_event_threat_detection_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/eventThreatDetectionSettings/effectiveCustomModules/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 = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(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_effective_event_threat_detection_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings/effectiveCustomModules/*}" % client.transport._host, args[1]) + + +def test_get_effective_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_effective_event_threat_detection_custom_module( + securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + + +def test_get_effective_event_threat_detection_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, + dict, +]) +def test_list_effective_event_threat_detection_custom_modules_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(return_value) + 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_effective_event_threat_detection_custom_modules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEffectiveEventThreatDetectionCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_effective_event_threat_detection_custom_modules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_effective_event_threat_detection_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_effective_event_threat_detection_custom_modules] = mock_rpc + + request = {} + client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_effective_event_threat_detection_custom_modules(request) + + # Establish 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_effective_event_threat_detection_custom_modules_rest_required_fields(request_type=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_effective_event_threat_detection_custom_modules._get_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_effective_event_threat_detection_custom_modules._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(return_value) + 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_effective_event_threat_detection_custom_modules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_effective_event_threat_detection_custom_modules_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_effective_event_threat_detection_custom_modules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_effective_event_threat_detection_custom_modules_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_effective_event_threat_detection_custom_modules") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_effective_event_threat_detection_custom_modules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.pb(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.to_json(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse()) + + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + + client.list_effective_event_threat_detection_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_effective_event_threat_detection_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_effective_event_threat_detection_custom_modules(request) + + +def test_list_effective_event_threat_detection_custom_modules_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + + # 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 = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(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_effective_event_threat_detection_custom_modules(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/effectiveCustomModules" % client.transport._host, args[1]) + + +def test_list_effective_event_threat_detection_custom_modules_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_effective_event_threat_detection_custom_modules( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_effective_event_threat_detection_custom_modules_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.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': 'organizations/sample1/eventThreatDetectionSettings'} + + pager = client.list_effective_event_threat_detection_custom_modules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) + for i in results) + + pages = list(client.list_effective_event_threat_detection_custom_modules(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.BatchCreateResourceValueConfigsRequest, + dict, +]) +def test_batch_create_resource_value_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.BatchCreateResourceValueConfigsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) + +def test_batch_create_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc + + request = {} + client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_resource_value_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_batch_create_resource_value_configs_rest_required_fields(request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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()).batch_create_resource_value_configs._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_create_resource_value_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_create_resource_value_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_resource_value_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_batch_create_resource_value_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_batch_create_resource_value_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(securitycenter_service.BatchCreateResourceValueConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.BatchCreateResourceValueConfigsResponse.to_json(securitycenter_service.BatchCreateResourceValueConfigsResponse()) + + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + client.batch_create_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_create_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_create_resource_value_configs(request) + + +def test_batch_create_resource_value_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(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.batch_create_resource_value_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=organizations/*}/resourceValueConfigs:batchCreate" % client.transport._host, args[1]) + + +def test_batch_create_resource_value_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], + ) + + +def test_batch_create_resource_value_configs_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteResourceValueConfigRequest, + dict, +]) +def test_delete_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = 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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + + request = {} + client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.DeleteResourceValueConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( + 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_resource_value_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_resource_value_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteResourceValueConfigRequest.pb(securitycenter_service.DeleteResourceValueConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteResourceValueConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteResourceValueConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_resource_value_config(request) + + +def test_delete_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/resourceValueConfigs/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_resource_value_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=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_resource_value_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name='name_value', + ) + + +def test_delete_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetResourceValueConfigRequest, + dict, +]) +def test_get_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + +def test_get_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc + + request = {} + client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.GetResourceValueConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource_value_config.ResourceValueConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_resource_value_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_resource_value_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetResourceValueConfigRequest.pb(securitycenter_service.GetResourceValueConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource_value_config.ResourceValueConfig.to_json(resource_value_config.ResourceValueConfig()) + + request = securitycenter_service.GetResourceValueConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource_value_config.ResourceValueConfig() + + client.get_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetResourceValueConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_resource_value_config(request) + + +def test_get_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resource_value_config.ResourceValueConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig.pb(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_resource_value_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=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) + + +def test_get_resource_value_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name='name_value', + ) + + +def test_get_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListResourceValueConfigsRequest, + dict, +]) +def test_list_resource_value_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc + + request = {} + client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_value_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_resource_value_configs_rest_required_fields(request_type=securitycenter_service.ListResourceValueConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListResourceValueConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_resource_value_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_resource_value_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_resource_value_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_resource_value_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_resource_value_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListResourceValueConfigsRequest.pb(securitycenter_service.ListResourceValueConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListResourceValueConfigsResponse.to_json(securitycenter_service.ListResourceValueConfigsResponse()) + + request = securitycenter_service.ListResourceValueConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListResourceValueConfigsResponse() + + client.list_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListResourceValueConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_resource_value_configs(request) + + +def test_list_resource_value_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListResourceValueConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse.pb(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_resource_value_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=organizations/*}/resourceValueConfigs" % client.transport._host, args[1]) + + +def test_list_resource_value_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent='parent_value', + ) + + +def test_list_resource_value_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListResourceValueConfigsResponse.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': 'organizations/sample1'} + + pager = client.list_resource_value_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource_value_config.ResourceValueConfig) + for i in results) + + pages = list(client.list_resource_value_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateResourceValueConfigRequest, + dict, +]) +def test_update_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} + request_init["resource_value_config"] = {'name': 'organizations/sample1/resourceValueConfigs/sample2', 'resource_value': 1, 'tag_values': ['tag_values_value1', 'tag_values_value2'], 'resource_type': 'resource_type_value', 'scope': 'scope_value', 'resource_labels_selector': {}, 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'cloud_provider': 1, 'sensitive_data_protection_mapping': {'high_sensitivity_mapping': 1, 'medium_sensitivity_mapping': 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 = securitycenter_service.UpdateResourceValueConfigRequest.meta.fields["resource_value_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["resource_value_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["resource_value_config"][field])): + del request_init["resource_value_config"][field][i][subfield] + else: + del request_init["resource_value_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 = gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + +def test_update_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + + request = {} + client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.UpdateResourceValueConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_resource_value_config.ResourceValueConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("resourceValueConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_resource_value_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_resource_value_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateResourceValueConfigRequest.pb(securitycenter_service.UpdateResourceValueConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_resource_value_config.ResourceValueConfig.to_json(gcs_resource_value_config.ResourceValueConfig()) + + request = securitycenter_service.UpdateResourceValueConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_resource_value_config.ResourceValueConfig() + + client.update_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateResourceValueConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_resource_value_config(request) + + +def test_update_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_resource_value_config.ResourceValueConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + resource_value_config=gcs_resource_value_config.ResourceValueConfig(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 = gcs_resource_value_config.ResourceValueConfig.pb(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_resource_value_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/{resource_value_config.name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) + + +def test_update_resource_value_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListValuedResourcesRequest, + dict, +]) +def test_list_valued_resources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) + 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_valued_resources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_list_valued_resources_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_valued_resources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc + + request = {} + client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_valued_resources(request) + + # Establish 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_valued_resources_rest_required_fields(request_type=securitycenter_service.ListValuedResourcesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_valued_resources._get_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_valued_resources._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListValuedResourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) + 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_valued_resources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_valued_resources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_valued_resources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_valued_resources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_valued_resources") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_valued_resources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListValuedResourcesRequest.pb(securitycenter_service.ListValuedResourcesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListValuedResourcesResponse.to_json(securitycenter_service.ListValuedResourcesResponse()) + + request = securitycenter_service.ListValuedResourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListValuedResourcesResponse() + + client.list_valued_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_valued_resources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListValuedResourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_valued_resources(request) + + +def test_list_valued_resources_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListValuedResourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse.pb(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_valued_resources(**mock_args) + + # Establish that the underlying call 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=organizations/*/simulations/*}/valuedResources" % client.transport._host, args[1]) + + +def test_list_valued_resources_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent='parent_value', + ) + + +def test_list_valued_resources_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListValuedResourcesResponse.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': 'organizations/sample1/simulations/sample2'} + + pager = client.list_valued_resources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, valued_resource.ValuedResource) + for i in results) + + pages = list(client.list_valued_resources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListAttackPathsRequest, + dict, +]) +def test_list_attack_paths_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) + 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_attack_paths(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_attack_paths_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_attack_paths in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc + + request = {} + client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_attack_paths(request) + + # Establish 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_attack_paths_rest_required_fields(request_type=securitycenter_service.ListAttackPathsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_attack_paths._get_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_attack_paths._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAttackPathsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) + 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_attack_paths(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_attack_paths_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_attack_paths._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_attack_paths_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_attack_paths") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_attack_paths") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListAttackPathsRequest.pb(securitycenter_service.ListAttackPathsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListAttackPathsResponse.to_json(securitycenter_service.ListAttackPathsResponse()) + + request = securitycenter_service.ListAttackPathsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListAttackPathsResponse() + + client.list_attack_paths(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_attack_paths_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAttackPathsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_attack_paths(request) + + +def test_list_attack_paths_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAttackPathsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse.pb(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_attack_paths(**mock_args) + + # Establish that the underlying call 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=organizations/*/simulations/*}/attackPaths" % client.transport._host, args[1]) + + +def test_list_attack_paths_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent='parent_value', + ) + + +def test_list_attack_paths_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListAttackPathsResponse.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': 'organizations/sample1/simulations/sample2'} + + pager = client.list_attack_paths(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, attack_path.AttackPath) + for i in results) + + pages = list(client.list_attack_paths(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.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SecurityCenterClient( + 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 = SecurityCenterClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecurityCenterClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, +]) +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() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SecurityCenterClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecurityCenterGrpcTransport, + ) + +def test_security_center_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_security_center_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.securitycenter_v1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'bulk_mute_findings', + 'create_security_health_analytics_custom_module', + 'create_source', + 'create_finding', + 'create_mute_config', + 'create_notification_config', + 'delete_mute_config', + 'delete_notification_config', + 'delete_security_health_analytics_custom_module', + 'get_simulation', + 'get_valued_resource', + 'get_big_query_export', + 'get_iam_policy', + 'get_mute_config', + 'get_notification_config', + 'get_organization_settings', + 'get_effective_security_health_analytics_custom_module', + 'get_security_health_analytics_custom_module', + 'get_source', + 'group_assets', + 'group_findings', + 'list_assets', + 'list_descendant_security_health_analytics_custom_modules', + 'list_findings', + 'list_mute_configs', + 'list_notification_configs', + 'list_effective_security_health_analytics_custom_modules', + 'list_security_health_analytics_custom_modules', + 'list_sources', + 'run_asset_discovery', + 'set_finding_state', + 'set_mute', + 'set_iam_policy', + 'test_iam_permissions', + 'simulate_security_health_analytics_custom_module', + 'update_external_system', + 'update_finding', + 'update_mute_config', + 'update_notification_config', + 'update_organization_settings', + 'update_security_health_analytics_custom_module', + 'update_source', + 'update_security_marks', + 'create_big_query_export', + 'delete_big_query_export', + 'update_big_query_export', + 'list_big_query_exports', + 'create_event_threat_detection_custom_module', + 'delete_event_threat_detection_custom_module', + 'get_event_threat_detection_custom_module', + 'list_descendant_event_threat_detection_custom_modules', + 'list_event_threat_detection_custom_modules', + 'update_event_threat_detection_custom_module', + 'validate_event_threat_detection_custom_module', + 'get_effective_event_threat_detection_custom_module', + 'list_effective_event_threat_detection_custom_modules', + 'batch_create_resource_value_configs', + 'delete_resource_value_config', + 'get_resource_value_config', + 'list_resource_value_configs', + 'update_resource_value_config', + 'list_valued_resources', + 'list_attack_paths', + '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_security_center_base_transport_with_credentials_file(): + # Instantiate the 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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + 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_security_center_base_transport_with_adc(): + # Test the default 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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +def test_security_center_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) + SecurityCenterClient() + 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_transport_auth_adc(transport_class): + # If 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, + ], +) +def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_security_center_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host 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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_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.SecurityCenterRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_security_center_rest_lro_client(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a 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 + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_no_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_with_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_security_center_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SecurityCenterClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SecurityCenterClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.bulk_mute_findings._session + session2 = client2.transport.bulk_mute_findings._session + assert session1 != session2 + session1 = client1.transport.create_security_health_analytics_custom_module._session + session2 = client2.transport.create_security_health_analytics_custom_module._session + assert session1 != session2 + session1 = client1.transport.create_source._session + session2 = client2.transport.create_source._session + assert session1 != session2 + session1 = client1.transport.create_finding._session + session2 = client2.transport.create_finding._session + assert session1 != session2 + session1 = client1.transport.create_mute_config._session + session2 = client2.transport.create_mute_config._session + assert session1 != session2 + session1 = client1.transport.create_notification_config._session + session2 = client2.transport.create_notification_config._session + assert session1 != session2 + session1 = client1.transport.delete_mute_config._session + session2 = client2.transport.delete_mute_config._session + assert session1 != session2 + session1 = client1.transport.delete_notification_config._session + session2 = client2.transport.delete_notification_config._session + assert session1 != session2 + session1 = client1.transport.delete_security_health_analytics_custom_module._session + session2 = client2.transport.delete_security_health_analytics_custom_module._session + assert session1 != session2 + session1 = client1.transport.get_simulation._session + session2 = client2.transport.get_simulation._session + assert session1 != session2 + session1 = client1.transport.get_valued_resource._session + session2 = client2.transport.get_valued_resource._session + assert session1 != session2 + session1 = client1.transport.get_big_query_export._session + session2 = client2.transport.get_big_query_export._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.get_mute_config._session + session2 = client2.transport.get_mute_config._session + assert session1 != session2 + session1 = client1.transport.get_notification_config._session + session2 = client2.transport.get_notification_config._session + assert session1 != session2 + session1 = client1.transport.get_organization_settings._session + session2 = client2.transport.get_organization_settings._session + assert session1 != session2 + session1 = client1.transport.get_effective_security_health_analytics_custom_module._session + session2 = client2.transport.get_effective_security_health_analytics_custom_module._session + assert session1 != session2 + session1 = client1.transport.get_security_health_analytics_custom_module._session + session2 = client2.transport.get_security_health_analytics_custom_module._session + assert session1 != session2 + session1 = client1.transport.get_source._session + session2 = client2.transport.get_source._session + assert session1 != session2 + session1 = client1.transport.group_assets._session + session2 = client2.transport.group_assets._session + assert session1 != session2 + session1 = client1.transport.group_findings._session + session2 = client2.transport.group_findings._session + assert session1 != session2 + session1 = client1.transport.list_assets._session + session2 = client2.transport.list_assets._session + assert session1 != session2 + session1 = client1.transport.list_descendant_security_health_analytics_custom_modules._session + session2 = client2.transport.list_descendant_security_health_analytics_custom_modules._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_mute_configs._session + session2 = client2.transport.list_mute_configs._session + assert session1 != session2 + session1 = client1.transport.list_notification_configs._session + session2 = client2.transport.list_notification_configs._session + assert session1 != session2 + session1 = client1.transport.list_effective_security_health_analytics_custom_modules._session + session2 = client2.transport.list_effective_security_health_analytics_custom_modules._session + assert session1 != session2 + session1 = client1.transport.list_security_health_analytics_custom_modules._session + session2 = client2.transport.list_security_health_analytics_custom_modules._session + assert session1 != session2 + session1 = client1.transport.list_sources._session + session2 = client2.transport.list_sources._session + assert session1 != session2 + session1 = client1.transport.run_asset_discovery._session + session2 = client2.transport.run_asset_discovery._session + assert session1 != session2 + session1 = client1.transport.set_finding_state._session + session2 = client2.transport.set_finding_state._session + assert session1 != session2 + session1 = client1.transport.set_mute._session + session2 = client2.transport.set_mute._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 + session1 = client1.transport.simulate_security_health_analytics_custom_module._session + session2 = client2.transport.simulate_security_health_analytics_custom_module._session + assert session1 != session2 + session1 = client1.transport.update_external_system._session + session2 = client2.transport.update_external_system._session + assert session1 != session2 + session1 = client1.transport.update_finding._session + session2 = client2.transport.update_finding._session + assert session1 != session2 + session1 = client1.transport.update_mute_config._session + session2 = client2.transport.update_mute_config._session + assert session1 != session2 + session1 = client1.transport.update_notification_config._session + session2 = client2.transport.update_notification_config._session + assert session1 != session2 + session1 = client1.transport.update_organization_settings._session + session2 = client2.transport.update_organization_settings._session + assert session1 != session2 + session1 = client1.transport.update_security_health_analytics_custom_module._session + session2 = client2.transport.update_security_health_analytics_custom_module._session + assert session1 != session2 + session1 = client1.transport.update_source._session + session2 = client2.transport.update_source._session + assert session1 != session2 + session1 = client1.transport.update_security_marks._session + session2 = client2.transport.update_security_marks._session + assert session1 != session2 + session1 = client1.transport.create_big_query_export._session + session2 = client2.transport.create_big_query_export._session + assert session1 != session2 + session1 = client1.transport.delete_big_query_export._session + session2 = client2.transport.delete_big_query_export._session + assert session1 != session2 + session1 = client1.transport.update_big_query_export._session + session2 = client2.transport.update_big_query_export._session + assert session1 != session2 + session1 = client1.transport.list_big_query_exports._session + session2 = client2.transport.list_big_query_exports._session + assert session1 != session2 + session1 = client1.transport.create_event_threat_detection_custom_module._session + session2 = client2.transport.create_event_threat_detection_custom_module._session + assert session1 != session2 + session1 = client1.transport.delete_event_threat_detection_custom_module._session + session2 = client2.transport.delete_event_threat_detection_custom_module._session + assert session1 != session2 + session1 = client1.transport.get_event_threat_detection_custom_module._session + session2 = client2.transport.get_event_threat_detection_custom_module._session + assert session1 != session2 + session1 = client1.transport.list_descendant_event_threat_detection_custom_modules._session + session2 = client2.transport.list_descendant_event_threat_detection_custom_modules._session + assert session1 != session2 + session1 = client1.transport.list_event_threat_detection_custom_modules._session + session2 = client2.transport.list_event_threat_detection_custom_modules._session + assert session1 != session2 + session1 = client1.transport.update_event_threat_detection_custom_module._session + session2 = client2.transport.update_event_threat_detection_custom_module._session + assert session1 != session2 + session1 = client1.transport.validate_event_threat_detection_custom_module._session + session2 = client2.transport.validate_event_threat_detection_custom_module._session + assert session1 != session2 + session1 = client1.transport.get_effective_event_threat_detection_custom_module._session + session2 = client2.transport.get_effective_event_threat_detection_custom_module._session + assert session1 != session2 + session1 = client1.transport.list_effective_event_threat_detection_custom_modules._session + session2 = client2.transport.list_effective_event_threat_detection_custom_modules._session + assert session1 != session2 + session1 = client1.transport.batch_create_resource_value_configs._session + session2 = client2.transport.batch_create_resource_value_configs._session + assert session1 != session2 + session1 = client1.transport.delete_resource_value_config._session + session2 = client2.transport.delete_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.get_resource_value_config._session + session2 = client2.transport.get_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.list_resource_value_configs._session + session2 = client2.transport.list_resource_value_configs._session + assert session1 != session2 + session1 = client1.transport.update_resource_value_config._session + session2 = client2.transport.update_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.list_valued_resources._session + session2 = client2.transport.list_valued_resources._session + assert session1 != session2 + session1 = client1.transport.list_attack_paths._session + session2 = client2.transport.list_attack_paths._session + assert session1 != session2 +def test_security_center_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcTransport( + 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_security_center_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcAsyncIOTransport( + 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(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_security_center_grpc_lro_client(): + client = SecurityCenterClient( + 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_security_center_grpc_lro_async_client(): + client = SecurityCenterAsyncClient( + 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_asset_path(): + organization = "squid" + asset = "clam" + expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.asset_path(organization, asset) + assert expected == actual + + +def test_parse_asset_path(): + expected = { + "organization": "whelk", + "asset": "octopus", + } + path = SecurityCenterClient.asset_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_asset_path(path) + assert expected == actual + +def test_attack_path_path(): + organization = "oyster" + simulation = "nudibranch" + valued_resource = "cuttlefish" + attack_path = "mussel" + expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) + actual = SecurityCenterClient.attack_path_path(organization, simulation, valued_resource, attack_path) + assert expected == actual + + +def test_parse_attack_path_path(): + expected = { + "organization": "winkle", + "simulation": "nautilus", + "valued_resource": "scallop", + "attack_path": "abalone", + } + path = SecurityCenterClient.attack_path_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_attack_path_path(path) + assert expected == actual + +def test_big_query_export_path(): + organization = "squid" + export = "clam" + expected = "organizations/{organization}/bigQueryExports/{export}".format(organization=organization, export=export, ) + actual = SecurityCenterClient.big_query_export_path(organization, export) + assert expected == actual + + +def test_parse_big_query_export_path(): + expected = { + "organization": "whelk", + "export": "octopus", + } + path = SecurityCenterClient.big_query_export_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_big_query_export_path(path) + assert expected == actual + +def test_dlp_job_path(): + project = "oyster" + dlp_job = "nudibranch" + expected = "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) + actual = SecurityCenterClient.dlp_job_path(project, dlp_job) + assert expected == actual + + +def test_parse_dlp_job_path(): + expected = { + "project": "cuttlefish", + "dlp_job": "mussel", + } + path = SecurityCenterClient.dlp_job_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_dlp_job_path(path) + assert expected == actual + +def test_effective_event_threat_detection_custom_module_path(): + organization = "winkle" + module = "nautilus" + expected = "organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}".format(organization=organization, module=module, ) + actual = SecurityCenterClient.effective_event_threat_detection_custom_module_path(organization, module) + assert expected == actual + + +def test_parse_effective_event_threat_detection_custom_module_path(): + expected = { + "organization": "scallop", + "module": "abalone", + } + path = SecurityCenterClient.effective_event_threat_detection_custom_module_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_effective_event_threat_detection_custom_module_path(path) + assert expected == actual + +def test_effective_security_health_analytics_custom_module_path(): + organization = "squid" + effective_custom_module = "clam" + expected = "organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{effective_custom_module}".format(organization=organization, effective_custom_module=effective_custom_module, ) + actual = SecurityCenterClient.effective_security_health_analytics_custom_module_path(organization, effective_custom_module) + assert expected == actual + + +def test_parse_effective_security_health_analytics_custom_module_path(): + expected = { + "organization": "whelk", + "effective_custom_module": "octopus", + } + path = SecurityCenterClient.effective_security_health_analytics_custom_module_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_effective_security_health_analytics_custom_module_path(path) + assert expected == actual + +def test_event_threat_detection_custom_module_path(): + organization = "oyster" + module = "nudibranch" + expected = "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}".format(organization=organization, module=module, ) + actual = SecurityCenterClient.event_threat_detection_custom_module_path(organization, module) + assert expected == actual + + +def test_parse_event_threat_detection_custom_module_path(): + expected = { + "organization": "cuttlefish", + "module": "mussel", + } + path = SecurityCenterClient.event_threat_detection_custom_module_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_event_threat_detection_custom_module_path(path) + assert expected == actual + +def test_external_system_path(): + organization = "winkle" + source = "nautilus" + finding = "scallop" + externalsystem = "abalone" + expected = "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) + actual = SecurityCenterClient.external_system_path(organization, source, finding, externalsystem) + assert expected == actual + + +def test_parse_external_system_path(): + expected = { + "organization": "squid", + "source": "clam", + "finding": "whelk", + "externalsystem": "octopus", + } + path = SecurityCenterClient.external_system_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_external_system_path(path) + assert expected == actual + +def test_finding_path(): + organization = "oyster" + source = "nudibranch" + finding = "cuttlefish" + expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + actual = SecurityCenterClient.finding_path(organization, source, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "organization": "mussel", + "source": "winkle", + "finding": "nautilus", + } + path = SecurityCenterClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_finding_path(path) + assert expected == actual + +def test_mute_config_path(): + organization = "scallop" + mute_config = "abalone" + expected = "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) + actual = SecurityCenterClient.mute_config_path(organization, mute_config) + assert expected == actual + + +def test_parse_mute_config_path(): + expected = { + "organization": "squid", + "mute_config": "clam", + } + path = SecurityCenterClient.mute_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_mute_config_path(path) + assert expected == actual + +def test_notification_config_path(): + organization = "whelk" + notification_config = "octopus" + expected = "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) + actual = SecurityCenterClient.notification_config_path(organization, notification_config) + assert expected == actual + + +def test_parse_notification_config_path(): + expected = { + "organization": "oyster", + "notification_config": "nudibranch", + } + path = SecurityCenterClient.notification_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_notification_config_path(path) + assert expected == actual + +def test_organization_settings_path(): + organization = "cuttlefish" + expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) + actual = SecurityCenterClient.organization_settings_path(organization) + assert expected == actual + + +def test_parse_organization_settings_path(): + expected = { + "organization": "mussel", + } + path = SecurityCenterClient.organization_settings_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_organization_settings_path(path) + assert expected == actual + +def test_policy_path(): + organization = "winkle" + constraint_name = "nautilus" + expected = "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) + actual = SecurityCenterClient.policy_path(organization, constraint_name) + assert expected == actual + + +def test_parse_policy_path(): + expected = { + "organization": "scallop", + "constraint_name": "abalone", + } + path = SecurityCenterClient.policy_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_policy_path(path) + assert expected == actual + +def test_resource_value_config_path(): + organization = "squid" + resource_value_config = "clam" + expected = "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) + actual = SecurityCenterClient.resource_value_config_path(organization, resource_value_config) + assert expected == actual + + +def test_parse_resource_value_config_path(): + expected = { + "organization": "whelk", + "resource_value_config": "octopus", + } + path = SecurityCenterClient.resource_value_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_resource_value_config_path(path) + assert expected == actual + +def test_security_health_analytics_custom_module_path(): + organization = "oyster" + custom_module = "nudibranch" + expected = "organizations/{organization}/securityHealthAnalyticsSettings/customModules/{custom_module}".format(organization=organization, custom_module=custom_module, ) + actual = SecurityCenterClient.security_health_analytics_custom_module_path(organization, custom_module) + assert expected == actual + + +def test_parse_security_health_analytics_custom_module_path(): + expected = { + "organization": "cuttlefish", + "custom_module": "mussel", + } + path = SecurityCenterClient.security_health_analytics_custom_module_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_health_analytics_custom_module_path(path) + assert expected == actual + +def test_security_marks_path(): + organization = "winkle" + asset = "nautilus" + expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.security_marks_path(organization, asset) + assert expected == actual + + +def test_parse_security_marks_path(): + expected = { + "organization": "scallop", + "asset": "abalone", + } + path = SecurityCenterClient.security_marks_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_marks_path(path) + assert expected == actual + +def test_simulation_path(): + organization = "squid" + simulation = "clam" + expected = "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) + actual = SecurityCenterClient.simulation_path(organization, simulation) + assert expected == actual + + +def test_parse_simulation_path(): + expected = { + "organization": "whelk", + "simulation": "octopus", + } + path = SecurityCenterClient.simulation_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_simulation_path(path) + assert expected == actual + +def test_source_path(): + organization = "oyster" + source = "nudibranch" + expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + actual = SecurityCenterClient.source_path(organization, source) + assert expected == actual + + +def test_parse_source_path(): + expected = { + "organization": "cuttlefish", + "source": "mussel", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_path(path) + assert expected == actual + +def test_table_data_profile_path(): + project = "winkle" + table_profile = "nautilus" + expected = "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) + actual = SecurityCenterClient.table_data_profile_path(project, table_profile) + assert expected == actual + + +def test_parse_table_data_profile_path(): + expected = { + "project": "scallop", + "table_profile": "abalone", + } + path = SecurityCenterClient.table_data_profile_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_table_data_profile_path(path) + assert expected == actual + +def test_topic_path(): + project = "squid" + topic = "clam" + expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + actual = SecurityCenterClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "whelk", + "topic": "octopus", + } + path = SecurityCenterClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_topic_path(path) + assert expected == actual + +def test_valued_resource_path(): + organization = "oyster" + simulation = "nudibranch" + valued_resource = "cuttlefish" + expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) + actual = SecurityCenterClient.valued_resource_path(organization, simulation, valued_resource) + assert expected == actual + + +def test_parse_valued_resource_path(): + expected = { + "organization": "mussel", + "simulation": "winkle", + "valued_resource": "nautilus", + } + path = SecurityCenterClient.valued_resource_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_valued_resource_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SecurityCenterClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = SecurityCenterClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = SecurityCenterClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = SecurityCenterClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SecurityCenterClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = SecurityCenterClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = SecurityCenterClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = SecurityCenterClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SecurityCenterClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = SecurityCenterClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + transport_class = SecurityCenterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations/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 = 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.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations/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 = 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_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations/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() + + # 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 + + 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(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations'}, 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() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations'} + request = request_type(**request_init) + # Mock the http request call within the method and 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.ListOperationsResponse() + + # 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), +]) +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-securitycenter/v1beta1/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v1beta1/.coveragerc new file mode 100644 index 000000000000..45cb273f8f7c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/securitycenter/__init__.py + google/cloud/securitycenter/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-securitycenter/v1beta1/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v1beta1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/.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-securitycenter/v1beta1/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v1beta1/MANIFEST.in new file mode 100644 index 000000000000..328e3b8929b0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/securitycenter *.py +recursive-include google/cloud/securitycenter_v1beta1 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst new file mode 100644 index 000000000000..f8c63f4cb48a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v1beta1/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/conf.py new file mode 100644 index 000000000000..8e92d2319721 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter 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-securitycenter" +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-securitycenter-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-securitycenter.tex", + u"google-cloud-securitycenter 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-securitycenter", + u"Google Cloud Securitycenter 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-securitycenter", + u"google-cloud-securitycenter Documentation", + author, + "google-cloud-securitycenter", + "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v1beta1/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/index.rst new file mode 100644 index 000000000000..883606269b5e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + securitycenter_v1beta1/services + securitycenter_v1beta1/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst new file mode 100644 index 000000000000..304849ecc112 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst @@ -0,0 +1,10 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center + :members: + :inherited-members: + +.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst new file mode 100644 index 000000000000..a09a4b86906d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v1beta1 API +==================================================== +.. toctree:: + :maxdepth: 2 + + security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst new file mode 100644 index 000000000000..0bbeba064657 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Securitycenter v1beta1 API +================================================= + +.. automodule:: google.cloud.securitycenter_v1beta1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__init__.py new file mode 100644 index 000000000000..34bcf9197d85 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__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.cloud.securitycenter import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.securitycenter_v1beta1.services.security_center.client import SecurityCenterClient +from google.cloud.securitycenter_v1beta1.services.security_center.async_client import SecurityCenterAsyncClient + +from google.cloud.securitycenter_v1beta1.types.asset import Asset +from google.cloud.securitycenter_v1beta1.types.finding import Finding +from google.cloud.securitycenter_v1beta1.types.organization_settings import OrganizationSettings +from google.cloud.securitycenter_v1beta1.types.run_asset_discovery_response import RunAssetDiscoveryResponse +from google.cloud.securitycenter_v1beta1.types.security_marks import SecurityMarks +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import CreateFindingRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import CreateSourceRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GetOrganizationSettingsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GetSourceRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupAssetsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupAssetsResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupFindingsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupFindingsResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupResult +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListAssetsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListAssetsResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListFindingsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListFindingsResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListSourcesRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListSourcesResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import RunAssetDiscoveryRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import SetFindingStateRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateFindingRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateOrganizationSettingsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateSecurityMarksRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateSourceRequest +from google.cloud.securitycenter_v1beta1.types.source import Source + +__all__ = ('SecurityCenterClient', + 'SecurityCenterAsyncClient', + 'Asset', + 'Finding', + 'OrganizationSettings', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateSourceRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/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-securitycenter/v1beta1/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py new file mode 100644 index 000000000000..4f049ee47efe --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__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.cloud.securitycenter_v1beta1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + +from .types.asset import Asset +from .types.finding import Finding +from .types.organization_settings import OrganizationSettings +from .types.run_asset_discovery_response import RunAssetDiscoveryResponse +from .types.security_marks import SecurityMarks +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import GetOrganizationSettingsRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GroupAssetsRequest +from .types.securitycenter_service import GroupAssetsResponse +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAssetsRequest +from .types.securitycenter_service import ListAssetsResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import RunAssetDiscoveryRequest +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateOrganizationSettingsRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.source import Source + +__all__ = ( + 'SecurityCenterAsyncClient', +'Asset', +'CreateFindingRequest', +'CreateSourceRequest', +'Finding', +'GetOrganizationSettingsRequest', +'GetSourceRequest', +'GroupAssetsRequest', +'GroupAssetsResponse', +'GroupFindingsRequest', +'GroupFindingsResponse', +'GroupResult', +'ListAssetsRequest', +'ListAssetsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListSourcesRequest', +'ListSourcesResponse', +'OrganizationSettings', +'RunAssetDiscoveryRequest', +'RunAssetDiscoveryResponse', +'SecurityCenterClient', +'SecurityMarks', +'SetFindingStateRequest', +'Source', +'UpdateFindingRequest', +'UpdateOrganizationSettingsRequest', +'UpdateSecurityMarksRequest', +'UpdateSourceRequest', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json new file mode 100644 index 000000000000..afd9dcb019c2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json @@ -0,0 +1,298 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v1beta1", + "protoPackage": "google.cloud.securitycenter.v1beta1", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "rest": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/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-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/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-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py new file mode 100644 index 000000000000..bffcff5da306 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + 'SecurityCenterClient', + 'SecurityCenterAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py new file mode 100644 index 000000000000..6e93123eb92f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.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. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.securitycenter_v1beta1 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.securitycenter_v1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V1 Beta APIs for Security Center service.""" + + _client: SecurityCenterClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE + + asset_path = staticmethod(SecurityCenterClient.asset_path) + parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) + parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) + organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) + parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) + source_path = staticmethod(SecurityCenterClient.source_path) + parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) + common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) + parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) + common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) + parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) + common_project_path = staticmethod(SecurityCenterClient.common_project_path) + parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) + common_location_path = staticmethod(SecurityCenterClient.common_location_path) + parse_common_location_path = staticmethod(SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v1beta1 + + async def sample_create_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.CreateSourceRequest, dict]]): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = 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_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding_id: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_create_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.CreateFindingRequest, dict]]): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 get_organization_settings(self, + request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest, dict]]): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_organization_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 get_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v1beta1 + + async def sample_get_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GetSourceRequest, dict]]): + The request object. Request message for getting a source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 group_assets(self, + request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsAsyncPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_group_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest, dict]]): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsAsyncPager: + Response message for grouping by + assets. + 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, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.GroupAssetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_group_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest, dict]]): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". + To groupBy across all sources provide a source_id of + ``-``. For example: + organizations/{organization_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state``). The string value + should follow SQL syntax: comma separated list of + fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets(self, + request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists an organization's assets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_list_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.ListAssetsRequest, dict]]): + The request object. Request message for listing assets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsAsyncPager: + Response message for listing assets. + + 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, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(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_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListAssetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings(self, + request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_list_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListFindingsRequest( + parent="parent_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.securitycenter_v1beta1.types.ListFindingsRequest, dict]]): + The request object. Request message for listing findings. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.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_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_list_sources(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.ListSourcesRequest, dict]]): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]". + + 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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesAsyncPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_asset_discovery(self, + request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS 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 securitycenter_v1beta1 + + async def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest, dict]]): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.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([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, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.run_asset_discovery] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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, + empty_pb2.Empty, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + start_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of 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 securitycenter_v1beta1 + + async def sample_set_finding_state(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest, dict]]): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`google.cloud.securitycenter_v1beta1.types.Finding.State`): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 update_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_update_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest, dict]]): + The request object. Request message for updating or + creating a finding. + finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe domain. + self._client._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_organization_settings(self, + request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, + *, + organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = await client.update_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest, dict]]): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`google.cloud.securitycenter_v1beta1.types.OrganizationSettings`): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_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 update_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v1beta1 + + async def sample_update_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest, dict]]): + The request object. Request message for updating a + source. + source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): + Required. The source resource to + update. + + This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_update_security_marks(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest, dict]]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`google.cloud.securitycenter_v1beta1.types.SecurityMarks`): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe domain. + self._client._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) -> "SecurityCenterAsyncClient": + 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__ = ( + "SecurityCenterAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py new file mode 100644 index 000000000000..72d03d765968 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py @@ -0,0 +1,2755 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_v1beta1 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.securitycenter_v1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .transports.rest import SecurityCenterRestTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + _transport_registry["rest"] = SecurityCenterRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SecurityCenterTransport]: + """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V1 Beta APIs for Security Center 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 = "securitycenter.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: + SecurityCenterClient: 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: + SecurityCenterClient: 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) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def asset_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified asset string.""" + return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_asset_path(path: str) -> Dict[str,str]: + """Parses a asset path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def finding_path(organization: str,source: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def organization_settings_path(organization: str,) -> str: + """Returns a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format(organization=organization, ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str,str]: + """Parses a organization_settings path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str,str]: + """Parses a security_marks path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str,source: str,) -> str: + """Returns a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str,str]: + """Parses a source path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 + SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient._read_environment_variables() + self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) + if transport_provided: + # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SecurityCenterTransport], 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_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v1beta1 + + def sample_create_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.CreateSourceRequest, dict]): + The request object. Request message for creating a + source. + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (google.cloud.securitycenter_v1beta1.types.Source): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding_id: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_create_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.CreateFindingRequest, dict]): + The request object. Request message for creating a + finding. + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (google.cloud.securitycenter_v1beta1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 get_organization_settings(self, + request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest, dict]): + The request object. Request message for getting + organization settings. + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_organization_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 get_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v1beta1 + + def sample_get_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.GetSourceRequest, dict]): + The request object. Request message for getting a source. + name (str): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 group_assets(self, + request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_group_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest, dict]): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsPager: + Response message for grouping by + assets. + 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, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.GroupAssetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_group_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest, dict]): + The request object. Request message for grouping by + findings. + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". + To groupBy across all sources provide a source_id of + ``-``. For example: + organizations/{organization_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (str): + Required. Expression that defines what assets fields to + use for grouping (including ``state``). The string value + should follow SQL syntax: comma separated list of + fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets(self, + request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists an organization's assets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_list_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.ListAssetsRequest, dict]): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsPager: + Response message for listing assets. + + 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, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListAssetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings(self, + request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_list_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListFindingsRequest( + parent="parent_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.securitycenter_v1beta1.types.ListFindingsRequest, dict]): + The request object. Request message for listing findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsPager: + Response message for listing + findings. + 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.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_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_list_sources(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.ListSourcesRequest, dict]): + The request object. Request message for listing sources. + parent (str): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]". + + 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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_asset_discovery(self, + request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), + ) -> operation.Operation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS 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 securitycenter_v1beta1 + + def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest, dict]): + The request object. Request message for running asset + discovery for an organization. + parent (str): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.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([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, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.run_asset_discovery] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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, + empty_pb2.Empty, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + start_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of 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 securitycenter_v1beta1 + + def sample_set_finding_state(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest, dict]): + The request object. Request message for updating a + finding's state. + name (str): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (google.cloud.securitycenter_v1beta1.types.Finding.State): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # 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 + + def update_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_update_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest, dict]): + The request object. Request message for updating or + creating a finding. + finding (google.cloud.securitycenter_v1beta1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe 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_organization_settings(self, + request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, + *, + organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = client.update_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest, dict]): + The request object. Request message for updating an + organization's settings. + organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_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 update_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v1beta1 + + def sample_update_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest, dict]): + The request object. Request message for updating a + source. + source (google.cloud.securitycenter_v1beta1.types.Source): + Required. The source resource to + update. + + This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_update_security_marks(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest, dict]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe 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) -> "SecurityCenterClient": + 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__ = ( + "SecurityCenterClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py new file mode 100644 index 000000000000..51807c4b0d79 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.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 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.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source + + +class GroupAssetsPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupAssetsResponse], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1beta1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + 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[securitycenter_service.GroupAssetsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupAssetsAsyncPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` + attributes are available on the 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[securitycenter_service.GroupAssetsResponse]], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1beta1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + 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[securitycenter_service.GroupAssetsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1beta1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` + attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1beta1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListAssetsResponse], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + 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[securitycenter_service.ListAssetsResponse]: + 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + for page in self.pages: + yield from page.list_assets_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` + attributes are available on the 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[securitycenter_service.ListAssetsResponse]], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + 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[securitycenter_service.ListAssetsResponse]: + 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_assets_results: + 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.securitycenter_v1beta1.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.securitycenter_v1beta1.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[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v1beta1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.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 = securitycenter_service.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[securitycenter_service.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.securitycenter_v1beta1.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.securitycenter_v1beta1.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[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v1beta1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.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 = securitycenter_service.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[securitycenter_service.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) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1beta1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` + attributes are available on the 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[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1beta1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.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-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py new file mode 100644 index 000000000000..9d36139c1a9b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/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 SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .rest import SecurityCenterRestTransport +from .rest import SecurityCenterRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry['grpc'] = SecurityCenterGrpcTransport +_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport +_transport_registry['rest'] = SecurityCenterRestTransport + +__all__ = ( + 'SecurityCenterTransport', + 'SecurityCenterGrpcTransport', + 'SecurityCenterGrpcAsyncIOTransport', + 'SecurityCenterRestTransport', + 'SecurityCenterRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py new file mode 100644 index 000000000000..9c83124b6382 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py @@ -0,0 +1,498 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.securitycenter_v1beta1 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.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +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 SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'securitycenter.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.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: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_source: gapic_v1.method.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_settings: gapic_v1.method.wrap_method( + self.get_organization_settings, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_source: gapic_v1.method.wrap_method( + self.get_source, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.group_assets: gapic_v1.method.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_sources: gapic_v1.method.wrap_method( + self.list_sources, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.run_asset_discovery: gapic_v1.method.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_finding: gapic_v1.method.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=480.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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + 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 get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Union[ + organization_settings.OrganizationSettings, + Awaitable[organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Union[ + source.Source, + Awaitable[source.Source] + ]]: + raise NotImplementedError() + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Union[ + securitycenter_service.GroupAssetsResponse, + Awaitable[securitycenter_service.GroupAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Union[ + securitycenter_service.GroupFindingsResponse, + Awaitable[securitycenter_service.GroupFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Union[ + securitycenter_service.ListAssetsResponse, + Awaitable[securitycenter_service.ListAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Union[ + securitycenter_service.ListFindingsResponse, + Awaitable[securitycenter_service.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Union[ + securitycenter_service.ListSourcesResponse, + Awaitable[securitycenter_service.ListSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + 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 test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Union[ + gcs_organization_settings.OrganizationSettings, + Awaitable[gcs_organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Union[ + gcs_security_marks.SecurityMarks, + Awaitable[gcs_security_marks.SecurityMarks] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SecurityCenterTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py new file mode 100644 index 000000000000..bd93a5f13210 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.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. +# +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.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +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 SecurityCenterTransport, DEFAULT_CLIENT_INFO + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V1 Beta APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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 create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + ~.GroupAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + 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.securitycenter.v1beta1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + operations_pb2.Operation]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + ~.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 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + ~.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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SecurityCenterGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 000000000000..47e586023e58 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,945 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +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 SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V1 Beta APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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._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 create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + 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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Awaitable[organization_settings.OrganizationSettings]]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Awaitable[securitycenter_service.GroupAssetsResponse]]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + Awaitable[~.GroupAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse]]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Awaitable[securitycenter_service.ListAssetsResponse]]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + 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.securitycenter.v1beta1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse]]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + 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 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + 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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.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.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + 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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Awaitable[gcs_organization_settings.OrganizationSettings]]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks]]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + 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_source: gapic_v1.method_async.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method_async.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_settings: gapic_v1.method_async.wrap_method( + self.get_organization_settings, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_source: gapic_v1.method_async.wrap_method( + self.get_source, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.group_assets: gapic_v1.method_async.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method_async.wrap_method( + self.group_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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method_async.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method_async.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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_sources: gapic_v1.method_async.wrap_method( + self.list_sources, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.run_asset_discovery: gapic_v1.method_async.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method_async.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_finding: gapic_v1.method_async.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method_async.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method_async.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method_async.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py new file mode 100644 index 000000000000..a44f2b2a1487 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py @@ -0,0 +1,2542 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # 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 path_template +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 +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +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 SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SecurityCenterRestInterceptor: + """Interceptor for SecurityCenter. + + 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 SecurityCenterRestTransport. + + .. code-block:: python + class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): + def pre_create_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_organization_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_organization_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_assets(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_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_run_asset_discovery(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_asset_discovery(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_finding_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_finding_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_organization_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_organization_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_security_marks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_security_marks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_source(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) + client = SecurityCenterClient(transport=transport) + + + """ + def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for create_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for create_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_organization_settings(self, request: securitycenter_service.GetOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_organization_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_organization_settings(self, response: organization_settings.OrganizationSettings) -> organization_settings.OrganizationSettings: + """Post-rpc interceptor for get_organization_settings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_source(self, response: source.Source) -> source.Source: + """Post-rpc interceptor for get_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_assets(self, request: securitycenter_service.GroupAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_assets(self, response: securitycenter_service.GroupAssetsResponse) -> securitycenter_service.GroupAssetsResponse: + """Post-rpc interceptor for group_assets + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: + """Post-rpc interceptor for group_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_assets(self, request: securitycenter_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_assets(self, response: securitycenter_service.ListAssetsResponse) -> securitycenter_service.ListAssetsResponse: + """Post-rpc interceptor for list_assets + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. + """ + return request, metadata + + def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_sources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: + """Post-rpc interceptor for list_sources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_run_asset_discovery(self, request: securitycenter_service.RunAssetDiscoveryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.RunAssetDiscoveryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for run_asset_discovery + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_run_asset_discovery(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for run_asset_discovery + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for update_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_organization_settings(self, request: securitycenter_service.UpdateOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_organization_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_organization_settings(self, response: gcs_organization_settings.OrganizationSettings) -> gcs_organization_settings.OrganizationSettings: + """Post-rpc interceptor for update_organization_settings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: + """Post-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for update_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SecurityCenterRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SecurityCenterRestInterceptor + + +class SecurityCenterRestTransport(SecurityCenterTransport): + """REST backend transport for SecurityCenter. + + V1 Beta APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[SecurityCenterRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 + 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 + ) + 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 SecurityCenterRestInterceptor() + 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': '/v1beta1/{name=organizations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1beta1/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=organizations/*/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="v1beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "findingId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the create finding method over HTTP. + + Args: + request (~.securitycenter_service.CreateFindingRequest): + The request object. Request message for creating a + finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=organizations/*/sources/*}/findings', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_create_finding(request, metadata) + pb_request = securitycenter_service.CreateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_finding(resp) + return resp + + class _CreateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the create source method over HTTP. + + Args: + request (~.securitycenter_service.CreateSourceRequest): + The request object. Request message for creating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=organizations/*}/sources', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_create_source(request, metadata) + pb_request = securitycenter_service.CreateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_source(resp) + return resp + + class _GetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{resource=organizations/*/sources/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetOrganizationSettings(SecurityCenterRestStub): + def __hash__(self): + return hash("GetOrganizationSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetOrganizationSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> organization_settings.OrganizationSettings: + r"""Call the get organization settings method over HTTP. + + Args: + request (~.securitycenter_service.GetOrganizationSettingsRequest): + The request object. Request message for getting + organization 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: + ~.organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=organizations/*/organizationSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_organization_settings(request, metadata) + pb_request = securitycenter_service.GetOrganizationSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = organization_settings.OrganizationSettings() + pb_resp = organization_settings.OrganizationSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_organization_settings(resp) + return resp + + class _GetSource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> source.Source: + r"""Call the get source method over HTTP. + + Args: + request (~.securitycenter_service.GetSourceRequest): + The request object. Request message for getting a source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=organizations/*/sources/*}', + }, + ] + request, metadata = self._interceptor.pre_get_source(request, metadata) + pb_request = securitycenter_service.GetSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = source.Source() + pb_resp = source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_source(resp) + return resp + + class _GroupAssets(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupAssetsResponse: + r"""Call the group assets method over HTTP. + + Args: + request (~.securitycenter_service.GroupAssetsRequest): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupAssetsResponse: + Response message for grouping by + assets. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=organizations/*}/assets:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_assets(request, metadata) + pb_request = securitycenter_service.GroupAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupAssetsResponse() + pb_resp = securitycenter_service.GroupAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_assets(resp) + return resp + + class _GroupFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupFindingsResponse: + r"""Call the group findings method over HTTP. + + Args: + request (~.securitycenter_service.GroupFindingsRequest): + The request object. Request message for grouping by + findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupFindingsResponse: + Response message for group by + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=organizations/*/sources/*}/findings:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_findings(request, metadata) + pb_request = securitycenter_service.GroupFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupFindingsResponse() + pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_findings(resp) + return resp + + class _ListAssets(SecurityCenterRestStub): + def __hash__(self): + return hash("ListAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListAssetsResponse: + r"""Call the list assets method over HTTP. + + Args: + request (~.securitycenter_service.ListAssetsRequest): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListAssetsResponse: + Response message for listing assets. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=organizations/*}/assets', + }, + ] + request, metadata = self._interceptor.pre_list_assets(request, metadata) + pb_request = securitycenter_service.ListAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListAssetsResponse() + pb_resp = securitycenter_service.ListAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_assets(resp) + return resp + + class _ListFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("ListFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.securitycenter_service.ListFindingsRequest): + The request object. Request message for listing findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListFindingsResponse: + Response message for listing + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=organizations/*/sources/*}/findings', + }, + ] + request, metadata = self._interceptor.pre_list_findings(request, metadata) + pb_request = securitycenter_service.ListFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListFindingsResponse() + pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListSources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListSources") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListSourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListSourcesResponse: + r"""Call the list sources method over HTTP. + + Args: + request (~.securitycenter_service.ListSourcesRequest): + The request object. Request message for listing sources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListSourcesResponse: + Response message for listing sources. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=organizations/*}/sources', + }, + ] + request, metadata = self._interceptor.pre_list_sources(request, metadata) + pb_request = securitycenter_service.ListSourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListSourcesResponse() + pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sources(resp) + return resp + + class _RunAssetDiscovery(SecurityCenterRestStub): + def __hash__(self): + return hash("RunAssetDiscovery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.RunAssetDiscoveryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the run asset discovery method over HTTP. + + Args: + request (~.securitycenter_service.RunAssetDiscoveryRequest): + The request object. Request message for running asset + discovery for an organization. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=organizations/*}/assets:runDiscovery', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_run_asset_discovery(request, metadata) + pb_request = securitycenter_service.RunAssetDiscoveryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_run_asset_discovery(resp) + return resp + + class _SetFindingState(SecurityCenterRestStub): + def __hash__(self): + return hash("SetFindingState") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SetFindingStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the set finding state method over HTTP. + + Args: + request (~.securitycenter_service.SetFindingStateRequest): + The request object. Request message for updating a + finding's state. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{name=organizations/*/sources/*/findings/*}:setState', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_finding_state(request, metadata) + pb_request = securitycenter_service.SetFindingStateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_set_finding_state(resp) + return resp + + class _SetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{resource=organizations/*/sources/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _TestIamPermissions(SecurityCenterRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{resource=organizations/*/sources/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UpdateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the update finding method over HTTP. + + Args: + request (~.securitycenter_service.UpdateFindingRequest): + The request object. Request message for updating or + creating a finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta1/{finding.name=organizations/*/sources/*/findings/*}', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_update_finding(request, metadata) + pb_request = securitycenter_service.UpdateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_finding(resp) + return resp + + class _UpdateOrganizationSettings(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateOrganizationSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateOrganizationSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Call the update organization + settings method over HTTP. + + Args: + request (~.securitycenter_service.UpdateOrganizationSettingsRequest): + The request object. Request message for updating an + organization's 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: + ~.gcs_organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta1/{organization_settings.name=organizations/*/organizationSettings}', + 'body': 'organization_settings', + }, + ] + request, metadata = self._interceptor.pre_update_organization_settings(request, metadata) + pb_request = securitycenter_service.UpdateOrganizationSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_organization_settings.OrganizationSettings() + pb_resp = gcs_organization_settings.OrganizationSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_organization_settings(resp) + return resp + + class _UpdateSecurityMarks(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSecurityMarks") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSecurityMarksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_security_marks.SecurityMarks: + r"""Call the update security marks method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSecurityMarksRequest): + The request object. Request message for updating a + SecurityMarks resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1beta1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, + ] + request, metadata = self._interceptor.pre_update_security_marks(request, metadata) + pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_security_marks.SecurityMarks() + pb_resp = gcs_security_marks.SecurityMarks.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_security_marks(resp) + return resp + + class _UpdateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the update source method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSourceRequest): + The request object. Request message for updating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta1/{source.name=organizations/*/sources/*}', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_update_source(request, metadata) + pb_request = securitycenter_service.UpdateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_source(resp) + return resp + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.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_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + 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._RunAssetDiscovery(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SecurityCenterRestTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py new file mode 100644 index 000000000000..d3d5b965f804 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .asset import ( + Asset, +) +from .finding import ( + Finding, +) +from .organization_settings import ( + OrganizationSettings, +) +from .run_asset_discovery_response import ( + RunAssetDiscoveryResponse, +) +from .security_marks import ( + SecurityMarks, +) +from .securitycenter_service import ( + CreateFindingRequest, + CreateSourceRequest, + GetOrganizationSettingsRequest, + GetSourceRequest, + GroupAssetsRequest, + GroupAssetsResponse, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListAssetsRequest, + ListAssetsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListSourcesRequest, + ListSourcesResponse, + RunAssetDiscoveryRequest, + SetFindingStateRequest, + UpdateFindingRequest, + UpdateOrganizationSettingsRequest, + UpdateSecurityMarksRequest, + UpdateSourceRequest, +) +from .source import ( + Source, +) + +__all__ = ( + 'Asset', + 'Finding', + 'OrganizationSettings', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateSourceRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py new file mode 100644 index 000000000000..16ad84206b64 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'Asset', + }, +) + + +class Asset(proto.Message): + r"""Security Command Center representation of a Google Cloud + resource. + + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All + modifications to an Asset are only within the context of + Security Command Center and don't affect the referenced Google + Cloud resource. + + Attributes: + name (str): + The relative resource name of this asset. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/assets/{asset_id}". + security_center_properties (google.cloud.securitycenter_v1beta1.types.Asset.SecurityCenterProperties): + Security Command Center managed properties. + These properties are managed by Security Command + Center and cannot be modified by the user. + resource_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Resource managed properties. These properties + are managed and defined by the Google Cloud + resource and cannot be modified by the user. + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): + User specified security marks. These marks + are entirely managed by the user and come from + the SecurityMarks resource that belongs to the + asset. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was last updated, + added, or deleted in Security Command Center. + """ + + class SecurityCenterProperties(proto.Message): + r"""Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified by + the user. + + Attributes: + resource_name (str): + Immutable. The full resource name of the Google Cloud + resource this asset represents. This field is immutable + after create time. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_type (str): + The type of the Google Cloud resource. + Examples include: APPLICATION, PROJECT, and + ORGANIZATION. This is a case insensitive field + defined by Security Command Center and/or the + producer of the resource and is immutable after + create time. + resource_parent (str): + The full resource name of the immediate parent of the + resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_project (str): + The full resource name of the project the resource belongs + to. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_owners (MutableSequence[str]): + Owners of the Google Cloud resource. + """ + + resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + resource_parent: str = proto.Field( + proto.STRING, + number=3, + ) + resource_project: str = proto.Field( + proto.STRING, + number=4, + ) + resource_owners: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + security_center_properties: SecurityCenterProperties = proto.Field( + proto.MESSAGE, + number=2, + message=SecurityCenterProperties, + ) + resource_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py new file mode 100644 index 000000000000..15d2a4ec1ee5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.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.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + + A finding is a record of assessment data (security, risk, health + or privacy) ingested into Security Command Center for + presentation, notification, analysis, policy testing, and + enforcement. For example, an XSS vulnerability in an App Engine + application is a finding. + + Attributes: + name (str): + The relative resource name of this finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". + parent (str): + Immutable. The relative resource name of the source the + finding belongs to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. For example: + "organizations/{organization_id}/sources/{source_id}". + resource_name (str): + For findings on Google Cloud resources, the full resource + name of the Google Cloud resource this finding is for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + This field is immutable after creation time. + state (google.cloud.securitycenter_v1beta1.types.Finding.State): + The state of the finding. + category (str): + The additional taxonomy group within findings from a given + source. This field is immutable after creation time. + Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the event took place, or + when an update to the finding occurred. For + example, if the finding represents an open + firewall it would capture the time the detector + believes the firewall became open. The accuracy + is determined by the detector. If the finding + were to be resolved afterward, this time would + reflect when the finding was resolved. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the finding was created in + Security Command Center. + """ + class State(proto.Enum): + r"""The state of the finding. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + ACTIVE (1): + The finding requires attention and has not + been addressed yet. + INACTIVE (2): + The finding has been fixed, triaged as a + non-issue or otherwise addressed and is no + longer active. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + resource_name: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + category: str = proto.Field( + proto.STRING, + number=5, + ) + external_uri: str = proto.Field( + proto.STRING, + number=6, + ) + source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py new file mode 100644 index 000000000000..e94e037fd61a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'OrganizationSettings', + }, +) + + +class OrganizationSettings(proto.Message): + r"""User specified settings that are attached to the Security + Command Center organization. + + Attributes: + name (str): + The relative resource name of the settings. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/organizationSettings". + enable_asset_discovery (bool): + A flag that indicates if Asset Discovery should be enabled. + If the flag is set to ``true``, then discovery of assets + will occur. If it is set to \`false, all historical assets + will remain, but discovery of future assets will not occur. + asset_discovery_config (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig): + The configuration used for Asset Discovery + runs. + """ + + class AssetDiscoveryConfig(proto.Message): + r"""The configuration used for Asset Discovery runs. + + Attributes: + project_ids (MutableSequence[str]): + The project ids to use for filtering asset + discovery. + inclusion_mode (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + The mode to use for filtering asset + discovery. + """ + class InclusionMode(proto.Enum): + r"""The mode of inclusion when running Asset Discovery. Asset discovery + can be limited by explicitly identifying projects to be included or + excluded. If INCLUDE_ONLY is set, then only those projects within + the organization and their children are discovered during asset + discovery. If EXCLUDE is set, then projects that don't match those + projects are discovered during asset discovery. If neither are set, + then all projects within the organization are discovered during + asset discovery. + + Values: + INCLUSION_MODE_UNSPECIFIED (0): + Unspecified. Setting the mode with this value + will disable inclusion/exclusion filtering for + Asset Discovery. + INCLUDE_ONLY (1): + Asset Discovery will capture only the + resources within the projects specified. All + other resources will be ignored. + EXCLUDE (2): + Asset Discovery will ignore all resources + under the projects specified. All other + resources will be retrieved. + """ + INCLUSION_MODE_UNSPECIFIED = 0 + INCLUDE_ONLY = 1 + EXCLUDE = 2 + + project_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + inclusion_mode: 'OrganizationSettings.AssetDiscoveryConfig.InclusionMode' = proto.Field( + proto.ENUM, + number=2, + enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + enable_asset_discovery: bool = proto.Field( + proto.BOOL, + number=2, + ) + asset_discovery_config: AssetDiscoveryConfig = proto.Field( + proto.MESSAGE, + number=3, + message=AssetDiscoveryConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py new file mode 100644 index 000000000000..c5bccb3dd7f2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.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 + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'RunAssetDiscoveryResponse', + }, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + + Attributes: + state (google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (google.protobuf.duration_pb2.Duration): + The duration between asset discovery run + start and end + """ + class State(proto.Enum): + r"""The state of an asset discovery run. + + Values: + STATE_UNSPECIFIED (0): + Asset discovery run state was unspecified. + COMPLETED (1): + Asset discovery run completed successfully. + SUPERSEDED (2): + Asset discovery run was cancelled with tasks + still pending, as another run for the same + organization was started with a higher priority. + TERMINATED (3): + Asset discovery run was killed and + terminated. + """ + STATE_UNSPECIFIED = 0 + COMPLETED = 1 + SUPERSEDED = 2 + TERMINATED = 3 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py new file mode 100644 index 000000000000..f2b762a6f2ec --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'SecurityMarks', + }, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". + marks (MutableMapping[str, str]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + marks: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py new file mode 100644 index 000000000000..dd7fedfd6122 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py @@ -0,0 +1,1053 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1beta1.types import asset as gcs_asset +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'CreateFindingRequest', + 'CreateSourceRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'SetFindingStateRequest', + 'RunAssetDiscoveryRequest', + 'UpdateFindingRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSourceRequest', + 'UpdateSecurityMarksRequest', + }, +) + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + + Attributes: + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + alphanumeric and less than or equal to 32 + characters and greater than 0 characters in + length. + finding (google.cloud.securitycenter_v1beta1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + finding_id: str = proto.Field( + proto.STRING, + number=2, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_finding.Finding, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + source (google.cloud.securitycenter_v1beta1.types.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_source.Source, + ) + + +class GetOrganizationSettingsRequest(proto.Message): + r"""Request message for getting organization settings. + + Attributes: + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is "organizations/[organization_id]/source/[source_id]". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GroupAssetsRequest(proto.Message): + r"""Request message for grouping by assets. + + Attributes: + parent (str): + Required. Name of the organization to groupBy. Its format is + "organizations/[organization_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``resource_properties.size = 100`` is a valid + filter string. + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is + not set: + + - security_center_properties.resource_project + - security_center_properties.resource_type + - security_center_properties.resource_parent + + The following fields are supported when compare_duration is + set: + + - security_center_properties.resource_type + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the Asset's "state" property + is updated to indicate whether the asset was added, removed, + or remained present during the compare_duration period of + time that precedes the read_time. This is the time between + (read_time - compare_duration) and read_time. + + The state value is derived based on the presence of the + asset at the two points in time. Intermediate state changes + between the two times don't affect the result. For example, + the results aren't affected if the asset is removed and + re-created again. + + Possible "state" values when compare_duration is specified: + + - "ADDED": indicates that the asset was not present before + compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at + reference_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and reference_time. + + This field is ignored if ``state`` is not a field in + ``group_by``. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupAssetsResponse``; + indicates that this is a continuation of a prior + ``GroupAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupAssetsResponse(proto.Message): + r"""Response message for grouping by assets. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + + Attributes: + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". To + groupBy across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``source_properties.size = 100`` is a valid + filter string. + group_by (str): + Required. Expression that defines what assets fields to use + for grouping (including ``state``). The string value should + follow SQL syntax: comma separated list of fields. For + example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + page_size: int = proto.Field( + proto.INT32, + number=6, + ) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=struct_pb2.Value, + ) + count: int = proto.Field( + proto.INT64, + number=2, + ) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be "organizations/[organization_id]". + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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=7, + ) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v1beta1.types.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAssetsRequest(proto.Message): + r"""Request message for listing assets. + + Attributes: + parent (str): + Required. Name of the organization assets should belong to. + Its format is "organizations/[organization_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``resource_properties.size = 100`` is a valid + filter string. + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,resource_properties.a_property". + Redundant space characters in the syntax are insignificant. + "name desc,resource_properties.a_property" and " name desc , + resource_properties.a_property " are equivalent. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListAssetResult's "state" + attribute is updated to indicate whether the asset was + added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state value is derived based on the presence of the + asset at the two points in time. Intermediate state changes + between the two times don't affect the result. For example, + the results aren't affected if the asset is removed and + re-created again. + + Possible "state" values when compare_duration is specified: + + - "ADDED": indicates that the asset was not present before + compare_duration, but present at read_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at read_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and read_time. + + If compare_duration is not specified, then the only possible + state is "UNUSED", which indicates that the asset is present + at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. A field mask to specify the + ListAssetsResult fields to be listed in the + response. An empty field mask will list all + fields. + page_token (str): + The value returned by the last ``ListAssetsResponse``; + indicates that this is a continuation of a prior + ``ListAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=9, + ) + + +class ListAssetsResponse(proto.Message): + r"""Response message for listing assets. + + Attributes: + list_assets_results (MutableSequence[google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of assets matching the + query. + """ + + class ListAssetsResult(proto.Message): + r"""Result containing the Asset and its State. + + Attributes: + asset (google.cloud.securitycenter_v1beta1.types.Asset): + Asset matching the search request. + state (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult.State): + State of the asset. + """ + class State(proto.Enum): + r"""State of the asset. + + When querying across two points in time this describes the change + between the two points: ADDED, REMOVED, or ACTIVE. If there was no + compare_duration supplied in the request the state should be: UNUSED + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + UNUSED (1): + Request did not specify use of this field in + the result. + ADDED (2): + Asset was added between the points in time. + REMOVED (3): + Asset was removed between the points in time. + ACTIVE (4): + Asset was active at both point(s) in time. + """ + STATE_UNSPECIFIED = 0 + UNUSED = 1 + ADDED = 2 + REMOVED = 3 + ACTIVE = 4 + + asset: gcs_asset.Asset = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_asset.Asset, + ) + state: 'ListAssetsResponse.ListAssetsResult.State' = proto.Field( + proto.ENUM, + number=2, + enum='ListAssetsResponse.ListAssetsResult.State', + ) + + @property + def raw_page(self): + return self + + list_assets_results: MutableSequence[ListAssetsResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListAssetsResult, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + + Attributes: + parent (str): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id]". To + list across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``source_properties.size = 100`` is a valid + filter string. + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,source_properties.a_property". Redundant + space characters in the syntax are insignificant. "name + desc,source_properties.a_property" and " name desc , + source_properties.a_property " are equivalent. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. A field mask to specify the Finding + fields to be listed in the response. An empty + field mask will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=6, + ) + page_size: int = proto.Field( + proto.INT32, + number=7, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + + Attributes: + findings (MutableSequence[google.cloud.securitycenter_v1beta1.types.Finding]): + Findings matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + @property + def raw_page(self): + return self + + findings: MutableSequence[gcs_finding.Finding] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + + Attributes: + name (str): + Required. The relative resource name of the finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + state (google.cloud.securitycenter_v1beta1.types.Finding.State): + Required. The desired State of the finding. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the updated state + takes effect. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: gcs_finding.Finding.State = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.State, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class RunAssetDiscoveryRequest(proto.Message): + r"""Request message for running asset discovery for an + organization. + + Attributes: + parent (str): + Required. Name of the organization to run asset discovery + for. Its format is "organizations/[organization_id]". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + + Attributes: + finding (google.cloud.securitycenter_v1beta1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + finding resource. This field should not be + specified when creating a finding. + """ + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + + Attributes: + organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + settings resource. + """ + + organization_settings: gcs_organization_settings.OrganizationSettings = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_organization_settings.OrganizationSettings, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (google.cloud.securitycenter_v1beta1.types.Source): + Required. The source resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the source + resource. + """ + + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): + Required. The security marks resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + security marks resource. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the updated SecurityMarks + take effect. + """ + + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_marks.SecurityMarks, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + start_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-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py new file mode 100644 index 000000000000..761384a9c28f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v1beta1', + manifest={ + 'Source', + }, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, etc. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and + outdated/insecure libraries.". + """ + + 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, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/noxfile.py new file mode 100644 index 000000000000..09f9f6872402 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-securitycenter' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +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"): + 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/securitycenter_v1beta1/', + '--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"): + 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", + "grpcio", + "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/securitycenter_v1beta1/', + '--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( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): + # Ignore release of mypy 1.11.0 which may have a regression + 'mypy!=1.11.0', + '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-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_async.py new file mode 100644 index 000000000000..e2ccd162023c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_create_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_sync.py new file mode 100644 index 000000000000..8a6cd38a65ea --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_create_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_async.py new file mode 100644 index 000000000000..b705b58ee221 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_CreateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_create_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_sync.py new file mode 100644 index 000000000000..ed1f60c4c944 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_CreateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_create_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py new file mode 100644 index 000000000000..8f5186953423 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py new file mode 100644 index 000000000000..74daec484fa2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py new file mode 100644 index 000000000000..e21dbe268313 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_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 GetOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py new file mode 100644 index 000000000000..40c62b6f158e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_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 GetOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_async.py new file mode 100644 index 000000000000..92eeeb159eb1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GetSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_get_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_sync.py new file mode 100644 index 000000000000..4432d6697cb8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GetSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_get_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_async.py new file mode 100644 index 000000000000..7bc11cd58a3d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_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 GroupAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_group_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_sync.py new file mode 100644 index 000000000000..b5a0c8f1322b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_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 GroupAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_group_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_async.py new file mode 100644 index 000000000000..367437acd112 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_group_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_sync.py new file mode 100644 index 000000000000..2b3cdac52e46 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_group_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_async.py new file mode 100644 index 000000000000..80d46cf5ce6f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_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 ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_ListAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_list_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_sync.py new file mode 100644 index 000000000000..6f45a7b22700 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_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 ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_ListAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_list_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_async.py new file mode 100644 index 000000000000..3ee6027b07d6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_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 securitycenter_v1beta1 + + +async def sample_list_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_sync.py new file mode 100644 index 000000000000..6a9a7c526574 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_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 securitycenter_v1beta1 + + +def sample_list_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_async.py new file mode 100644 index 000000000000..ced7ea701eeb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_ListSources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_list_sources(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_sync.py new file mode 100644 index 000000000000..3eff727dc701 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_ListSources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_list_sources(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py new file mode 100644 index 000000000000..7ec0a72a67a5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py new file mode 100644 index 000000000000..7efbac655d2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_async.py new file mode 100644 index 000000000000..f9245b6f398e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_set_finding_state(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py new file mode 100644 index 000000000000..a2b160db84a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_set_finding_state(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py new file mode 100644 index 000000000000..9863d798d645 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py new file mode 100644 index 000000000000..ddac6e4fadb8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py new file mode 100644 index 000000000000..f1ecc97a8e8c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py new file mode 100644 index 000000000000..87f3b0ee6c7b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_async.py new file mode 100644 index 000000000000..8f8e6f58f99f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_update_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_sync.py new file mode 100644 index 000000000000..9c214219e880 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_update_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py new file mode 100644 index 000000000000..8174ebf4f93b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = await client.update_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py new file mode 100644 index 000000000000..b587f61c0ce3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = client.update_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_async.py new file mode 100644 index 000000000000..230075087471 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_update_security_marks(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py new file mode 100644 index 000000000000..f041a1b1fa1a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_update_security_marks(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_async.py new file mode 100644 index 000000000000..3afe218c0c83 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_update_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_sync.py new file mode 100644 index 000000000000..0ff7573f017d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_update_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json new file mode 100644 index 000000000000..a4c1295eaf99 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json @@ -0,0 +1,2945 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.securitycenter.v1beta1", + "version": "v1beta1" + } + ], + "language": "PYTHON", + "name": "google-cloud-securitycenter", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1beta1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v1beta1_generated_security_center_create_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1beta1_generated_security_center_create_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1beta1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v1beta1_generated_security_center_create_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1beta1_generated_security_center_create_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1beta1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v1beta1_generated_security_center_create_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_create_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1beta1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v1beta1_generated_security_center_create_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_create_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.get_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest" + }, + { + "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.securitycenter_v1beta1.types.OrganizationSettings", + "shortName": "get_organization_settings" + }, + "description": "Sample for GetOrganizationSettings", + "file": "securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.get_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest" + }, + { + "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.securitycenter_v1beta1.types.OrganizationSettings", + "shortName": "get_organization_settings" + }, + "description": "Sample for GetOrganizationSettings", + "file": "securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GetSourceRequest" + }, + { + "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.securitycenter_v1beta1.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v1beta1_generated_security_center_get_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_get_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GetSourceRequest" + }, + { + "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.securitycenter_v1beta1.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v1beta1_generated_security_center_get_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_get_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.group_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsAsyncPager", + "shortName": "group_assets" + }, + "description": "Sample for GroupAssets", + "file": "securitycenter_v1beta1_generated_security_center_group_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1beta1_generated_security_center_group_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.group_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsPager", + "shortName": "group_assets" + }, + "description": "Sample for GroupAssets", + "file": "securitycenter_v1beta1_generated_security_center_group_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1beta1_generated_security_center_group_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsAsyncPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v1beta1_generated_security_center_group_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1beta1_generated_security_center_group_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v1beta1_generated_security_center_group_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1beta1_generated_security_center_group_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.list_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.ListAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsAsyncPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "securitycenter_v1beta1_generated_security_center_list_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1beta1_generated_security_center_list_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.list_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.ListAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "securitycenter_v1beta1_generated_security_center_list_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1beta1_generated_security_center_list_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.ListFindingsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsAsyncPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v1beta1_generated_security_center_list_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1beta1_generated_security_center_list_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.ListFindingsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v1beta1_generated_security_center_list_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1beta1_generated_security_center_list_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.ListSourcesRequest" + }, + { + "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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesAsyncPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v1beta1_generated_security_center_list_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1beta1_generated_security_center_list_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.ListSourcesRequest" + }, + { + "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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v1beta1_generated_security_center_list_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1beta1_generated_security_center_list_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.run_asset_discovery", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.RunAssetDiscovery", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "RunAssetDiscovery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "run_asset_discovery" + }, + "description": "Sample for RunAssetDiscovery", + "file": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.run_asset_discovery", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.RunAssetDiscovery", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "RunAssetDiscovery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "run_asset_discovery" + }, + "description": "Sample for RunAssetDiscovery", + "file": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v1beta1.types.Finding.State" + }, + { + "name": "start_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v1beta1_generated_security_center_set_finding_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1beta1_generated_security_center_set_finding_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v1beta1.types.Finding.State" + }, + { + "name": "start_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1beta1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v1beta1_generated_security_center_update_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1beta1_generated_security_center_update_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1beta1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v1beta1_generated_security_center_update_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1beta1_generated_security_center_update_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest" + }, + { + "name": "organization_settings", + "type": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings", + "shortName": "update_organization_settings" + }, + "description": "Sample for UpdateOrganizationSettings", + "file": "securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest" + }, + { + "name": "organization_settings", + "type": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings", + "shortName": "update_organization_settings" + }, + "description": "Sample for UpdateOrganizationSettings", + "file": "securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v1beta1.types.SecurityMarks" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v1beta1_generated_security_center_update_security_marks_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1beta1_generated_security_center_update_security_marks_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v1beta1.types.SecurityMarks" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1beta1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v1beta1_generated_security_center_update_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1beta1_generated_security_center_update_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1beta1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v1beta1_generated_security_center_update_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1beta1_generated_security_center_update_source_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py new file mode 100644 index 000000000000..e4b81a3218c2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py @@ -0,0 +1,193 @@ +#! /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 securitycenterCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_source': ('parent', 'source', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_organization_settings': ('name', ), + 'get_source': ('name', ), + 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), + 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'page_token', 'page_size', ), + 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'field_mask', 'page_token', 'page_size', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'run_asset_discovery': ('parent', ), + 'set_finding_state': ('name', 'state', 'start_time', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_organization_settings': ('organization_settings', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), + 'update_source': ('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=securitycenterCallTransformer(), +): + """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 securitycenter 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-securitycenter/v1beta1/setup.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/setup.py new file mode 100644 index 000000000000..c4538ec101f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/setup.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. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-securitycenter' + + +description = "Google Cloud Securitycenter API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/securitycenter/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", + "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", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__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-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py new file mode 100644 index 000000000000..1ba9f20c0bed --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py @@ -0,0 +1,14372 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +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 + +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.securitycenter_v1beta1.services.security_center import SecurityCenterAsyncClient +from google.cloud.securitycenter_v1beta1.services.security_center import SecurityCenterClient +from google.cloud.securitycenter_v1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1beta1.services.security_center import transports +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +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 duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None + assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SecurityCenterClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SecurityCenterGrpcTransport, "grpc"), + (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + 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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + available_transports = [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterRestTransport, + ] + assert transport in available_transports + + transport = SecurityCenterClient.get_transport_class("grpc") + assert transport == transports.SecurityCenterGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, 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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), +]) +def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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_security_center_client_client_options_from_dict(): + with mock.patch('google.cloud.securitycenter_v1beta1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_create_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object + + request = {} + await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_create_source_async_from_dict(): + await test_create_source_async(request_type=dict) + + +def test_create_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.create_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.create_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + + +def test_create_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + response = client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +def test_create_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.create_finding] = mock_rpc + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object + + request = {} + await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +@pytest.mark.asyncio +async def test_create_finding_async_from_dict(): + await test_create_finding_async(request_type=dict) + + +def test_create_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + arg = args[0].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + + +def test_create_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + arg = args[0].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.GetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest( + resource='resource_value', + ) + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object + + request = {} + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetOrganizationSettingsRequest, + dict, +]) +def test_get_organization_settings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_get_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetOrganizationSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_organization_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest( + name='name_value', + ) + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_organization_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_organization_settings] = mock_rpc + request = {} + client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_organization_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_organization_settings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + +@pytest.mark.asyncio +async def test_get_organization_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_organization_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_organization_settings] = mock_object + + request = {} + await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_organization_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_get_organization_settings_async_from_dict(): + await test_get_organization_settings_async(request_type=dict) + + +def test_get_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = organization_settings.OrganizationSettings() + client.get_organization_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_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + await client.get_organization_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_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_organization_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_organization_settings_flattened_error(): + client = SecurityCenterClient( + credentials=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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_organization_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_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest( + name='name_value', + ) + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + +@pytest.mark.asyncio +async def test_get_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object + + request = {} + await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_source_async_from_dict(): + await test_get_source_async(request_type=dict) + + +def test_get_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = source.Source() + client.get_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + await client.get_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_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_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupAssetsRequest, + dict, +]) +def test_group_assets(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + ) + response = client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_group_assets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + +def test_group_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupAssetsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc + request = {} + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_group_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + +@pytest.mark.asyncio +async def test_group_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_assets] = mock_object + + request = {} + await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_group_assets_async_from_dict(): + await test_group_assets_async(request_type=dict) + + +def test_group_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = securitycenter_service.GroupAssetsResponse() + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_group_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) + await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_group_assets_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_assets(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, securitycenter_service.GroupResult) + for i in results) +def test_group_assets_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_assets(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_group_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_assets(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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_assets(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", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + ) + response = client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_group_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + +@pytest.mark.asyncio +async def test_group_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_findings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object + + request = {} + await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_findings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_group_findings_async_from_dict(): + await test_group_findings_async(request_type=dict) + + +def test_group_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = securitycenter_service.GroupFindingsResponse() + client.group_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_group_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + await client.group_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_group_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that the 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + + +def test_group_findings_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + +@pytest.mark.asyncio +async def test_group_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_group_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_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, securitycenter_service.GroupResult) + for i in results) +def test_group_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_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_group_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_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", [ + securitycenter_service.ListAssetsRequest, + dict, +]) +def test_list_assets(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_assets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + +def test_list_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListAssetsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_value', + page_token='page_token_value', + ) + +def test_list_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + +@pytest.mark.asyncio +async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object + + request = {} + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + + +def test_list_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = securitycenter_service.ListAssetsResponse() + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_assets_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) +def test_list_assets_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(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_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + 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_assets(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", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +def test_list_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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] == securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + +@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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object + + request = {} + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +@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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.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 = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.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 = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.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 = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.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", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListSourcesRequest( + 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_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + +@pytest.mark.asyncio +async def test_list_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_sources in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object + + request = {} + await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_sources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sources_async_from_dict(): + await test_list_sources_async(request_type=dict) + + +def test_list_sources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = securitycenter_service.ListSourcesResponse() + client.list_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_sources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + await client.list_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_sources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_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_sources_flattened_error(): + client = SecurityCenterClient( + credentials=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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_sources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_sources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_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, source.Source) + for i in results) +def test_list_sources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = list(client.list_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_sources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_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, source.Source) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_sources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + 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_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", [ + securitycenter_service.RunAssetDiscoveryRequest, + dict, +]) +def test_run_asset_discovery(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.RunAssetDiscoveryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_asset_discovery_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + +def test_run_asset_discovery_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.RunAssetDiscoveryRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_asset_discovery(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest( + parent='parent_value', + ) + +def test_run_asset_discovery_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_asset_discovery in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc + request = {} + client.run_asset_discovery(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.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_run_asset_discovery_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + +@pytest.mark.asyncio +async def test_run_asset_discovery_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.run_asset_discovery in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.run_asset_discovery] = mock_object + + request = {} + await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.RunAssetDiscoveryRequest() + 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_run_asset_discovery_async_from_dict(): + await test_run_asset_discovery_async(request_type=dict) + + +def test_run_asset_discovery_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_asset_discovery_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_run_asset_discovery_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery( + 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_run_asset_discovery_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_run_asset_discovery_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery( + 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_run_asset_discovery_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + response = client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +def test_set_finding_state_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + +@pytest.mark.asyncio +async def test_set_finding_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object + + request = {} + await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_finding_state(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +@pytest.mark.asyncio +async def test_set_finding_state_async_from_dict(): + await test_set_finding_state_async(request_type=dict) + + +def test_set_finding_state_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = finding.Finding() + client.set_finding_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_set_finding_state_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_finding_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_set_finding_state_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.SetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest( + resource='resource_value', + ) + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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( + version=774, + etag=b'etag_blob', + )) + response = await client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object + + request = {} + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = SecurityCenterClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.TestIamPermissionsRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( + resource='resource_value', + ) + +def test_test_iam_permissions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object + + request = {} + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + response = client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +def test_update_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateFindingRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.update_finding] = mock_rpc + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object + + request = {} + await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +@pytest.mark.asyncio +async def test_update_finding_async_from_dict(): + await test_update_finding_async(request_type=dict) + + +def test_update_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +def test_update_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_finding( + finding=gcs_finding.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].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + + +def test_update_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_finding( + finding=gcs_finding.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].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateOrganizationSettingsRequest, + dict, +]) +def test_update_organization_settings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_update_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateOrganizationSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_organization_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest( + ) + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_organization_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_organization_settings] = mock_rpc + request = {} + client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_organization_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_organization_settings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + +@pytest.mark.asyncio +async def test_update_organization_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_organization_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_organization_settings] = mock_object + + request = {} + await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_organization_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_update_organization_settings_async_from_dict(): + await test_update_organization_settings_async(request_type=dict) + + +def test_update_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = gcs_organization_settings.OrganizationSettings() + client.update_organization_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', + 'organization_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + await client.update_organization_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', + 'organization_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].organization_settings + mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') + assert arg == mock_val + + +def test_update_organization_settings_flattened_error(): + client = SecurityCenterClient( + credentials=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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].organization_settings + mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_update_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSourceRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object + + request = {} + await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_update_source_async_from_dict(): + await test_update_source_async(request_type=dict) + + +def test_update_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +def test_update_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_source( + source=gcs_source.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].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + + +def test_update_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_source( + source=gcs_source.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].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks( + name='name_value', + ) + response = client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + + +def test_update_security_marks_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + +def test_update_security_marks_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSecurityMarksRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( + ) + +def test_update_security_marks_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish that a new wrapper 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_security_marks_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + )) + response = await client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + +@pytest.mark.asyncio +async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_marks in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object + + request = {} + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_security_marks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + )) + response = await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_security_marks_async_from_dict(): + await test_update_security_marks_async(request_type=dict) + + +def test_update_security_marks_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = gcs_security_marks.SecurityMarks() + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_marks_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +def test_update_security_marks_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].security_marks + mock_val = gcs_security_marks.SecurityMarks(name='name_value') + assert arg == mock_val + + +def test_update_security_marks_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].security_marks + mock_val = gcs_security_marks.SecurityMarks(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': '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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.CreateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_source(request) + + +def test_create_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_create_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +def test_create_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request_init["finding"] = {'name': 'name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.create_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.create_finding] = mock_rpc + + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["finding_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 "findingId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "findingId" in jsonified_request + assert jsonified_request["findingId"] == request_init["finding_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["findingId"] = 'finding_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request + assert jsonified_request["findingId"] == 'finding_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.create_finding(request) + + expected_params = [ + ( + "findingId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.CreateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_finding(request) + + +def test_create_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(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 = gcs_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.create_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/v1beta1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) + + +def test_create_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_create_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.get_iam_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/v1beta1/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetOrganizationSettingsRequest, + dict, +]) +def test_get_organization_settings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/organizationSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_organization_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_organization_settings] = mock_rpc + + request = {} + client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.GetOrganizationSettingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_organization_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_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_organization_settings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_organization_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_organization_settings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_organization_settings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_organization_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetOrganizationSettingsRequest.pb(securitycenter_service.GetOrganizationSettingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = organization_settings.OrganizationSettings.to_json(organization_settings.OrganizationSettings()) + + request = securitycenter_service.GetOrganizationSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = organization_settings.OrganizationSettings() + + client.get_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/organizationSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_organization_settings(request) + + +def test_get_organization_settings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/organizationSettings'} + + # get truthy value for each flattened field + mock_args = dict( + 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 = organization_settings.OrganizationSettings.pb(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_organization_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/v1beta1/{name=organizations/*/organizationSettings}" % client.transport._host, args[1]) + + +def test_get_organization_settings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +def test_get_organization_settings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/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 = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = source.Source.to_json(source.Source()) + + request = securitycenter_service.GetSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = source.Source() + + client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_source(request) + + +def test_get_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v1beta1/{name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_get_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +def test_get_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupAssetsRequest, + dict, +]) +def test_group_assets_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_group_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc + + request = {} + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_group_assets_rest_required_fields(request_type=securitycenter_service.GroupAssetsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_assets_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_assets_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_assets") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupAssetsRequest.pb(securitycenter_service.GroupAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupAssetsResponse.to_json(securitycenter_service.GroupAssetsResponse()) + + request = securitycenter_service.GroupAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupAssetsResponse() + + client.group_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_assets(request) + + +def test_group_assets_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupAssetsResponse.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': 'organizations/sample1'} + + pager = client.group_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_findings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) + + request = securitycenter_service.GroupFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupFindingsResponse() + + client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_findings(request) + + +def test_group_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + group_by='group_by_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v1beta1/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) + + +def test_group_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} + + pager = client.group_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_findings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListAssetsRequest, + dict, +]) +def test_list_assets_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListAssetsResponse.pb(return_value) + 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_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_list_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish 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_assets_rest_required_fields(request_type=securitycenter_service.ListAssetsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_assets._get_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_assets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) + jsonified_request.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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListAssetsResponse.pb(return_value) + 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_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_assets_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_assets_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_assets") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListAssetsRequest.pb(securitycenter_service.ListAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListAssetsResponse.to_json(securitycenter_service.ListAssetsResponse()) + + request = securitycenter_service.ListAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListAssetsResponse() + + client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_assets(request) + + +def test_list_assets_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListAssetsResponse.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': 'organizations/sample1'} + + pager = client.list_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) + + pages = list(client.list_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.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' + assert response.total_size == 1086 + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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=securitycenter_service.ListFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) + jsonified_request.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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.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 = securitycenter_service.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 = [ + ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) + + request = securitycenter_service.ListFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListFindingsResponse() + + client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_findings(request) + + +def test_list_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} + + 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 + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_sources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_sources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) + + request = securitycenter_service.ListSourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListSourcesResponse() + + client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_sources(request) + + +def test_list_sources_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_list_sources_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} + + pager = client.list_sources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, source.Source) + for i in results) + + pages = list(client.list_sources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.RunAssetDiscoveryRequest, + dict, +]) +def test_run_asset_discovery_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') + + # 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 + response = client.run_asset_discovery(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_run_asset_discovery_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_asset_discovery in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc + + request = {} + client.run_asset_discovery(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.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_run_asset_discovery_rest_required_fields(request_type=securitycenter_service.RunAssetDiscoveryRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_asset_discovery._get_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()).run_asset_discovery._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 = SecurityCenterClient( + 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.run_asset_discovery(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_run_asset_discovery_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.run_asset_discovery._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_asset_discovery_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_run_asset_discovery") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_run_asset_discovery") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.RunAssetDiscoveryRequest.pb(securitycenter_service.RunAssetDiscoveryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = securitycenter_service.RunAssetDiscoveryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.run_asset_discovery(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_asset_discovery_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.run_asset_discovery(request) + + +def test_run_asset_discovery_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.run_asset_discovery(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=organizations/*}/assets:runDiscovery" % client.transport._host, args[1]) + + +def test_run_asset_discovery_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +def test_run_asset_discovery_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + + # 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 + response = client.set_finding_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( + 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': "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 = 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.set_finding_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_finding_state_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_finding_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "state", "startTime", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_finding_state_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetFindingStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_finding_state(request) + + +def test_set_finding_state_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + mock_args.update(sample_request) + + # 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.set_finding_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/v1beta1/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) + + +def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +def test_set_finding_state_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.set_iam_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/v1beta1/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # 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 + response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_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.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.update_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.update_finding] = mock_rpc + + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_finding._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_finding._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.update_finding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.UpdateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_finding(request) + + +def test_update_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + finding=gcs_finding.Finding(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 = gcs_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.update_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/v1beta1/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) + + +def test_update_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_update_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateOrganizationSettingsRequest, + dict, +]) +def test_update_organization_settings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + request_init["organization_settings"] = {'name': 'organizations/sample1/organizationSettings', 'enable_asset_discovery': True, 'asset_discovery_config': {'project_ids': ['project_ids_value1', 'project_ids_value2'], 'inclusion_mode': 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 = securitycenter_service.UpdateOrganizationSettingsRequest.meta.fields["organization_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["organization_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["organization_settings"][field])): + del request_init["organization_settings"][field][i][subfield] + else: + del request_init["organization_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 = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_organization_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_organization_settings] = mock_rpc + + request = {} + client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_organization_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_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_organization_settings.OrganizationSettings() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_organization_settings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_organization_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("organizationSettings", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_organization_settings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_organization_settings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_organization_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateOrganizationSettingsRequest.pb(securitycenter_service.UpdateOrganizationSettingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_organization_settings.OrganizationSettings.to_json(gcs_organization_settings.OrganizationSettings()) + + request = securitycenter_service.UpdateOrganizationSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_organization_settings.OrganizationSettings() + + client.update_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_organization_settings(request) + + +def test_update_organization_settings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_organization_settings.OrganizationSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + organization_settings=gcs_organization_settings.OrganizationSettings(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 = gcs_organization_settings.OrganizationSettings.pb(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_organization_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/v1beta1/{organization_settings.name=organizations/*/organizationSettings}" % client.transport._host, args[1]) + + +def test_update_organization_settings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +def test_update_organization_settings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': '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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.UpdateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_source(request) + + +def test_update_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1beta1/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_update_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + + +def test_update_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + request_init["security_marks"] = {'name': 'organizations/sample1/assets/sample2/securityMarks', 'marks': {}} + # The version of a generated dependency at test runtime may differ from the version used 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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] + + 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["security_marks"].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["security_marks"][field])): + del request_init["security_marks"][field][i][subfield] + else: + del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + +def test_update_security_marks_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_security_marks._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_security_marks._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("start_time", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_security_marks_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_security_marks._get_unset_required_fields({}) + assert set(unset_fields) == (set(("startTime", "updateMask", )) & set(("securityMarks", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_security_marks_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) + + request = securitycenter_service.UpdateSecurityMarksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_security_marks.SecurityMarks() + + client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_security_marks(request) + + +def test_update_security_marks_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + + # get arguments that satisfy an http rule for this method + sample_request = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + + # get truthy value for each flattened field + mock_args = dict( + security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}" % client.transport._host, args[1]) + + +def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + +def test_update_security_marks_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SecurityCenterClient( + 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 = SecurityCenterClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecurityCenterClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, +]) +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() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SecurityCenterClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecurityCenterGrpcTransport, + ) + +def test_security_center_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_security_center_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_source', + 'create_finding', + 'get_iam_policy', + 'get_organization_settings', + 'get_source', + 'group_assets', + 'group_findings', + 'list_assets', + 'list_findings', + 'list_sources', + 'run_asset_discovery', + 'set_finding_state', + 'set_iam_policy', + 'test_iam_permissions', + 'update_finding', + 'update_organization_settings', + 'update_source', + 'update_security_marks', + ) + 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_security_center_base_transport_with_credentials_file(): + # Instantiate the 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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + 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_security_center_base_transport_with_adc(): + # Test the default 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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +def test_security_center_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) + SecurityCenterClient() + 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_transport_auth_adc(transport_class): + # If 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, + ], +) +def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_security_center_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host 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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_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.SecurityCenterRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_security_center_rest_lro_client(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a 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 + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_no_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_with_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_security_center_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SecurityCenterClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SecurityCenterClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_source._session + session2 = client2.transport.create_source._session + assert session1 != session2 + session1 = client1.transport.create_finding._session + session2 = client2.transport.create_finding._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.get_organization_settings._session + session2 = client2.transport.get_organization_settings._session + assert session1 != session2 + session1 = client1.transport.get_source._session + session2 = client2.transport.get_source._session + assert session1 != session2 + session1 = client1.transport.group_assets._session + session2 = client2.transport.group_assets._session + assert session1 != session2 + session1 = client1.transport.group_findings._session + session2 = client2.transport.group_findings._session + assert session1 != session2 + session1 = client1.transport.list_assets._session + session2 = client2.transport.list_assets._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_sources._session + session2 = client2.transport.list_sources._session + assert session1 != session2 + session1 = client1.transport.run_asset_discovery._session + session2 = client2.transport.run_asset_discovery._session + assert session1 != session2 + session1 = client1.transport.set_finding_state._session + session2 = client2.transport.set_finding_state._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 + session1 = client1.transport.update_finding._session + session2 = client2.transport.update_finding._session + assert session1 != session2 + session1 = client1.transport.update_organization_settings._session + session2 = client2.transport.update_organization_settings._session + assert session1 != session2 + session1 = client1.transport.update_source._session + session2 = client2.transport.update_source._session + assert session1 != session2 + session1 = client1.transport.update_security_marks._session + session2 = client2.transport.update_security_marks._session + assert session1 != session2 +def test_security_center_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcTransport( + 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_security_center_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcAsyncIOTransport( + 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(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_security_center_grpc_lro_client(): + client = SecurityCenterClient( + 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_security_center_grpc_lro_async_client(): + client = SecurityCenterAsyncClient( + 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_asset_path(): + organization = "squid" + asset = "clam" + expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.asset_path(organization, asset) + assert expected == actual + + +def test_parse_asset_path(): + expected = { + "organization": "whelk", + "asset": "octopus", + } + path = SecurityCenterClient.asset_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_asset_path(path) + assert expected == actual + +def test_finding_path(): + organization = "oyster" + source = "nudibranch" + finding = "cuttlefish" + expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + actual = SecurityCenterClient.finding_path(organization, source, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "organization": "mussel", + "source": "winkle", + "finding": "nautilus", + } + path = SecurityCenterClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_finding_path(path) + assert expected == actual + +def test_organization_settings_path(): + organization = "scallop" + expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) + actual = SecurityCenterClient.organization_settings_path(organization) + assert expected == actual + + +def test_parse_organization_settings_path(): + expected = { + "organization": "abalone", + } + path = SecurityCenterClient.organization_settings_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_organization_settings_path(path) + assert expected == actual + +def test_security_marks_path(): + organization = "squid" + asset = "clam" + expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.security_marks_path(organization, asset) + assert expected == actual + + +def test_parse_security_marks_path(): + expected = { + "organization": "whelk", + "asset": "octopus", + } + path = SecurityCenterClient.security_marks_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_marks_path(path) + assert expected == actual + +def test_source_path(): + organization = "oyster" + source = "nudibranch" + expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + actual = SecurityCenterClient.source_path(organization, source) + assert expected == actual + + +def test_parse_source_path(): + expected = { + "organization": "cuttlefish", + "source": "mussel", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SecurityCenterClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = SecurityCenterClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = SecurityCenterClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = SecurityCenterClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SecurityCenterClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = SecurityCenterClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = SecurityCenterClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = SecurityCenterClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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 = SecurityCenterClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = SecurityCenterClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + transport_class = SecurityCenterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), +]) +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-securitycenter/v1p1beta1/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.coveragerc new file mode 100644 index 000000000000..45cb273f8f7c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/securitycenter/__init__.py + google/cloud/securitycenter/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-securitycenter/v1p1beta1/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.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-securitycenter/v1p1beta1/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/MANIFEST.in new file mode 100644 index 000000000000..57b563bd1a48 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/securitycenter *.py +recursive-include google/cloud/securitycenter_v1p1beta1 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst new file mode 100644 index 000000000000..f8c63f4cb48a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v1p1beta1/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/conf.py new file mode 100644 index 000000000000..8e92d2319721 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter 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-securitycenter" +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-securitycenter-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-securitycenter.tex", + u"google-cloud-securitycenter 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-securitycenter", + u"Google Cloud Securitycenter 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-securitycenter", + u"google-cloud-securitycenter Documentation", + author, + "google-cloud-securitycenter", + "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v1p1beta1/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/index.rst new file mode 100644 index 000000000000..45263147b433 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + securitycenter_v1p1beta1/services + securitycenter_v1p1beta1/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst new file mode 100644 index 000000000000..adab7f4a5e87 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst @@ -0,0 +1,10 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center + :members: + :inherited-members: + +.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst new file mode 100644 index 000000000000..7f537e851e63 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v1p1beta1 API +====================================================== +.. toctree:: + :maxdepth: 2 + + security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst new file mode 100644 index 000000000000..a68ac5c68cff --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Securitycenter v1p1beta1 API +=================================================== + +.. automodule:: google.cloud.securitycenter_v1p1beta1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py new file mode 100644 index 000000000000..fe0af04fb73b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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.securitycenter import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.securitycenter_v1p1beta1.services.security_center.client import SecurityCenterClient +from google.cloud.securitycenter_v1p1beta1.services.security_center.async_client import SecurityCenterAsyncClient + +from google.cloud.securitycenter_v1p1beta1.types.asset import Asset +from google.cloud.securitycenter_v1p1beta1.types.finding import Finding +from google.cloud.securitycenter_v1p1beta1.types.folder import Folder +from google.cloud.securitycenter_v1p1beta1.types.notification_config import NotificationConfig +from google.cloud.securitycenter_v1p1beta1.types.notification_message import NotificationMessage +from google.cloud.securitycenter_v1p1beta1.types.organization_settings import OrganizationSettings +from google.cloud.securitycenter_v1p1beta1.types.resource import Resource +from google.cloud.securitycenter_v1p1beta1.types.run_asset_discovery_response import RunAssetDiscoveryResponse +from google.cloud.securitycenter_v1p1beta1.types.security_marks import SecurityMarks +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateFindingRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateNotificationConfigRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateSourceRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import DeleteNotificationConfigRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetNotificationConfigRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetOrganizationSettingsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetSourceRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupAssetsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupAssetsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupFindingsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupFindingsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupResult +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListAssetsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListAssetsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListFindingsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListFindingsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListNotificationConfigsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListNotificationConfigsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListSourcesRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListSourcesResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import RunAssetDiscoveryRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import SetFindingStateRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateFindingRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateNotificationConfigRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateOrganizationSettingsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateSecurityMarksRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateSourceRequest +from google.cloud.securitycenter_v1p1beta1.types.source import Source + +__all__ = ('SecurityCenterClient', + 'SecurityCenterAsyncClient', + 'Asset', + 'Finding', + 'Folder', + 'NotificationConfig', + 'NotificationMessage', + 'OrganizationSettings', + 'Resource', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateNotificationConfigRequest', + 'CreateSourceRequest', + 'DeleteNotificationConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/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-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py new file mode 100644 index 000000000000..84391a72a3b7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__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 google.cloud.securitycenter_v1p1beta1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + +from .types.asset import Asset +from .types.finding import Finding +from .types.folder import Folder +from .types.notification_config import NotificationConfig +from .types.notification_message import NotificationMessage +from .types.organization_settings import OrganizationSettings +from .types.resource import Resource +from .types.run_asset_discovery_response import RunAssetDiscoveryResponse +from .types.security_marks import SecurityMarks +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateNotificationConfigRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import DeleteNotificationConfigRequest +from .types.securitycenter_service import GetNotificationConfigRequest +from .types.securitycenter_service import GetOrganizationSettingsRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GroupAssetsRequest +from .types.securitycenter_service import GroupAssetsResponse +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAssetsRequest +from .types.securitycenter_service import ListAssetsResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListNotificationConfigsRequest +from .types.securitycenter_service import ListNotificationConfigsResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import RunAssetDiscoveryRequest +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateNotificationConfigRequest +from .types.securitycenter_service import UpdateOrganizationSettingsRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.source import Source + +__all__ = ( + 'SecurityCenterAsyncClient', +'Asset', +'CreateFindingRequest', +'CreateNotificationConfigRequest', +'CreateSourceRequest', +'DeleteNotificationConfigRequest', +'Finding', +'Folder', +'GetNotificationConfigRequest', +'GetOrganizationSettingsRequest', +'GetSourceRequest', +'GroupAssetsRequest', +'GroupAssetsResponse', +'GroupFindingsRequest', +'GroupFindingsResponse', +'GroupResult', +'ListAssetsRequest', +'ListAssetsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListNotificationConfigsRequest', +'ListNotificationConfigsResponse', +'ListSourcesRequest', +'ListSourcesResponse', +'NotificationConfig', +'NotificationMessage', +'OrganizationSettings', +'Resource', +'RunAssetDiscoveryRequest', +'RunAssetDiscoveryResponse', +'SecurityCenterClient', +'SecurityMarks', +'SetFindingStateRequest', +'Source', +'UpdateFindingRequest', +'UpdateNotificationConfigRequest', +'UpdateOrganizationSettingsRequest', +'UpdateSecurityMarksRequest', +'UpdateSourceRequest', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json new file mode 100644 index 000000000000..892a85e5f9fd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json @@ -0,0 +1,373 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v1p1beta1", + "protoPackage": "google.cloud.securitycenter.v1p1beta1", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "rest": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py new file mode 100644 index 000000000000..bffcff5da306 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + 'SecurityCenterClient', + 'SecurityCenterAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py new file mode 100644 index 000000000000..a996989322a3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py @@ -0,0 +1,3039 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.securitycenter_v1p1beta1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.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.securitycenter_v1p1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1p1beta1.types import security_marks +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_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 SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V1p1Beta1 APIs for Security Center service.""" + + _client: SecurityCenterClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE + + asset_path = staticmethod(SecurityCenterClient.asset_path) + parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) + parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) + notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) + parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) + organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) + parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) + source_path = staticmethod(SecurityCenterClient.source_path) + parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) + topic_path = staticmethod(SecurityCenterClient.topic_path) + parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) + common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) + parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) + common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) + parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) + common_project_path = staticmethod(SecurityCenterClient.common_project_path) + parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) + common_location_path = staticmethod(SecurityCenterClient.common_location_path) + parse_common_location_path = staticmethod(SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v1p1beta1 + + async def sample_create_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest, dict]]): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = 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_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding_id: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_create_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest, dict]]): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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 create_notification_config(self, + request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + config_id: Optional[str] = None, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_create_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest, dict]]): + The request object. Request message for creating a + notification config. + parent (:class:`str`): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be between 1 and 128 characters, + and contains alphanumeric characters, + underscores or hyphens only. + + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_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.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_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_notification_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_notification_config(self, + request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest, dict]]): + The request object. Request message for deleting a + notification config. + name (:class:`str`): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1p1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 get_notification_config(self, + request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_get_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest, dict]]): + The request object. Request message for getting a + notification config. + name (:class:`str`): + Required. Name of the notification config to get. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 get_organization_settings(self, + request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest, dict]]): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_organization_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 get_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v1p1beta1 + + async def sample_get_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest, dict]]): + The request object. Request message for getting a source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 group_assets(self, + request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsAsyncPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_group_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest, dict]]): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsAsyncPager: + Response message for grouping by + assets. + 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, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.GroupAssetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_group_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest, dict]]): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + The following fields are supported when compare_duration + is set: + + - state_change + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets(self, + request: Optional[Union[securitycenter_service.ListAssetsRequest, 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.ListAssetsAsyncPager: + r"""Lists an organization's assets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_list_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest, dict]]): + The request object. Request message for listing assets. + parent (:class:`str`): + Required. Name of the organization assets should belong + to. Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsAsyncPager: + Response message for listing assets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListAssetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings(self, + request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsAsyncPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_list_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListFindingsRequest( + parent="parent_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.securitycenter_v1p1beta1.types.ListFindingsRequest, dict]]): + The request object. Request message for listing findings. + parent (:class:`str`): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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_notification_configs(self, + request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsAsyncPager: + r"""Lists notification configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest, dict]]): + The request object. Request message for listing + notification configs. + parent (:class:`str`): + Required. Name of the organization to list notification + configs. Its format is + "organizations/[organization_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsAsyncPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListNotificationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_list_sources(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest, dict]]): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id], folders/[folder_id], + or projects/[project_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesAsyncPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_asset_discovery(self, + request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS 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 securitycenter_v1p1beta1 + + async def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest, dict]]): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` + Response of asset discovery run + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.run_asset_discovery] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + start_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of 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 securitycenter_v1p1beta1 + + async def sample_set_finding_state(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest, dict]]): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding.State`): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1p1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v1p1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 update_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + update_mask: 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]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_update_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest, dict]]): + The request object. Request message for updating or + creating a finding. + finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + + 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.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + 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_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe domain. + self._client._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_config(self, + request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, + *, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + update_mask: 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_update_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest, dict]]): + The request object. Request message for updating a + notification config. + notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the notification config. + If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_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 update_organization_settings(self, + request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, + *, + organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = await client.update_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest, dict]]): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings`): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_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 update_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + update_mask: 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]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v1p1beta1 + + async def sample_update_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest, dict]]): + The request object. Request message for updating a + source. + source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): + Required. The source resource to + update. + + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the source resource. + If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = 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_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + update_mask: 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]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_update_security_marks(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest, dict]]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`google.cloud.securitycenter_v1p1beta1.types.SecurityMarks`): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + + 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.securitycenter_v1p1beta1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + 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_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe domain. + self._client._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) -> "SecurityCenterAsyncClient": + 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__ = ( + "SecurityCenterAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py new file mode 100644 index 000000000000..caeded73d36f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py @@ -0,0 +1,3441 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_v1p1beta1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from 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.securitycenter_v1p1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1p1beta1.types import security_marks +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_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 SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .transports.rest import SecurityCenterRestTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + _transport_registry["rest"] = SecurityCenterRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SecurityCenterTransport]: + """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V1p1Beta1 APIs for Security Center 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 = "securitycenter.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: + SecurityCenterClient: 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: + SecurityCenterClient: 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) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def asset_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified asset string.""" + return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_asset_path(path: str) -> Dict[str,str]: + """Parses a asset path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def finding_path(organization: str,source: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def notification_config_path(organization: str,notification_config: str,) -> str: + """Returns a fully-qualified notification_config string.""" + return "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) + + @staticmethod + def parse_notification_config_path(path: str) -> Dict[str,str]: + """Parses a notification_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def organization_settings_path(organization: str,) -> str: + """Returns a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format(organization=organization, ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str,str]: + """Parses a organization_settings path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str,str]: + """Parses a security_marks path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str,source: str,) -> str: + """Returns a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str,str]: + """Parses a source path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def topic_path(project: str,topic: str,) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str,str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 + SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient._read_environment_variables() + self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) + if transport_provided: + # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SecurityCenterTransport], 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_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v1p1beta1 + + def sample_create_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest, dict]): + The request object. Request message for creating a + source. + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (google.cloud.securitycenter_v1p1beta1.types.Source): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding_id: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_create_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest, dict]): + The request object. Request message for creating a + finding. + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (str): + Required. Unique identifier provided + by the client within the parent scope. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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 create_notification_config(self, + request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + config_id: Optional[str] = None, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_create_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest, dict]): + The request object. Request message for creating a + notification config. + parent (str): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must be between 1 and 128 characters, + and contains alphanumeric characters, + underscores or hyphens only. + + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_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.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_notification_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_notification_config(self, + request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest, dict]): + The request object. Request message for deleting a + notification config. + name (str): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1p1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 get_notification_config(self, + request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_get_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest, dict]): + The request object. Request message for getting a + notification config. + name (str): + Required. Name of the notification config to get. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 get_organization_settings(self, + request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest, dict]): + The request object. Request message for getting + organization settings. + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_organization_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 get_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v1p1beta1 + + def sample_get_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest, dict]): + The request object. Request message for getting a source. + name (str): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 group_assets(self, + request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_group_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest, dict]): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsPager: + Response message for grouping by + assets. + 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, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.GroupAssetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_group_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest, dict]): + The request object. Request message for grouping by + findings. + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (str): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + The following fields are supported when compare_duration + is set: + + - state_change + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets(self, + request: Optional[Union[securitycenter_service.ListAssetsRequest, 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.ListAssetsPager: + r"""Lists an organization's assets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_list_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest, dict]): + The request object. Request message for listing assets. + parent (str): + Required. Name of the organization assets should belong + to. Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsPager: + Response message for listing assets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListAssetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings(self, + request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_list_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListFindingsRequest( + parent="parent_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.securitycenter_v1p1beta1.types.ListFindingsRequest, dict]): + The request object. Request message for listing findings. + parent (str): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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_notification_configs(self, + request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsPager: + r"""Lists notification configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest, dict]): + The request object. Request message for listing + notification configs. + parent (str): + Required. Name of the organization to list notification + configs. Its format is + "organizations/[organization_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListNotificationConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_list_sources(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest, dict]): + The request object. Request message for listing sources. + parent (str): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id], folders/[folder_id], + or projects/[project_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_asset_discovery(self, + request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), + ) -> operation.Operation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS 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 securitycenter_v1p1beta1 + + def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest, dict]): + The request object. Request message for running asset + discovery for an organization. + parent (str): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` + Response of asset discovery run + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.run_asset_discovery] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + start_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of 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 securitycenter_v1p1beta1 + + def sample_set_finding_state(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest, dict]): + The request object. Request message for updating a + finding's state. + name (str): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1p1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v1p1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # 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 + + def update_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + update_mask: 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]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_update_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest, dict]): + The request object. Request message for updating or + creating a finding. + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + + 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.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + 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_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe 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_config(self, + request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, + *, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + update_mask: 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_update_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest, dict]): + The request object. Request message for updating a + notification config. + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the notification config. + If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_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 update_organization_settings(self, + request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, + *, + organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = client.update_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest, dict]): + The request object. Request message for updating an + organization's settings. + organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_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 update_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + update_mask: 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]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v1p1beta1 + + def sample_update_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest, dict]): + The request object. Request message for updating a + source. + source (google.cloud.securitycenter_v1p1beta1.types.Source): + Required. The source resource to + update. + + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the source resource. + If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = 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_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + update_mask: 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]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_update_security_marks(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest, dict]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + + 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.securitycenter_v1p1beta1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + 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_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe 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) -> "SecurityCenterClient": + 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__ = ( + "SecurityCenterClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py new file mode 100644 index 000000000000..ddad1b803817 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py @@ -0,0 +1,839 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from 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.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source + + +class GroupAssetsPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupAssetsResponse], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1p1beta1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + 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[securitycenter_service.GroupAssetsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupAssetsAsyncPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` + attributes are available on the 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[securitycenter_service.GroupAssetsResponse]], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1p1beta1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + 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[securitycenter_service.GroupAssetsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1p1beta1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` + attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1p1beta1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListAssetsResponse], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + 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[securitycenter_service.ListAssetsResponse]: + 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + for page in self.pages: + yield from page.list_assets_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` + attributes are available on the 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[securitycenter_service.ListAssetsResponse]], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + 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[securitycenter_service.ListAssetsResponse]: + 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_assets_results: + 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.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.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[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v1p1beta1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + for page in self.pages: + yield from page.list_findings_results + + 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.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.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[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v1p1beta1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_findings_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + 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[securitycenter_service.ListNotificationConfigsResponse]: + 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[notification_config.NotificationConfig]: + for page in self.pages: + yield from page.notification_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsAsyncPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` + attributes are available on the 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[securitycenter_service.ListNotificationConfigsResponse]], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + 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[securitycenter_service.ListNotificationConfigsResponse]: + 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[notification_config.NotificationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.notification_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1p1beta1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` + attributes are available on the 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[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1p1beta1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.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-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py new file mode 100644 index 000000000000..9d36139c1a9b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/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 SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .rest import SecurityCenterRestTransport +from .rest import SecurityCenterRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry['grpc'] = SecurityCenterGrpcTransport +_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport +_transport_registry['rest'] = SecurityCenterRestTransport + +__all__ = ( + 'SecurityCenterTransport', + 'SecurityCenterGrpcTransport', + 'SecurityCenterGrpcAsyncIOTransport', + 'SecurityCenterRestTransport', + 'SecurityCenterRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py new file mode 100644 index 000000000000..00cffef9c86f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.securitycenter_v1p1beta1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +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.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +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 empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'securitycenter.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.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: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_source: gapic_v1.method.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method.wrap_method( + self.create_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method.wrap_method( + self.delete_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_notification_config: gapic_v1.method.wrap_method( + self.get_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_settings: gapic_v1.method.wrap_method( + self.get_organization_settings, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_source: gapic_v1.method.wrap_method( + self.get_source, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.group_assets: gapic_v1.method.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method.wrap_method( + self.list_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_sources: gapic_v1.method.wrap_method( + self.list_sources, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.run_asset_discovery: gapic_v1.method.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_finding: gapic_v1.method.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method.wrap_method( + self.update_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=480.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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + 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 get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Union[ + notification_config.NotificationConfig, + Awaitable[notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Union[ + organization_settings.OrganizationSettings, + Awaitable[organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Union[ + source.Source, + Awaitable[source.Source] + ]]: + raise NotImplementedError() + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Union[ + securitycenter_service.GroupAssetsResponse, + Awaitable[securitycenter_service.GroupAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Union[ + securitycenter_service.GroupFindingsResponse, + Awaitable[securitycenter_service.GroupFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Union[ + securitycenter_service.ListAssetsResponse, + Awaitable[securitycenter_service.ListAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Union[ + securitycenter_service.ListFindingsResponse, + Awaitable[securitycenter_service.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Union[ + securitycenter_service.ListNotificationConfigsResponse, + Awaitable[securitycenter_service.ListNotificationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Union[ + securitycenter_service.ListSourcesResponse, + Awaitable[securitycenter_service.ListSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + 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 test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Union[ + gcs_organization_settings.OrganizationSettings, + Awaitable[gcs_organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Union[ + gcs_security_marks.SecurityMarks, + Awaitable[gcs_security_marks.SecurityMarks] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SecurityCenterTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py new file mode 100644 index 000000000000..a2a5e40ef1f0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py @@ -0,0 +1,895 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import 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.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +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 empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V1p1Beta1 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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 create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + ~.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_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + ~.GroupAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + 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.securitycenter.v1p1beta1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + ~.ListNotificationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + operations_pb2.Operation]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + ~.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 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + ~.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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SecurityCenterGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 000000000000..0743b78ddbd6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,1125 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +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 empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V1p1Beta1 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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._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 create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + 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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + 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_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Awaitable[notification_config.NotificationConfig]]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Awaitable[organization_settings.OrganizationSettings]]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Awaitable[securitycenter_service.GroupAssetsResponse]]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + Awaitable[~.GroupAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse]]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Awaitable[securitycenter_service.ListAssetsResponse]]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + 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.securitycenter.v1p1beta1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + Awaitable[~.ListNotificationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse]]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + 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 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + 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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.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.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + 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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Awaitable[gcs_organization_settings.OrganizationSettings]]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks]]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + 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_source: gapic_v1.method_async.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method_async.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method_async.wrap_method( + self.create_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method_async.wrap_method( + self.delete_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_notification_config: gapic_v1.method_async.wrap_method( + self.get_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_settings: gapic_v1.method_async.wrap_method( + self.get_organization_settings, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_source: gapic_v1.method_async.wrap_method( + self.get_source, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.group_assets: gapic_v1.method_async.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method_async.wrap_method( + self.group_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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method_async.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method_async.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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method_async.wrap_method( + self.list_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_sources: gapic_v1.method_async.wrap_method( + self.list_sources, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.run_asset_discovery: gapic_v1.method_async.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method_async.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_finding: gapic_v1.method_async.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method_async.wrap_method( + self.update_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method_async.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method_async.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method_async.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py new file mode 100644 index 000000000000..ea67cf703231 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py @@ -0,0 +1,3197 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # 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 path_template +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 +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SecurityCenterRestInterceptor: + """Interceptor for SecurityCenter. + + 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 SecurityCenterRestTransport. + + .. code-block:: python + class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): + def pre_create_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_organization_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_organization_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_assets(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_notification_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_notification_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_run_asset_discovery(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_asset_discovery(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_finding_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_finding_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_organization_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_organization_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_security_marks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_security_marks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_source(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) + client = SecurityCenterClient(transport=transport) + + + """ + def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for create_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_notification_config(self, request: securitycenter_service.CreateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for create_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_delete_notification_config(self, request: securitycenter_service.DeleteNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_notification_config(self, request: securitycenter_service.GetNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_notification_config(self, response: notification_config.NotificationConfig) -> notification_config.NotificationConfig: + """Post-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_organization_settings(self, request: securitycenter_service.GetOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_organization_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_organization_settings(self, response: organization_settings.OrganizationSettings) -> organization_settings.OrganizationSettings: + """Post-rpc interceptor for get_organization_settings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_source(self, response: source.Source) -> source.Source: + """Post-rpc interceptor for get_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_assets(self, request: securitycenter_service.GroupAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_assets(self, response: securitycenter_service.GroupAssetsResponse) -> securitycenter_service.GroupAssetsResponse: + """Post-rpc interceptor for group_assets + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: + """Post-rpc interceptor for group_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_assets(self, request: securitycenter_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_assets(self, response: securitycenter_service.ListAssetsResponse) -> securitycenter_service.ListAssetsResponse: + """Post-rpc interceptor for list_assets + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. + """ + return request, metadata + + def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_notification_configs(self, request: securitycenter_service.ListNotificationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListNotificationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_notification_configs(self, response: securitycenter_service.ListNotificationConfigsResponse) -> securitycenter_service.ListNotificationConfigsResponse: + """Post-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_sources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: + """Post-rpc interceptor for list_sources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_run_asset_discovery(self, request: securitycenter_service.RunAssetDiscoveryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.RunAssetDiscoveryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for run_asset_discovery + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_run_asset_discovery(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for run_asset_discovery + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for update_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_notification_config(self, request: securitycenter_service.UpdateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_organization_settings(self, request: securitycenter_service.UpdateOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_organization_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_organization_settings(self, response: gcs_organization_settings.OrganizationSettings) -> gcs_organization_settings.OrganizationSettings: + """Post-rpc interceptor for update_organization_settings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: + """Post-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for update_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SecurityCenterRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SecurityCenterRestInterceptor + + +class SecurityCenterRestTransport(SecurityCenterTransport): + """REST backend transport for SecurityCenter. + + V1p1Beta1 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[SecurityCenterRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 + 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 + ) + 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 SecurityCenterRestInterceptor() + 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': '/v1p1beta1/{name=organizations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1p1beta1/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1p1beta1/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1p1beta1/{name=organizations/*/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="v1p1beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "findingId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the create finding method over HTTP. + + Args: + request (~.securitycenter_service.CreateFindingRequest): + The request object. Request message for creating a + finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=organizations/*/sources/*}/findings', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_create_finding(request, metadata) + pb_request = securitycenter_service.CreateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_finding(resp) + return resp + + class _CreateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "configId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the create notification + config method over HTTP. + + Args: + request (~.securitycenter_service.CreateNotificationConfigRequest): + The request object. Request message for creating a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=organizations/*}/notificationConfigs', + 'body': 'notification_config', + }, + ] + request, metadata = self._interceptor.pre_create_notification_config(request, metadata) + pb_request = securitycenter_service.CreateNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_notification_config(resp) + return resp + + class _CreateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the create source method over HTTP. + + Args: + request (~.securitycenter_service.CreateSourceRequest): + The request object. Request message for creating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=organizations/*}/sources', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_create_source(request, metadata) + pb_request = securitycenter_service.CreateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_source(resp) + return resp + + class _DeleteNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete notification + config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteNotificationConfigRequest): + The request object. Request message for deleting a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1p1beta1/{name=organizations/*/notificationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_notification_config(request, metadata) + pb_request = securitycenter_service.DeleteNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _GetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{resource=organizations/*/sources/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> notification_config.NotificationConfig: + r"""Call the get notification config method over HTTP. + + Args: + request (~.securitycenter_service.GetNotificationConfigRequest): + The request object. Request message for getting a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.notification_config.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{name=organizations/*/notificationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_notification_config(request, metadata) + pb_request = securitycenter_service.GetNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = notification_config.NotificationConfig() + pb_resp = notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_notification_config(resp) + return resp + + class _GetOrganizationSettings(SecurityCenterRestStub): + def __hash__(self): + return hash("GetOrganizationSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetOrganizationSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> organization_settings.OrganizationSettings: + r"""Call the get organization settings method over HTTP. + + Args: + request (~.securitycenter_service.GetOrganizationSettingsRequest): + The request object. Request message for getting + organization 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: + ~.organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{name=organizations/*/organizationSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_organization_settings(request, metadata) + pb_request = securitycenter_service.GetOrganizationSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = organization_settings.OrganizationSettings() + pb_resp = organization_settings.OrganizationSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_organization_settings(resp) + return resp + + class _GetSource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> source.Source: + r"""Call the get source method over HTTP. + + Args: + request (~.securitycenter_service.GetSourceRequest): + The request object. Request message for getting a source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{name=organizations/*/sources/*}', + }, + ] + request, metadata = self._interceptor.pre_get_source(request, metadata) + pb_request = securitycenter_service.GetSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = source.Source() + pb_resp = source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_source(resp) + return resp + + class _GroupAssets(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupAssetsResponse: + r"""Call the group assets method over HTTP. + + Args: + request (~.securitycenter_service.GroupAssetsRequest): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupAssetsResponse: + Response message for grouping by + assets. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=organizations/*}/assets:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=folders/*}/assets:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=projects/*}/assets:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_assets(request, metadata) + pb_request = securitycenter_service.GroupAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupAssetsResponse() + pb_resp = securitycenter_service.GroupAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_assets(resp) + return resp + + class _GroupFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupFindingsResponse: + r"""Call the group findings method over HTTP. + + Args: + request (~.securitycenter_service.GroupFindingsRequest): + The request object. Request message for grouping by + findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupFindingsResponse: + Response message for group by + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=organizations/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=folders/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=projects/*/sources/*}/findings:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_findings(request, metadata) + pb_request = securitycenter_service.GroupFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupFindingsResponse() + pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_findings(resp) + return resp + + class _ListAssets(SecurityCenterRestStub): + def __hash__(self): + return hash("ListAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListAssetsResponse: + r"""Call the list assets method over HTTP. + + Args: + request (~.securitycenter_service.ListAssetsRequest): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListAssetsResponse: + Response message for listing assets. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=organizations/*}/assets', + }, +{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=folders/*}/assets', + }, +{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=projects/*}/assets', + }, + ] + request, metadata = self._interceptor.pre_list_assets(request, metadata) + pb_request = securitycenter_service.ListAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListAssetsResponse() + pb_resp = securitycenter_service.ListAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_assets(resp) + return resp + + class _ListFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("ListFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.securitycenter_service.ListFindingsRequest): + The request object. Request message for listing findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListFindingsResponse: + Response message for listing + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=organizations/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=folders/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=projects/*/sources/*}/findings', + }, + ] + request, metadata = self._interceptor.pre_list_findings(request, metadata) + pb_request = securitycenter_service.ListFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListFindingsResponse() + pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListNotificationConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListNotificationConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListNotificationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListNotificationConfigsResponse: + r"""Call the list notification configs method over HTTP. + + Args: + request (~.securitycenter_service.ListNotificationConfigsRequest): + The request object. Request message for listing + notification configs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListNotificationConfigsResponse: + Response message for listing + notification configs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=organizations/*}/notificationConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_notification_configs(request, metadata) + pb_request = securitycenter_service.ListNotificationConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListNotificationConfigsResponse() + pb_resp = securitycenter_service.ListNotificationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_notification_configs(resp) + return resp + + class _ListSources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListSources") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListSourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListSourcesResponse: + r"""Call the list sources method over HTTP. + + Args: + request (~.securitycenter_service.ListSourcesRequest): + The request object. Request message for listing sources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListSourcesResponse: + Response message for listing sources. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=organizations/*}/sources', + }, +{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=folders/*}/sources', + }, +{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=projects/*}/sources', + }, + ] + request, metadata = self._interceptor.pre_list_sources(request, metadata) + pb_request = securitycenter_service.ListSourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListSourcesResponse() + pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sources(resp) + return resp + + class _RunAssetDiscovery(SecurityCenterRestStub): + def __hash__(self): + return hash("RunAssetDiscovery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.RunAssetDiscoveryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the run asset discovery method over HTTP. + + Args: + request (~.securitycenter_service.RunAssetDiscoveryRequest): + The request object. Request message for running asset + discovery for an organization. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=organizations/*}/assets:runDiscovery', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_run_asset_discovery(request, metadata) + pb_request = securitycenter_service.RunAssetDiscoveryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_run_asset_discovery(resp) + return resp + + class _SetFindingState(SecurityCenterRestStub): + def __hash__(self): + return hash("SetFindingState") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SetFindingStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the set finding state method over HTTP. + + Args: + request (~.securitycenter_service.SetFindingStateRequest): + The request object. Request message for updating a + finding's state. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{name=organizations/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1p1beta1/{name=folders/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1p1beta1/{name=projects/*/sources/*/findings/*}:setState', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_finding_state(request, metadata) + pb_request = securitycenter_service.SetFindingStateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_set_finding_state(resp) + return resp + + class _SetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{resource=organizations/*/sources/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _TestIamPermissions(SecurityCenterRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{resource=organizations/*/sources/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UpdateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the update finding method over HTTP. + + Args: + request (~.securitycenter_service.UpdateFindingRequest): + The request object. Request message for updating or + creating a finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p1beta1/{finding.name=organizations/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{finding.name=folders/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{finding.name=projects/*/sources/*/findings/*}', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_update_finding(request, metadata) + pb_request = securitycenter_service.UpdateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_finding(resp) + return resp + + class _UpdateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the update notification + config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateNotificationConfigRequest): + The request object. Request message for updating a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p1beta1/{notification_config.name=organizations/*/notificationConfigs/*}', + 'body': 'notification_config', + }, + ] + request, metadata = self._interceptor.pre_update_notification_config(request, metadata) + pb_request = securitycenter_service.UpdateNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_notification_config(resp) + return resp + + class _UpdateOrganizationSettings(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateOrganizationSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateOrganizationSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Call the update organization + settings method over HTTP. + + Args: + request (~.securitycenter_service.UpdateOrganizationSettingsRequest): + The request object. Request message for updating an + organization's 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: + ~.gcs_organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p1beta1/{organization_settings.name=organizations/*/organizationSettings}', + 'body': 'organization_settings', + }, + ] + request, metadata = self._interceptor.pre_update_organization_settings(request, metadata) + pb_request = securitycenter_service.UpdateOrganizationSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_organization_settings.OrganizationSettings() + pb_resp = gcs_organization_settings.OrganizationSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_organization_settings(resp) + return resp + + class _UpdateSecurityMarks(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSecurityMarks") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSecurityMarksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_security_marks.SecurityMarks: + r"""Call the update security marks method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSecurityMarksRequest): + The request object. Request message for updating a + SecurityMarks resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{security_marks.name=folders/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{security_marks.name=projects/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, + ] + request, metadata = self._interceptor.pre_update_security_marks(request, metadata) + pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_security_marks.SecurityMarks() + pb_resp = gcs_security_marks.SecurityMarks.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_security_marks(resp) + return resp + + class _UpdateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the update source method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSourceRequest): + The request object. Request message for updating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p1beta1/{source.name=organizations/*/sources/*}', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_update_source(request, metadata) + pb_request = securitycenter_service.UpdateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_source(resp) + return resp + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + 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._DeleteNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.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_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListNotificationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + 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._RunAssetDiscovery(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SecurityCenterRestTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py new file mode 100644 index 000000000000..9f0c2b8e8129 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__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 .asset import ( + Asset, +) +from .finding import ( + Finding, +) +from .folder import ( + Folder, +) +from .notification_config import ( + NotificationConfig, +) +from .notification_message import ( + NotificationMessage, +) +from .organization_settings import ( + OrganizationSettings, +) +from .resource import ( + Resource, +) +from .run_asset_discovery_response import ( + RunAssetDiscoveryResponse, +) +from .security_marks import ( + SecurityMarks, +) +from .securitycenter_service import ( + CreateFindingRequest, + CreateNotificationConfigRequest, + CreateSourceRequest, + DeleteNotificationConfigRequest, + GetNotificationConfigRequest, + GetOrganizationSettingsRequest, + GetSourceRequest, + GroupAssetsRequest, + GroupAssetsResponse, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListAssetsRequest, + ListAssetsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListSourcesRequest, + ListSourcesResponse, + RunAssetDiscoveryRequest, + SetFindingStateRequest, + UpdateFindingRequest, + UpdateNotificationConfigRequest, + UpdateOrganizationSettingsRequest, + UpdateSecurityMarksRequest, + UpdateSourceRequest, +) +from .source import ( + Source, +) + +__all__ = ( + 'Asset', + 'Finding', + 'Folder', + 'NotificationConfig', + 'NotificationMessage', + 'OrganizationSettings', + 'Resource', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateNotificationConfigRequest', + 'CreateSourceRequest', + 'DeleteNotificationConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py new file mode 100644 index 000000000000..2250330a504d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py @@ -0,0 +1,227 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1p1beta1.types import folder +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'Asset', + }, +) + + +class Asset(proto.Message): + r"""Security Command Center representation of a Google Cloud + resource. + + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All + modifications to an Asset are only within the context of + Security Command Center and don't affect the referenced Google + Cloud resource. + + Attributes: + name (str): + The relative resource name of this asset. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/assets/{asset_id}". + security_center_properties (google.cloud.securitycenter_v1p1beta1.types.Asset.SecurityCenterProperties): + Security Command Center managed properties. + These properties are managed by Security Command + Center and cannot be modified by the user. + resource_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Resource managed properties. These properties + are managed and defined by the Google Cloud + resource and cannot be modified by the user. + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): + User specified security marks. These marks + are entirely managed by the user and come from + the SecurityMarks resource that belongs to the + asset. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was last updated + or added in Cloud SCC. + iam_policy (google.cloud.securitycenter_v1p1beta1.types.Asset.IamPolicy): + Cloud IAM Policy information associated with + the Google Cloud resource described by the + Security Command Center asset. This information + is managed and defined by the Google Cloud + resource and cannot be modified by the user. + canonical_name (str): + The canonical name of the resource. It's either + "organizations/{organization_id}/assets/{asset_id}", + "folders/{folder_id}/assets/{asset_id}" or + "projects/{project_number}/assets/{asset_id}", depending on + the closest CRM ancestor of the resource. + """ + + class SecurityCenterProperties(proto.Message): + r"""Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified by + the user. + + Attributes: + resource_name (str): + The full resource name of the Google Cloud resource this + asset represents. This field is immutable after create time. + See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_type (str): + The type of the Google Cloud resource. + Examples include: APPLICATION, PROJECT, and + ORGANIZATION. This is a case insensitive field + defined by Security Command Center and/or the + producer of the resource and is immutable after + create time. + resource_parent (str): + The full resource name of the immediate parent of the + resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_project (str): + The full resource name of the project the resource belongs + to. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_owners (MutableSequence[str]): + Owners of the Google Cloud resource. + resource_display_name (str): + The user defined display name for this + resource. + resource_parent_display_name (str): + The user defined display name for the parent + of this resource. + resource_project_display_name (str): + The user defined display name for the project + of this resource. + folders (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. + """ + + resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + resource_parent: str = proto.Field( + proto.STRING, + number=3, + ) + resource_project: str = proto.Field( + proto.STRING, + number=4, + ) + resource_owners: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + resource_display_name: str = proto.Field( + proto.STRING, + number=6, + ) + resource_parent_display_name: str = proto.Field( + proto.STRING, + number=7, + ) + resource_project_display_name: str = proto.Field( + proto.STRING, + number=8, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=folder.Folder, + ) + + class IamPolicy(proto.Message): + r"""Cloud IAM Policy information associated with the Google Cloud + resource described by the Security Command Center asset. This + information is managed and defined by the Google Cloud resource + and cannot be modified by the user. + + Attributes: + policy_blob (str): + The JSON representation of the Policy + associated with the asset. See + https://cloud.google.com/iam/docs/reference/rest/v1/Policy + for format details. + """ + + policy_blob: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + security_center_properties: SecurityCenterProperties = proto.Field( + proto.MESSAGE, + number=2, + message=SecurityCenterProperties, + ) + resource_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + iam_policy: IamPolicy = proto.Field( + proto.MESSAGE, + number=11, + message=IamPolicy, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=13, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py new file mode 100644 index 000000000000..8fe9a48e3cfb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + + A finding is a record of assessment data (security, risk, health + or privacy) ingested into Security Command Center for + presentation, notification, analysis, policy testing, and + enforcement. For example, an XSS vulnerability in an App Engine + application is a finding. + + Attributes: + name (str): + The relative resource name of this finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". + parent (str): + The relative resource name of the source the finding belongs + to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. For example: + "organizations/{organization_id}/sources/{source_id}". + resource_name (str): + For findings on Google Cloud resources, the full resource + name of the Google Cloud resource this finding is for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + This field is immutable after creation time. + state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): + The state of the finding. + category (str): + The additional taxonomy group within findings from a given + source. This field is immutable after creation time. + Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the event took place, or + when an update to the finding occurred. For + example, if the finding represents an open + firewall it would capture the time the detector + believes the firewall became open. The accuracy + is determined by the detector. If the finding + were to be resolved afterward, this time would + reflect when the finding was resolved. Must not + be set to a value greater than the current + timestamp. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the finding was created in + Security Command Center. + severity (google.cloud.securitycenter_v1p1beta1.types.Finding.Severity): + The severity of the finding. This field is + managed by the source that writes the finding. + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" + or + "projects/{project_number}/sources/{source_id}/findings/{finding_id}", + depending on the closest CRM ancestor of the resource + associated with the finding. + """ + class State(proto.Enum): + r"""The state of the finding. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + ACTIVE (1): + The finding requires attention and has not + been addressed yet. + INACTIVE (2): + The finding has been fixed, triaged as a + non-issue or otherwise addressed and is no + longer active. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + class Severity(proto.Enum): + r"""The severity of the finding. This field is managed by the + source that writes the finding. + + 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, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + resource_name: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + category: str = proto.Field( + proto.STRING, + number=5, + ) + external_uri: str = proto.Field( + proto.STRING, + number=6, + ) + source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=13, + enum=Severity, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=14, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py new file mode 100644 index 000000000000..17d1a3c450ed --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.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.securitycenter.v1p1beta1', + manifest={ + 'Folder', + }, +) + + +class Folder(proto.Message): + r"""Message that contains the resource name and display name of a + folder resource. + + Attributes: + resource_folder (str): + Full resource name of this folder. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_folder_display_name (str): + The user defined display name for this + folder. + """ + + resource_folder: str = proto.Field( + proto.STRING, + number=1, + ) + resource_folder_display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py new file mode 100644 index 000000000000..8b92401c657b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'NotificationConfig', + }, +) + + +class NotificationConfig(proto.Message): + r"""Security Command Center notification configs. + + A notification config is a Security Command Center resource that + contains the configuration to send notifications for + create/update events of findings, assets and etc. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The relative resource name of this notification config. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/notificationConfigs/notify_public_bucket". + description (str): + The description of the notification config + (max of 1024 characters). + event_type (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.EventType): + The type of events the config is for, e.g. + FINDING. + pubsub_topic (str): + The Pub/Sub topic to send notifications to. Its format is + "projects/[project_id]/topics/[topic]". + service_account (str): + Output only. The service account that needs + "pubsub.topics.publish" permission to publish to + the Pub/Sub topic. + streaming_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.StreamingConfig): + The config for triggering streaming-based + notifications. + + This field is a member of `oneof`_ ``notify_config``. + """ + class EventType(proto.Enum): + r"""The type of events. + + Values: + EVENT_TYPE_UNSPECIFIED (0): + Unspecified event type. + FINDING (1): + Events for findings. + """ + EVENT_TYPE_UNSPECIFIED = 0 + FINDING = 1 + + class StreamingConfig(proto.Message): + r"""The config for streaming-based notifications, which send each + event as soon as it is detected. + + Attributes: + filter (str): + Expression that defines the filter to apply across + create/update events of assets or findings as specified by + the event type. The expression is a list of zero or more + restrictions combined via logical operators ``AND`` and + ``OR``. Parentheses are supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + """ + + filter: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + event_type: EventType = proto.Field( + proto.ENUM, + number=3, + enum=EventType, + ) + pubsub_topic: str = proto.Field( + proto.STRING, + number=4, + ) + service_account: str = proto.Field( + proto.STRING, + number=5, + ) + streaming_config: StreamingConfig = proto.Field( + proto.MESSAGE, + number=6, + oneof='notify_config', + message=StreamingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py new file mode 100644 index 000000000000..5572db1a6d80 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.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.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import resource as gcs_resource + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'NotificationMessage', + }, +) + + +class NotificationMessage(proto.Message): + r"""Security Command Center's Notification + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + notification_config_name (str): + Name of the notification config that + generated current notification. + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + If it's a Finding based notification config, + this field will be populated. + + This field is a member of `oneof`_ ``event``. + resource (google.cloud.securitycenter_v1p1beta1.types.Resource): + The Cloud resource tied to the notification. + """ + + notification_config_name: str = proto.Field( + proto.STRING, + number=1, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=2, + oneof='event', + message=gcs_finding.Finding, + ) + resource: gcs_resource.Resource = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_resource.Resource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py new file mode 100644 index 000000000000..e8a49050b4aa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'OrganizationSettings', + }, +) + + +class OrganizationSettings(proto.Message): + r"""User specified settings that are attached to the Security + Command Center organization. + + Attributes: + name (str): + The relative resource name of the settings. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/organizationSettings". + enable_asset_discovery (bool): + A flag that indicates if Asset Discovery should be enabled. + If the flag is set to ``true``, then discovery of assets + will occur. If it is set to \`false, all historical assets + will remain, but discovery of future assets will not occur. + asset_discovery_config (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig): + The configuration used for Asset Discovery + runs. + """ + + class AssetDiscoveryConfig(proto.Message): + r"""The configuration used for Asset Discovery runs. + + Attributes: + project_ids (MutableSequence[str]): + The project ids to use for filtering asset + discovery. + inclusion_mode (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + The mode to use for filtering asset + discovery. + folder_ids (MutableSequence[str]): + The folder ids to use for filtering asset + discovery. It consists of only digits, e.g., + 756619654966. + """ + class InclusionMode(proto.Enum): + r"""The mode of inclusion when running Asset Discovery. Asset discovery + can be limited by explicitly identifying projects to be included or + excluded. If INCLUDE_ONLY is set, then only those projects within + the organization and their children are discovered during asset + discovery. If EXCLUDE is set, then projects that don't match those + projects are discovered during asset discovery. If neither are set, + then all projects within the organization are discovered during + asset discovery. + + Values: + INCLUSION_MODE_UNSPECIFIED (0): + Unspecified. Setting the mode with this value + will disable inclusion/exclusion filtering for + Asset Discovery. + INCLUDE_ONLY (1): + Asset Discovery will capture only the + resources within the projects specified. All + other resources will be ignored. + EXCLUDE (2): + Asset Discovery will ignore all resources + under the projects specified. All other + resources will be retrieved. + """ + INCLUSION_MODE_UNSPECIFIED = 0 + INCLUDE_ONLY = 1 + EXCLUDE = 2 + + project_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + inclusion_mode: 'OrganizationSettings.AssetDiscoveryConfig.InclusionMode' = proto.Field( + proto.ENUM, + number=2, + enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', + ) + folder_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + enable_asset_discovery: bool = proto.Field( + proto.BOOL, + number=2, + ) + asset_discovery_config: AssetDiscoveryConfig = proto.Field( + proto.MESSAGE, + number=3, + message=AssetDiscoveryConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py new file mode 100644 index 000000000000..2fd5e7836be1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1p1beta1.types import folder + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'Resource', + }, +) + + +class Resource(proto.Message): + r"""Information related to the Google Cloud resource. + + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + project (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The human readable name of project that the + resource belongs to. + parent (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): + Output only. Contains a Folder message for + each folder in the assets ancestry. The first + folder is the deepest nested folder, and the + last folder is the folder directly under the + Organization. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + project: str = proto.Field( + proto.STRING, + number=2, + ) + project_display_name: str = proto.Field( + proto.STRING, + number=3, + ) + parent: str = proto.Field( + proto.STRING, + number=4, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=5, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=folder.Folder, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py new file mode 100644 index 000000000000..10769c100399 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.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 + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'RunAssetDiscoveryResponse', + }, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + + Attributes: + state (google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (google.protobuf.duration_pb2.Duration): + The duration between asset discovery run + start and end + """ + class State(proto.Enum): + r"""The state of an asset discovery run. + + Values: + STATE_UNSPECIFIED (0): + Asset discovery run state was unspecified. + COMPLETED (1): + Asset discovery run completed successfully. + SUPERSEDED (2): + Asset discovery run was cancelled with tasks + still pending, as another run for the same + organization was started with a higher priority. + TERMINATED (3): + Asset discovery run was killed and + terminated. + """ + STATE_UNSPECIFIED = 0 + COMPLETED = 1 + SUPERSEDED = 2 + TERMINATED = 3 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py new file mode 100644 index 000000000000..8473d65602f2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'SecurityMarks', + }, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". + marks (MutableMapping[str, str]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + canonical_name (str): + The canonical name of the marks. Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "folders/{folder_id}/assets/{asset_id}/securityMarks" + "projects/{project_number}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + marks: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py new file mode 100644 index 000000000000..42ec8bf37842 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py @@ -0,0 +1,1641 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1p1beta1.types import asset as gcs_asset +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import folder +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'CreateFindingRequest', + 'CreateNotificationConfigRequest', + 'CreateSourceRequest', + 'DeleteNotificationConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'SetFindingStateRequest', + 'RunAssetDiscoveryRequest', + 'UpdateFindingRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSourceRequest', + 'UpdateSecurityMarksRequest', + }, +) + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + + Attributes: + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + finding_id: str = proto.Field( + proto.STRING, + number=2, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_finding.Finding, + ) + + +class CreateNotificationConfigRequest(proto.Message): + r"""Request message for creating a notification config. + + Attributes: + parent (str): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + config_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + between 1 and 128 characters, and contains + alphanumeric characters, underscores or hyphens + only. + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): + Required. The notification config being + created. The name and the service account will + be ignored as they are both output only fields + on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + config_id: str = proto.Field( + proto.STRING, + number=2, + ) + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_notification_config.NotificationConfig, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + source (google.cloud.securitycenter_v1p1beta1.types.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_source.Source, + ) + + +class DeleteNotificationConfigRequest(proto.Message): + r"""Request message for deleting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetNotificationConfigRequest(proto.Message): + r"""Request message for getting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to get. Its format + is + "organizations/[organization_id]/notificationConfigs/[config_id]". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetOrganizationSettingsRequest(proto.Message): + r"""Request message for getting organization settings. + + Attributes: + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is "organizations/[organization_id]/source/[source_id]". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GroupAssetsRequest(proto.Message): + r"""Request message for grouping by assets. + + Attributes: + parent (str): + Required. Name of the organization to groupBy. Its format is + "organizations/[organization_id], folders/[folder_id], or + projects/[project_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_name_display_name: + ``=``, ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is + not set: + + - security_center_properties.resource_project + - security_center_properties.resource_project_display_name + - security_center_properties.resource_type + - security_center_properties.resource_parent + - security_center_properties.resource_parent_display_name + + The following fields are supported when compare_duration is + set: + + - security_center_properties.resource_type + - security_center_properties.resource_project_display_name + - security_center_properties.resource_parent_display_name + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the GroupResult's + "state_change" property is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at + reference_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and reference_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupAssetsResponse``; + indicates that this is a continuation of a prior + ``GroupAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupAssetsResponse(proto.Message): + r"""Response message for grouping by assets. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + + Attributes: + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + - severity: ``=``, ``:`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping (including ``state_change``). The string value + should follow SQL syntax: comma separated list of fields. + For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + The following fields are supported when compare_duration is + set: + + - state_change + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the GroupResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=struct_pb2.Value, + ) + count: int = proto.Field( + proto.INT64, + number=2, + ) + + +class ListNotificationConfigsRequest(proto.Message): + r"""Request message for listing notification configs. + + Attributes: + parent (str): + Required. Name of the organization to list notification + configs. Its format is "organizations/[organization_id]". + page_token (str): + The value returned by the last + ``ListNotificationConfigsResponse``; indicates that this is + a continuation of a prior ``ListNotificationConfigs`` call, + and that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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 ListNotificationConfigsResponse(proto.Message): + r"""Response message for listing notification configs. + + Attributes: + notification_configs (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.NotificationConfig]): + Notification configs belonging to the + requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + notification_configs: MutableSequence[gcs_notification_config.NotificationConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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=7, + ) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAssetsRequest(proto.Message): + r"""Request message for listing assets. + + Attributes: + parent (str): + Required. Name of the organization assets should belong to. + Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following are the allowed field and operator + combinations: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, + ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,resource_properties.a_property". + Redundant space characters in the syntax are insignificant. + "name desc,resource_properties.a_property" and " name desc , + resource_properties.a_property " are equivalent. + + The following fields are supported: name update_time + resource_properties security_marks.marks + security_center_properties.resource_name + security_center_properties.resource_display_name + security_center_properties.resource_parent + security_center_properties.resource_parent_display_name + security_center_properties.resource_project + security_center_properties.resource_project_display_name + security_center_properties.resource_type + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListAssetsResult's + "state_change" attribute is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at read_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at read_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the ListAssetsResult + fields to be listed in the response. + An empty field mask will list all fields. + page_token (str): + The value returned by the last ``ListAssetsResponse``; + indicates that this is a continuation of a prior + ``ListAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=9, + ) + + +class ListAssetsResponse(proto.Message): + r"""Response message for listing assets. + + Attributes: + list_assets_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of assets matching the + query. + """ + + class ListAssetsResult(proto.Message): + r"""Result containing the Asset and its State. + + Attributes: + asset (google.cloud.securitycenter_v1p1beta1.types.Asset): + Asset matching the search request. + state_change (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult.StateChange): + State change of the asset between the points + in time. + """ + class StateChange(proto.Enum): + r"""The change in state of the asset. + + When querying across two points in time this describes the change + between the two points: ADDED, REMOVED, or ACTIVE. If there was no + compare_duration supplied in the request the state change will be: + UNUSED + + Values: + UNUSED (0): + State change is unused, this is the canonical + default for this enum. + ADDED (1): + Asset was added between the points in time. + REMOVED (2): + Asset was removed between the points in time. + ACTIVE (3): + Asset was present at both point(s) in time. + """ + UNUSED = 0 + ADDED = 1 + REMOVED = 2 + ACTIVE = 3 + + asset: gcs_asset.Asset = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_asset.Asset, + ) + state_change: 'ListAssetsResponse.ListAssetsResult.StateChange' = proto.Field( + proto.ENUM, + number=2, + enum='ListAssetsResponse.ListAssetsResult.StateChange', + ) + + @property + def raw_page(self): + return self + + list_assets_results: MutableSequence[ListAssetsResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListAssetsResult, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + + Attributes: + parent (str): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + - severity: ``=``, ``:`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + security_marks.marks: ``=``, ``:`` source_properties: ``=``, + ``:``, ``>``, ``<``, ``>=``, ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,source_properties.a_property". Redundant + space characters in the syntax are insignificant. "name + desc,source_properties.a_property" and " name desc , + source_properties.a_property " are equivalent. + + The following fields are supported: name parent state + category resource_name event_time source_properties + security_marks.marks + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListFindingsResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added in any state during + the compare_duration period of time that precedes the + read_time. This is the time between (read_time - + compare_duration) and read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the Finding fields to + be listed in the response. An empty field mask + will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=9, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + + Attributes: + list_findings_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult]): + Findings matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + class ListFindingsResult(proto.Message): + r"""Result containing the Finding and its StateChange. + + Attributes: + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Finding matching the search request. + state_change (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.StateChange): + State change of the finding between the + points in time. + resource (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.Resource): + Output only. Resource that is associated with + this finding. + """ + class StateChange(proto.Enum): + r"""The change in state of the finding. + + When querying across two points in time this describes the change in + the finding between the two points: CHANGED, UNCHANGED, ADDED, or + REMOVED. Findings can not be deleted, so REMOVED implies that the + finding at timestamp does not match the filter specified, but it did + at timestamp - compare_duration. If there was no compare_duration + supplied in the request the state change will be: UNUSED + + Values: + UNUSED (0): + State change is unused, this is the canonical + default for this enum. + CHANGED (1): + The finding has changed state in some way + between the points in time and existed at both + points. + UNCHANGED (2): + The finding has not changed state between the + points in time and existed at both points. + ADDED (3): + The finding was created between the points in + time. + REMOVED (4): + The finding at timestamp does not match the filter + specified, but it did at timestamp - compare_duration. + """ + UNUSED = 0 + CHANGED = 1 + UNCHANGED = 2 + ADDED = 3 + REMOVED = 4 + + class Resource(proto.Message): + r"""Information related to the Google Cloud resource that is + associated with this finding. + + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + project_name (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The human readable name of project that the + resource belongs to. + parent_name (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + project_name: str = proto.Field( + proto.STRING, + number=2, + ) + project_display_name: str = proto.Field( + proto.STRING, + number=3, + ) + parent_name: str = proto.Field( + proto.STRING, + number=4, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=5, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=folder.Folder, + ) + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + state_change: 'ListFindingsResponse.ListFindingsResult.StateChange' = proto.Field( + proto.ENUM, + number=2, + enum='ListFindingsResponse.ListFindingsResult.StateChange', + ) + resource: 'ListFindingsResponse.ListFindingsResult.Resource' = proto.Field( + proto.MESSAGE, + number=3, + message='ListFindingsResponse.ListFindingsResult.Resource', + ) + + @property + def raw_page(self): + return self + + list_findings_results: MutableSequence[ListFindingsResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListFindingsResult, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + + Attributes: + name (str): + Required. The relative resource name of the finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): + Required. The desired State of the finding. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the updated state + takes effect. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: gcs_finding.Finding.State = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.State, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class RunAssetDiscoveryRequest(proto.Message): + r"""Request message for running asset discovery for an + organization. + + Attributes: + parent (str): + Required. Name of the organization to run asset discovery + for. Its format is "organizations/[organization_id]". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + + Attributes: + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must be alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing source_properties. + Individual source_properties can be added/updated by using + "source_properties." in the field mask. + """ + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateNotificationConfigRequest(proto.Message): + r"""Request message for updating a notification config. + + Attributes: + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): + Required. The notification config to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + notification config. + If empty all mutable fields will be updated. + """ + + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + + Attributes: + organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + settings resource. + If empty all mutable fields will be updated. + """ + + organization_settings: gcs_organization_settings.OrganizationSettings = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_organization_settings.OrganizationSettings, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (google.cloud.securitycenter_v1p1beta1.types.Source): + Required. The source resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the source + resource. + If empty all mutable fields will be updated. + """ + + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): + Required. The security marks resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If empty + or set to "marks", all marks will be replaced. Individual + marks can be updated using "marks.". + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the updated SecurityMarks + take effect. If not set uses current server + time. Updates will be applied to the + SecurityMarks that are active immediately + preceding this time. + """ + + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_marks.SecurityMarks, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + start_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-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py new file mode 100644 index 000000000000..53b3d04fda40 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'Source', + }, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, etc. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and + outdated/insecure libraries.". + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}", + "folders/{folder_id}/sources/{source_id}" or + "projects/{project_number}/sources/{source_id}", depending + on the closest CRM ancestor of the resource associated with + the finding. + """ + + 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, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=14, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/noxfile.py new file mode 100644 index 000000000000..32b130e85f33 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-securitycenter' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +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"): + 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/securitycenter_v1p1beta1/', + '--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"): + 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", + "grpcio", + "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/securitycenter_v1p1beta1/', + '--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( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): + # Ignore release of mypy 1.11.0 which may have a regression + 'mypy!=1.11.0', + '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-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_async.py new file mode 100644 index 000000000000..9609719bb2ab --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_create_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py new file mode 100644 index 000000000000..a908f103062d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_create_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py new file mode 100644 index 000000000000..ce18ebfeab2a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_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 CreateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_create_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py new file mode 100644 index 000000000000..ec4621a56f92 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_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 CreateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_create_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_async.py new file mode 100644 index 000000000000..a05525b26ae5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_create_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_sync.py new file mode 100644 index 000000000000..53a2606db659 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_create_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py new file mode 100644 index 000000000000..77696925a3b2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_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 DeleteNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py new file mode 100644 index 000000000000..697bd5dc58b7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_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 DeleteNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py new file mode 100644 index 000000000000..0143835b3615 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py new file mode 100644 index 000000000000..fc6a2f9ecd38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py new file mode 100644 index 000000000000..beffb7197acc --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_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 GetNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_get_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py new file mode 100644 index 000000000000..e0bf761c0629 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_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 GetNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_get_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py new file mode 100644 index 000000000000..25b7d03ebdb4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_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 GetOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py new file mode 100644 index 000000000000..94cd60452455 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_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 GetOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_async.py new file mode 100644 index 000000000000..1210ba0c3e4e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_get_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_sync.py new file mode 100644 index 000000000000..942cc4b79272 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_get_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_async.py new file mode 100644 index 000000000000..a487bea8e359 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_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 GroupAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_group_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py new file mode 100644 index 000000000000..c99f19c6389b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_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 GroupAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_group_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_async.py new file mode 100644 index 000000000000..3f65d770b14b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_group_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py new file mode 100644 index 000000000000..f70d29e29a1d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_group_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_async.py new file mode 100644 index 000000000000..55dec3edae30 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_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 ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_list_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py new file mode 100644 index 000000000000..150f9240dedb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_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 ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_list_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_async.py new file mode 100644 index 000000000000..6b7785c3b4f1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_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 securitycenter_v1p1beta1 + + +async def sample_list_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py new file mode 100644 index 000000000000..5a8b07c8466d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_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 securitycenter_v1p1beta1 + + +def sample_list_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py new file mode 100644 index 000000000000..41cdb54d0669 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_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 ListNotificationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py new file mode 100644 index 000000000000..8d8286a62581 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_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 ListNotificationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_async.py new file mode 100644 index 000000000000..261f3b9fcb73 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_list_sources(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py new file mode 100644 index 000000000000..847e73dd0797 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_list_sources(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py new file mode 100644 index 000000000000..47e5c5bb61d7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py new file mode 100644 index 000000000000..fa965b321439 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py new file mode 100644 index 000000000000..4d10d033f247 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_set_finding_state(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py new file mode 100644 index 000000000000..a77fb9ce8347 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_set_finding_state(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py new file mode 100644 index 000000000000..3cd28543769f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py new file mode 100644 index 000000000000..29ba6d93636e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py new file mode 100644 index 000000000000..8b663d640a2f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py new file mode 100644 index 000000000000..b484fc5c8e69 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_async.py new file mode 100644 index 000000000000..6fbcfd65b541 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_update_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py new file mode 100644 index 000000000000..11a3b6e7fac8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_update_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py new file mode 100644 index 000000000000..cc60d07059d3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_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 UpdateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_update_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py new file mode 100644 index 000000000000..1ad9f8ee9c1c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_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 UpdateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_update_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py new file mode 100644 index 000000000000..962efe30b0e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = await client.update_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py new file mode 100644 index 000000000000..007047607a2f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = client.update_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py new file mode 100644 index 000000000000..6f9484b9d009 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_update_security_marks(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py new file mode 100644 index 000000000000..091847a4ef33 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_update_security_marks(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_async.py new file mode 100644 index 000000000000..559623a451be --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_update_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_sync.py new file mode 100644 index 000000000000..5f72d8dd2b64 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_update_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json new file mode 100644 index 000000000000..774592ce11f7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json @@ -0,0 +1,3808 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.securitycenter.v1p1beta1", + "version": "v1p1beta1" + } + ], + "language": "PYTHON", + "name": "google-cloud-securitycenter", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v1p1beta1_generated_security_center_create_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1p1beta1_generated_security_center_create_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "config_id", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "config_id", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1p1beta1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v1p1beta1_generated_security_center_create_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_create_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1p1beta1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v1p1beta1_generated_security_center_create_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_create_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest" + }, + { + "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_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest" + }, + { + "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_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v1p1beta1.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v1p1beta1.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest" + }, + { + "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.securitycenter_v1p1beta1.types.OrganizationSettings", + "shortName": "get_organization_settings" + }, + "description": "Sample for GetOrganizationSettings", + "file": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest" + }, + { + "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.securitycenter_v1p1beta1.types.OrganizationSettings", + "shortName": "get_organization_settings" + }, + "description": "Sample for GetOrganizationSettings", + "file": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest" + }, + { + "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.securitycenter_v1p1beta1.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v1p1beta1_generated_security_center_get_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest" + }, + { + "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.securitycenter_v1p1beta1.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v1p1beta1_generated_security_center_get_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.group_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsAsyncPager", + "shortName": "group_assets" + }, + "description": "Sample for GroupAssets", + "file": "securitycenter_v1p1beta1_generated_security_center_group_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1p1beta1_generated_security_center_group_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.group_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsPager", + "shortName": "group_assets" + }, + "description": "Sample for GroupAssets", + "file": "securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsAsyncPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v1p1beta1_generated_security_center_group_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1p1beta1_generated_security_center_group_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsAsyncPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "securitycenter_v1p1beta1_generated_security_center_list_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1p1beta1_generated_security_center_list_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsAsyncPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v1p1beta1_generated_security_center_list_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1p1beta1_generated_security_center_list_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsAsyncPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesAsyncPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v1p1beta1_generated_security_center_list_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1p1beta1_generated_security_center_list_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.run_asset_discovery", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.RunAssetDiscovery", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "RunAssetDiscovery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "run_asset_discovery" + }, + "description": "Sample for RunAssetDiscovery", + "file": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.run_asset_discovery", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.RunAssetDiscovery", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "RunAssetDiscovery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "run_asset_discovery" + }, + "description": "Sample for RunAssetDiscovery", + "file": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v1p1beta1.types.Finding.State" + }, + { + "name": "start_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v1p1beta1.types.Finding.State" + }, + { + "name": "start_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" + }, + { + "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.securitycenter_v1p1beta1.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v1p1beta1_generated_security_center_update_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1p1beta1_generated_security_center_update_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" + }, + { + "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.securitycenter_v1p1beta1.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" + }, + { + "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.securitycenter_v1p1beta1.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" + }, + { + "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.securitycenter_v1p1beta1.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest" + }, + { + "name": "organization_settings", + "type": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings", + "shortName": "update_organization_settings" + }, + "description": "Sample for UpdateOrganizationSettings", + "file": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest" + }, + { + "name": "organization_settings", + "type": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings", + "shortName": "update_organization_settings" + }, + "description": "Sample for UpdateOrganizationSettings", + "file": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v1p1beta1.types.SecurityMarks" + }, + { + "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.securitycenter_v1p1beta1.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v1p1beta1.types.SecurityMarks" + }, + { + "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.securitycenter_v1p1beta1.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1p1beta1.types.Source" + }, + { + "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.securitycenter_v1p1beta1.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v1p1beta1_generated_security_center_update_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1p1beta1_generated_security_center_update_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1p1beta1.types.Source" + }, + { + "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.securitycenter_v1p1beta1.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v1p1beta1_generated_security_center_update_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1p1beta1_generated_security_center_update_source_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py new file mode 100644 index 000000000000..51a5e411dcfb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py @@ -0,0 +1,198 @@ +#! /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 securitycenterCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_notification_config': ('parent', 'config_id', 'notification_config', ), + 'create_source': ('parent', 'source', ), + 'delete_notification_config': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_notification_config': ('name', ), + 'get_organization_settings': ('name', ), + 'get_source': ('name', ), + 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), + 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), + 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_notification_configs': ('parent', 'page_token', 'page_size', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'run_asset_discovery': ('parent', ), + 'set_finding_state': ('name', 'state', 'start_time', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_notification_config': ('notification_config', 'update_mask', ), + 'update_organization_settings': ('organization_settings', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), + 'update_source': ('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=securitycenterCallTransformer(), +): + """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 securitycenter 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-securitycenter/v1p1beta1/setup.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/setup.py new file mode 100644 index 000000000000..c4538ec101f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/setup.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. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-securitycenter' + + +description = "Google Cloud Securitycenter API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/securitycenter/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", + "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", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__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-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py new file mode 100644 index 000000000000..8de42633a7ea --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py @@ -0,0 +1,18405 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +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 + +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.securitycenter_v1p1beta1.services.security_center import SecurityCenterAsyncClient +from google.cloud.securitycenter_v1p1beta1.services.security_center import SecurityCenterClient +from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1p1beta1.services.security_center import transports +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1p1beta1.types import security_marks +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +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 duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None + assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SecurityCenterClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SecurityCenterGrpcTransport, "grpc"), + (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + 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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + available_transports = [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterRestTransport, + ] + assert transport in available_transports + + transport = SecurityCenterClient.get_transport_class("grpc") + assert transport == transports.SecurityCenterGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, 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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), +]) +def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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_security_center_client_client_options_from_dict(): + with mock.patch('google.cloud.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_create_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object + + request = {} + await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_create_source_async_from_dict(): + await test_create_source_async(request_type=dict) + + +def test_create_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.create_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.create_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + + +def test_create_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + response = client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +def test_create_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.create_finding] = mock_rpc + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object + + request = {} + await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_create_finding_async_from_dict(): + await test_create_finding_async(request_type=dict) + + +def test_create_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + arg = args[0].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + + +def test_create_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + arg = args[0].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateNotificationConfigRequest, + dict, +]) +def test_create_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_create_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateNotificationConfigRequest( + parent='parent_value', + config_id='config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest( + parent='parent_value', + config_id='config_id_value', + ) + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_create_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_notification_config] = mock_object + + request = {} + await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_create_notification_config_async_from_dict(): + await test_create_notification_config_async(request_type=dict) + + +def test_create_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.create_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.create_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_notification_config( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + # Establish that the 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].config_id + mock_val = 'config_id_value' + assert arg == mock_val + arg = args[0].notification_config + mock_val = gcs_notification_config.NotificationConfig(name='name_value') + assert arg == mock_val + + +def test_create_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_notification_config( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + # Establish that 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].config_id + mock_val = 'config_id_value' + assert arg == mock_val + arg = args[0].notification_config + mock_val = gcs_notification_config.NotificationConfig(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_notification_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, +]) +def test_delete_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteNotificationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest( + name='name_value', + ) + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_delete_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_notification_config] = mock_object + + request = {} + await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteNotificationConfigRequest() + 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_config_async_from_dict(): + await test_delete_notification_config_async(request_type=dict) + + +def test_delete_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = None + client.delete_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_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_notification_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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_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_notification_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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_notification_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.GetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest( + resource='resource_value', + ) + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object + + request = {} + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetNotificationConfigRequest, + dict, +]) +def test_get_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_get_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetNotificationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest( + name='name_value', + ) + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_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_notification_config] = mock_rpc + request = {} + client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_get_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_notification_config] = mock_object + + request = {} + await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_get_notification_config_async_from_dict(): + await test_get_notification_config_async(request_type=dict) + + +def test_get_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = notification_config.NotificationConfig() + client.get_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + await client.get_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_notification_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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_notification_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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_notification_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetOrganizationSettingsRequest, + dict, +]) +def test_get_organization_settings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_get_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetOrganizationSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_organization_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest( + name='name_value', + ) + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_organization_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_organization_settings] = mock_rpc + request = {} + client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_organization_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_organization_settings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + +@pytest.mark.asyncio +async def test_get_organization_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_organization_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_organization_settings] = mock_object + + request = {} + await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_organization_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_get_organization_settings_async_from_dict(): + await test_get_organization_settings_async(request_type=dict) + + +def test_get_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = organization_settings.OrganizationSettings() + client.get_organization_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_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + await client.get_organization_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_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_organization_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_organization_settings_flattened_error(): + client = SecurityCenterClient( + credentials=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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_organization_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_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_get_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest( + name='name_value', + ) + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + +@pytest.mark.asyncio +async def test_get_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object + + request = {} + await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_get_source_async_from_dict(): + await test_get_source_async(request_type=dict) + + +def test_get_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = source.Source() + client.get_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + await client.get_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_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_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupAssetsRequest, + dict, +]) +def test_group_assets(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_assets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + +def test_group_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupAssetsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc + request = {} + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_group_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + +@pytest.mark.asyncio +async def test_group_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_assets] = mock_object + + request = {} + await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_assets_async_from_dict(): + await test_group_assets_async(request_type=dict) + + +def test_group_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = securitycenter_service.GroupAssetsResponse() + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_group_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) + await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_group_assets_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_assets(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, securitycenter_service.GroupResult) + for i in results) +def test_group_assets_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_assets(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_group_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_assets(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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_assets(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", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + +@pytest.mark.asyncio +async def test_group_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_findings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object + + request = {} + await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_findings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_findings_async_from_dict(): + await test_group_findings_async(request_type=dict) + + +def test_group_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = securitycenter_service.GroupFindingsResponse() + client.group_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_group_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + await client.group_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_group_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that the 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + + +def test_group_findings_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + +@pytest.mark.asyncio +async def test_group_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_group_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_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, securitycenter_service.GroupResult) + for i in results) +def test_group_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_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_group_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_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", [ + securitycenter_service.ListAssetsRequest, + dict, +]) +def test_list_assets(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_assets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + +def test_list_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListAssetsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_value', + page_token='page_token_value', + ) + +def test_list_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + +@pytest.mark.asyncio +async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object + + request = {} + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + + +def test_list_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = securitycenter_service.ListAssetsResponse() + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_assets_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_assets( + 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_assets_flattened_error(): + client = SecurityCenterClient( + credentials=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_assets( + securitycenter_service.ListAssetsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_assets_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_assets( + 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_assets_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_assets( + securitycenter_service.ListAssetsRequest(), + parent='parent_value', + ) + + +def test_list_assets_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) +def test_list_assets_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(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_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + 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_assets(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", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +def test_list_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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] == securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + +@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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object + + request = {} + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +@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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( + 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 = securitycenter_service.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', + ) + + # Establish that the 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_findings_flattened_error(): + client = SecurityCenterClient( + credentials=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( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_findings_flattened_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.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', + ) + + # Establish that 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_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_findings( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + + +def test_list_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in results) +def test_list_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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 = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_findings_async_pages(): + client = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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", [ + securitycenter_service.ListNotificationConfigsRequest, + dict, +]) +def test_list_notification_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListNotificationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_notification_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListNotificationConfigsRequest( + 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_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notification_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_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_notification_configs] = mock_rpc + request = {} + client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_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_notification_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + +@pytest.mark.asyncio +async def test_list_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_notification_configs] = mock_object + + request = {} + await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_notification_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListNotificationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_from_dict(): + await test_list_notification_configs_async(request_type=dict) + + +def test_list_notification_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + 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_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + client.list_notification_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_notification_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + 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_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + await client.list_notification_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_notification_configs_flattened(): + client = SecurityCenterClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_notification_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_notification_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_notification_configs_flattened_async(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_notification_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_notification_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_notification_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + 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_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, notification_config.NotificationConfig) + for i in results) +def test_list_notification_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_notification_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_notification_configs_async_pager(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_notification_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, notification_config.NotificationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_pages(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + 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_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", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListSourcesRequest( + 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_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + +@pytest.mark.asyncio +async def test_list_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_sources in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object + + request = {} + await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_sources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sources_async_from_dict(): + await test_list_sources_async(request_type=dict) + + +def test_list_sources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = securitycenter_service.ListSourcesResponse() + client.list_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_sources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + await client.list_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_sources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_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_sources_flattened_error(): + client = SecurityCenterClient( + credentials=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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_sources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_sources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_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, source.Source) + for i in results) +def test_list_sources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = list(client.list_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_sources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_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, source.Source) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_sources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + 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_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", [ + securitycenter_service.RunAssetDiscoveryRequest, + dict, +]) +def test_run_asset_discovery(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.RunAssetDiscoveryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_asset_discovery_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + +def test_run_asset_discovery_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.RunAssetDiscoveryRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_asset_discovery(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest( + parent='parent_value', + ) + +def test_run_asset_discovery_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_asset_discovery in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc + request = {} + client.run_asset_discovery(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.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_run_asset_discovery_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + +@pytest.mark.asyncio +async def test_run_asset_discovery_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.run_asset_discovery in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.run_asset_discovery] = mock_object + + request = {} + await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.RunAssetDiscoveryRequest() + 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_run_asset_discovery_async_from_dict(): + await test_run_asset_discovery_async(request_type=dict) + + +def test_run_asset_discovery_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_asset_discovery_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_run_asset_discovery_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery( + 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_run_asset_discovery_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_run_asset_discovery_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery( + 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_run_asset_discovery_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + response = client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +def test_set_finding_state_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + +@pytest.mark.asyncio +async def test_set_finding_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object + + request = {} + await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_finding_state(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_set_finding_state_async_from_dict(): + await test_set_finding_state_async(request_type=dict) + + +def test_set_finding_state_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = finding.Finding() + client.set_finding_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_set_finding_state_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_finding_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_set_finding_state_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.SetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest( + resource='resource_value', + ) + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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( + version=774, + etag=b'etag_blob', + )) + response = await client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object + + request = {} + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = SecurityCenterClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.TestIamPermissionsRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( + resource='resource_value', + ) + +def test_test_iam_permissions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object + + request = {} + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + response = client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +def test_update_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateFindingRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.update_finding] = mock_rpc + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object + + request = {} + await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_finding_async_from_dict(): + await test_update_finding_async(request_type=dict) + + +def test_update_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +def test_update_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_finding( + finding=gcs_finding.Finding(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].finding + mock_val = gcs_finding.Finding(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_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_finding( + finding=gcs_finding.Finding(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].finding + mock_val = gcs_finding.Finding(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_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, +]) +def test_update_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_update_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateNotificationConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest( + ) + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_update_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_notification_config] = mock_object + + request = {} + await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_update_notification_config_async_from_dict(): + await test_update_notification_config_async(request_type=dict) + + +def test_update_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.update_notification_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', + 'notification_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.update_notification_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', + 'notification_config.name=name_value', + ) in kw['metadata'] + + +def test_update_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_notification_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateOrganizationSettingsRequest, + dict, +]) +def test_update_organization_settings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_update_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateOrganizationSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_organization_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest( + ) + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_organization_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_organization_settings] = mock_rpc + request = {} + client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_organization_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_organization_settings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + +@pytest.mark.asyncio +async def test_update_organization_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_organization_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_organization_settings] = mock_object + + request = {} + await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_organization_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_update_organization_settings_async_from_dict(): + await test_update_organization_settings_async(request_type=dict) + + +def test_update_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = gcs_organization_settings.OrganizationSettings() + client.update_organization_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', + 'organization_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + await client.update_organization_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', + 'organization_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].organization_settings + mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') + assert arg == mock_val + + +def test_update_organization_settings_flattened_error(): + client = SecurityCenterClient( + credentials=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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].organization_settings + mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSourceRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object + + request = {} + await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_source_async_from_dict(): + await test_update_source_async(request_type=dict) + + +def test_update_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +def test_update_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_source( + source=gcs_source.Source(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].source + mock_val = gcs_source.Source(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_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_source( + source=gcs_source.Source(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].source + mock_val = gcs_source.Source(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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + response = client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_security_marks_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + +def test_update_security_marks_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSecurityMarksRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( + ) + +def test_update_security_marks_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish that a new wrapper 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_security_marks_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + +@pytest.mark.asyncio +async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_marks in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object + + request = {} + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_security_marks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_security_marks_async_from_dict(): + await test_update_security_marks_async(request_type=dict) + + +def test_update_security_marks_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = gcs_security_marks.SecurityMarks() + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_marks_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +def test_update_security_marks_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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].security_marks + mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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].security_marks + mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.CreateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_source(request) + + +def test_create_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1p1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_create_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +def test_create_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request_init["finding"] = {'name': 'name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.create_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.create_finding] = mock_rpc + + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["finding_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 "findingId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "findingId" in jsonified_request + assert jsonified_request["findingId"] == request_init["finding_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["findingId"] = 'finding_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request + assert jsonified_request["findingId"] == 'finding_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.create_finding(request) + + expected_params = [ + ( + "findingId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.CreateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_finding(request) + + +def test_create_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(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 = gcs_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.create_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/v1p1beta1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) + + +def test_create_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_create_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateNotificationConfigRequest, + dict, +]) +def test_create_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["notification_config"] = {'name': 'name_value', 'description': 'description_value', 'event_type': 1, 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.CreateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.CreateNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["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 "configId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "configId" in jsonified_request + assert jsonified_request["configId"] == request_init["config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["configId"] = 'config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("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 "configId" in jsonified_request + assert jsonified_request["configId"] == 'config_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ( + "configId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("configId", )) & set(("parent", "configId", "notificationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateNotificationConfigRequest.pb(securitycenter_service.CreateNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) + + request = securitycenter_service.CreateNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.create_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_notification_config(request) + + +def test_create_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/v1p1beta1/{parent=organizations/*}/notificationConfigs" % client.transport._host, args[1]) + + +def test_create_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + +def test_create_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, +]) +def test_delete_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/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 = 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_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.DeleteNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_notification_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteNotificationConfigRequest.pb(securitycenter_service.DeleteNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_notification_config(request) + + +def test_delete_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/notificationConfigs/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_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/v1p1beta1/{name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +def test_delete_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.get_iam_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/v1p1beta1/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetNotificationConfigRequest, + dict, +]) +def test_get_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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_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_notification_config] = mock_rpc + + request = {} + client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.GetNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetNotificationConfigRequest.pb(securitycenter_service.GetNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = notification_config.NotificationConfig.to_json(notification_config.NotificationConfig()) + + request = securitycenter_service.GetNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = notification_config.NotificationConfig() + + client.get_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_notification_config(request) + + +def test_get_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig.pb(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_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/v1p1beta1/{name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_get_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +def test_get_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetOrganizationSettingsRequest, + dict, +]) +def test_get_organization_settings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/organizationSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_organization_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_organization_settings] = mock_rpc + + request = {} + client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.GetOrganizationSettingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_organization_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_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_organization_settings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_organization_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_organization_settings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_organization_settings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_organization_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetOrganizationSettingsRequest.pb(securitycenter_service.GetOrganizationSettingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = organization_settings.OrganizationSettings.to_json(organization_settings.OrganizationSettings()) + + request = securitycenter_service.GetOrganizationSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = organization_settings.OrganizationSettings() + + client.get_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/organizationSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_organization_settings(request) + + +def test_get_organization_settings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/organizationSettings'} + + # get truthy value for each flattened field + mock_args = dict( + 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 = organization_settings.OrganizationSettings.pb(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_organization_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/v1p1beta1/{name=organizations/*/organizationSettings}" % client.transport._host, args[1]) + + +def test_get_organization_settings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +def test_get_organization_settings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/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 = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = source.Source.to_json(source.Source()) + + request = securitycenter_service.GetSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = source.Source() + + client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_source(request) + + +def test_get_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v1p1beta1/{name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_get_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +def test_get_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupAssetsRequest, + dict, +]) +def test_group_assets_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_group_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc + + request = {} + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_group_assets_rest_required_fields(request_type=securitycenter_service.GroupAssetsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_assets_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_assets_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_assets") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupAssetsRequest.pb(securitycenter_service.GroupAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupAssetsResponse.to_json(securitycenter_service.GroupAssetsResponse()) + + request = securitycenter_service.GroupAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupAssetsResponse() + + client.group_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_assets(request) + + +def test_group_assets_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupAssetsResponse.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': 'organizations/sample1'} + + pager = client.group_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_findings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) + + request = securitycenter_service.GroupFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupFindingsResponse() + + client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_findings(request) + + +def test_group_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + group_by='group_by_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v1p1beta1/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) + + +def test_group_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} + + pager = client.group_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_findings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListAssetsRequest, + dict, +]) +def test_list_assets_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListAssetsResponse.pb(return_value) + 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_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_list_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish 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_assets_rest_required_fields(request_type=securitycenter_service.ListAssetsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_assets._get_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_assets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) + jsonified_request.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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListAssetsResponse.pb(return_value) + 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_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_assets_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_assets_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_assets") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListAssetsRequest.pb(securitycenter_service.ListAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListAssetsResponse.to_json(securitycenter_service.ListAssetsResponse()) + + request = securitycenter_service.ListAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListAssetsResponse() + + client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_assets(request) + + +def test_list_assets_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAssetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse.pb(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_assets(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1p1beta1/{parent=organizations/*}/assets" % client.transport._host, args[1]) + + +def test_list_assets_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_assets( + securitycenter_service.ListAssetsRequest(), + parent='parent_value', + ) + + +def test_list_assets_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListAssetsResponse.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': 'organizations/sample1'} + + pager = client.list_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) + + pages = list(client.list_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.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' + assert response.total_size == 1086 + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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=securitycenter_service.ListFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) + jsonified_request.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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.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 = securitycenter_service.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 = [ + ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) + + request = securitycenter_service.ListFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListFindingsResponse() + + client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_findings(request) + + +def test_list_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.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/v1p1beta1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) + + +def test_list_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + + +def test_list_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} + + pager = client.list_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) + 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 + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListNotificationConfigsRequest, + dict, +]) +def test_list_notification_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) + 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_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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_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_notification_configs] = mock_rpc + + request = {} + client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_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_notification_configs_rest_required_fields(request_type=securitycenter_service.ListNotificationConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListNotificationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) + 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_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_notification_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_notification_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_notification_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_notification_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_notification_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListNotificationConfigsRequest.pb(securitycenter_service.ListNotificationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListNotificationConfigsResponse.to_json(securitycenter_service.ListNotificationConfigsResponse()) + + request = securitycenter_service.ListNotificationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListNotificationConfigsResponse() + + client.list_notification_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_notification_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_notification_configs(request) + + +def test_list_notification_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListNotificationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse.pb(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_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/v1p1beta1/{parent=organizations/*}/notificationConfigs" % client.transport._host, args[1]) + + +def test_list_notification_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListNotificationConfigsResponse.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': 'organizations/sample1'} + + pager = client.list_notification_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, notification_config.NotificationConfig) + for i in results) + + pages = list(client.list_notification_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_sources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_sources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) + + request = securitycenter_service.ListSourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListSourcesResponse() + + client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_sources(request) + + +def test_list_sources_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v1p1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_list_sources_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} + + pager = client.list_sources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, source.Source) + for i in results) + + pages = list(client.list_sources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.RunAssetDiscoveryRequest, + dict, +]) +def test_run_asset_discovery_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') + + # 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 + response = client.run_asset_discovery(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_run_asset_discovery_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_asset_discovery in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc + + request = {} + client.run_asset_discovery(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.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_run_asset_discovery_rest_required_fields(request_type=securitycenter_service.RunAssetDiscoveryRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_asset_discovery._get_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()).run_asset_discovery._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 = SecurityCenterClient( + 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.run_asset_discovery(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_run_asset_discovery_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.run_asset_discovery._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_asset_discovery_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_run_asset_discovery") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_run_asset_discovery") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.RunAssetDiscoveryRequest.pb(securitycenter_service.RunAssetDiscoveryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = securitycenter_service.RunAssetDiscoveryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.run_asset_discovery(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_asset_discovery_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.run_asset_discovery(request) + + +def test_run_asset_discovery_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.run_asset_discovery(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1p1beta1/{parent=organizations/*}/assets:runDiscovery" % client.transport._host, args[1]) + + +def test_run_asset_discovery_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +def test_run_asset_discovery_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + + # 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 + response = client.set_finding_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( + 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': "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 = 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.set_finding_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_finding_state_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_finding_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "state", "startTime", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_finding_state_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetFindingStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_finding_state(request) + + +def test_set_finding_state_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + mock_args.update(sample_request) + + # 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.set_finding_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/v1p1beta1/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) + + +def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +def test_set_finding_state_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.set_iam_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/v1p1beta1/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # 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 + response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_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.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1p1beta1/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.update_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.update_finding] = mock_rpc + + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_finding._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_finding._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.update_finding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.UpdateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_finding(request) + + +def test_update_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + finding=gcs_finding.Finding(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 = gcs_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.update_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/v1p1beta1/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) + + +def test_update_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, +]) +def test_update_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} + request_init["notification_config"] = {'name': 'organizations/sample1/notificationConfigs/sample2', 'description': 'description_value', 'event_type': 1, 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.UpdateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.UpdateNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("notificationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateNotificationConfigRequest.pb(securitycenter_service.UpdateNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) + + request = securitycenter_service.UpdateNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.update_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_notification_config(request) + + +def test_update_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/v1p1beta1/{notification_config.name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_update_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateOrganizationSettingsRequest, + dict, +]) +def test_update_organization_settings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + request_init["organization_settings"] = {'name': 'organizations/sample1/organizationSettings', 'enable_asset_discovery': True, 'asset_discovery_config': {'project_ids': ['project_ids_value1', 'project_ids_value2'], 'inclusion_mode': 1, 'folder_ids': ['folder_ids_value1', 'folder_ids_value2']}} + # The version of a generated dependency at test runtime may differ from the version used 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 = securitycenter_service.UpdateOrganizationSettingsRequest.meta.fields["organization_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["organization_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["organization_settings"][field])): + del request_init["organization_settings"][field][i][subfield] + else: + del request_init["organization_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 = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_organization_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_organization_settings] = mock_rpc + + request = {} + client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_organization_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_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_organization_settings.OrganizationSettings() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_organization_settings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_organization_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("organizationSettings", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_organization_settings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_organization_settings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_organization_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateOrganizationSettingsRequest.pb(securitycenter_service.UpdateOrganizationSettingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_organization_settings.OrganizationSettings.to_json(gcs_organization_settings.OrganizationSettings()) + + request = securitycenter_service.UpdateOrganizationSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_organization_settings.OrganizationSettings() + + client.update_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_organization_settings(request) + + +def test_update_organization_settings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_organization_settings.OrganizationSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + organization_settings=gcs_organization_settings.OrganizationSettings(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 = gcs_organization_settings.OrganizationSettings.pb(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_organization_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/v1p1beta1/{organization_settings.name=organizations/*/organizationSettings}" % client.transport._host, args[1]) + + +def test_update_organization_settings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +def test_update_organization_settings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.UpdateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_source(request) + + +def test_update_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1p1beta1/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_update_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + request_init["security_marks"] = {'name': 'organizations/sample1/assets/sample2/securityMarks', 'marks': {}, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] + + 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["security_marks"].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["security_marks"][field])): + del request_init["security_marks"][field][i][subfield] + else: + del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + +def test_update_security_marks_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_security_marks._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_security_marks._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("start_time", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_security_marks_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_security_marks._get_unset_required_fields({}) + assert set(unset_fields) == (set(("startTime", "updateMask", )) & set(("securityMarks", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_security_marks_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) + + request = securitycenter_service.UpdateSecurityMarksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_security_marks.SecurityMarks() + + client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_security_marks(request) + + +def test_update_security_marks_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + + # get arguments that satisfy an http rule for this method + sample_request = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + + # get truthy value for each flattened field + mock_args = dict( + security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1p1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}" % client.transport._host, args[1]) + + +def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_security_marks_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SecurityCenterClient( + 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 = SecurityCenterClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecurityCenterClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, +]) +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() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SecurityCenterClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecurityCenterGrpcTransport, + ) + +def test_security_center_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_security_center_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_source', + 'create_finding', + 'create_notification_config', + 'delete_notification_config', + 'get_iam_policy', + 'get_notification_config', + 'get_organization_settings', + 'get_source', + 'group_assets', + 'group_findings', + 'list_assets', + 'list_findings', + 'list_notification_configs', + 'list_sources', + 'run_asset_discovery', + 'set_finding_state', + 'set_iam_policy', + 'test_iam_permissions', + 'update_finding', + 'update_notification_config', + 'update_organization_settings', + 'update_source', + 'update_security_marks', + ) + 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_security_center_base_transport_with_credentials_file(): + # Instantiate the 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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + 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_security_center_base_transport_with_adc(): + # Test the default 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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +def test_security_center_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) + SecurityCenterClient() + 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_transport_auth_adc(transport_class): + # If 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, + ], +) +def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_security_center_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host 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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_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.SecurityCenterRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_security_center_rest_lro_client(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a 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 + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_no_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_with_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_security_center_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SecurityCenterClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SecurityCenterClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_source._session + session2 = client2.transport.create_source._session + assert session1 != session2 + session1 = client1.transport.create_finding._session + session2 = client2.transport.create_finding._session + assert session1 != session2 + session1 = client1.transport.create_notification_config._session + session2 = client2.transport.create_notification_config._session + assert session1 != session2 + session1 = client1.transport.delete_notification_config._session + session2 = client2.transport.delete_notification_config._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.get_notification_config._session + session2 = client2.transport.get_notification_config._session + assert session1 != session2 + session1 = client1.transport.get_organization_settings._session + session2 = client2.transport.get_organization_settings._session + assert session1 != session2 + session1 = client1.transport.get_source._session + session2 = client2.transport.get_source._session + assert session1 != session2 + session1 = client1.transport.group_assets._session + session2 = client2.transport.group_assets._session + assert session1 != session2 + session1 = client1.transport.group_findings._session + session2 = client2.transport.group_findings._session + assert session1 != session2 + session1 = client1.transport.list_assets._session + session2 = client2.transport.list_assets._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_notification_configs._session + session2 = client2.transport.list_notification_configs._session + assert session1 != session2 + session1 = client1.transport.list_sources._session + session2 = client2.transport.list_sources._session + assert session1 != session2 + session1 = client1.transport.run_asset_discovery._session + session2 = client2.transport.run_asset_discovery._session + assert session1 != session2 + session1 = client1.transport.set_finding_state._session + session2 = client2.transport.set_finding_state._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 + session1 = client1.transport.update_finding._session + session2 = client2.transport.update_finding._session + assert session1 != session2 + session1 = client1.transport.update_notification_config._session + session2 = client2.transport.update_notification_config._session + assert session1 != session2 + session1 = client1.transport.update_organization_settings._session + session2 = client2.transport.update_organization_settings._session + assert session1 != session2 + session1 = client1.transport.update_source._session + session2 = client2.transport.update_source._session + assert session1 != session2 + session1 = client1.transport.update_security_marks._session + session2 = client2.transport.update_security_marks._session + assert session1 != session2 +def test_security_center_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcTransport( + 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_security_center_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcAsyncIOTransport( + 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(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_security_center_grpc_lro_client(): + client = SecurityCenterClient( + 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_security_center_grpc_lro_async_client(): + client = SecurityCenterAsyncClient( + 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_asset_path(): + organization = "squid" + asset = "clam" + expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.asset_path(organization, asset) + assert expected == actual + + +def test_parse_asset_path(): + expected = { + "organization": "whelk", + "asset": "octopus", + } + path = SecurityCenterClient.asset_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_asset_path(path) + assert expected == actual + +def test_finding_path(): + organization = "oyster" + source = "nudibranch" + finding = "cuttlefish" + expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + actual = SecurityCenterClient.finding_path(organization, source, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "organization": "mussel", + "source": "winkle", + "finding": "nautilus", + } + path = SecurityCenterClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_finding_path(path) + assert expected == actual + +def test_notification_config_path(): + organization = "scallop" + notification_config = "abalone" + expected = "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) + actual = SecurityCenterClient.notification_config_path(organization, notification_config) + assert expected == actual + + +def test_parse_notification_config_path(): + expected = { + "organization": "squid", + "notification_config": "clam", + } + path = SecurityCenterClient.notification_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_notification_config_path(path) + assert expected == actual + +def test_organization_settings_path(): + organization = "whelk" + expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) + actual = SecurityCenterClient.organization_settings_path(organization) + assert expected == actual + + +def test_parse_organization_settings_path(): + expected = { + "organization": "octopus", + } + path = SecurityCenterClient.organization_settings_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_organization_settings_path(path) + assert expected == actual + +def test_security_marks_path(): + organization = "oyster" + asset = "nudibranch" + expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.security_marks_path(organization, asset) + assert expected == actual + + +def test_parse_security_marks_path(): + expected = { + "organization": "cuttlefish", + "asset": "mussel", + } + path = SecurityCenterClient.security_marks_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_marks_path(path) + assert expected == actual + +def test_source_path(): + organization = "winkle" + source = "nautilus" + expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + actual = SecurityCenterClient.source_path(organization, source) + assert expected == actual + + +def test_parse_source_path(): + expected = { + "organization": "scallop", + "source": "abalone", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_path(path) + assert expected == actual + +def test_topic_path(): + project = "squid" + topic = "clam" + expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + actual = SecurityCenterClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "whelk", + "topic": "octopus", + } + path = SecurityCenterClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_topic_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SecurityCenterClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = SecurityCenterClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = SecurityCenterClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = SecurityCenterClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SecurityCenterClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = SecurityCenterClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = SecurityCenterClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = SecurityCenterClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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 = SecurityCenterClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = SecurityCenterClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + transport_class = SecurityCenterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), +]) +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-securitycenter/v2/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v2/.coveragerc new file mode 100644 index 000000000000..45cb273f8f7c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/securitycenter/__init__.py + google/cloud/securitycenter/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-securitycenter/v2/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v2/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v2/MANIFEST.in new file mode 100644 index 000000000000..7d0a7010fae0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/securitycenter *.py +recursive-include google/cloud/securitycenter_v2 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/README.rst b/owl-bot-staging/google-cloud-securitycenter/v2/README.rst new file mode 100644 index 000000000000..f8c63f4cb48a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v2/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v2/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v2/docs/conf.py new file mode 100644 index 000000000000..8e92d2319721 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter 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-securitycenter" +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-securitycenter-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-securitycenter.tex", + u"google-cloud-securitycenter 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-securitycenter", + u"Google Cloud Securitycenter 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-securitycenter", + u"google-cloud-securitycenter Documentation", + author, + "google-cloud-securitycenter", + "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v2/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/index.rst new file mode 100644 index 000000000000..af3ca0f134f0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + securitycenter_v2/services + securitycenter_v2/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst new file mode 100644 index 000000000000..6b9d3b9b1795 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst @@ -0,0 +1,10 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v2.services.security_center + :members: + :inherited-members: + +.. automodule:: google.cloud.securitycenter_v2.services.security_center.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst new file mode 100644 index 000000000000..adb8a6096090 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v2 API +=============================================== +.. toctree:: + :maxdepth: 2 + + security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst new file mode 100644 index 000000000000..3210d372fb24 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Securitycenter v2 API +============================================ + +.. automodule:: google.cloud.securitycenter_v2.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py new file mode 100644 index 000000000000..121fb285646b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py @@ -0,0 +1,257 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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.securitycenter import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.securitycenter_v2.services.security_center.client import SecurityCenterClient +from google.cloud.securitycenter_v2.services.security_center.async_client import SecurityCenterAsyncClient + +from google.cloud.securitycenter_v2.types.access import Access +from google.cloud.securitycenter_v2.types.access import Geolocation +from google.cloud.securitycenter_v2.types.access import ServiceAccountDelegationInfo +from google.cloud.securitycenter_v2.types.application import Application +from google.cloud.securitycenter_v2.types.attack_exposure import AttackExposure +from google.cloud.securitycenter_v2.types.attack_path import AttackPath +from google.cloud.securitycenter_v2.types.backup_disaster_recovery import BackupDisasterRecovery +from google.cloud.securitycenter_v2.types.bigquery_export import BigQueryExport +from google.cloud.securitycenter_v2.types.cloud_armor import AdaptiveProtection +from google.cloud.securitycenter_v2.types.cloud_armor import Attack +from google.cloud.securitycenter_v2.types.cloud_armor import CloudArmor +from google.cloud.securitycenter_v2.types.cloud_armor import Requests +from google.cloud.securitycenter_v2.types.cloud_armor import SecurityPolicy +from google.cloud.securitycenter_v2.types.cloud_dlp_data_profile import CloudDlpDataProfile +from google.cloud.securitycenter_v2.types.cloud_dlp_inspection import CloudDlpInspection +from google.cloud.securitycenter_v2.types.compliance import Compliance +from google.cloud.securitycenter_v2.types.connection import Connection +from google.cloud.securitycenter_v2.types.contact_details import Contact +from google.cloud.securitycenter_v2.types.contact_details import ContactDetails +from google.cloud.securitycenter_v2.types.container import Container +from google.cloud.securitycenter_v2.types.database import Database +from google.cloud.securitycenter_v2.types.exfiltration import ExfilResource +from google.cloud.securitycenter_v2.types.exfiltration import Exfiltration +from google.cloud.securitycenter_v2.types.external_system import ExternalSystem +from google.cloud.securitycenter_v2.types.file import File +from google.cloud.securitycenter_v2.types.finding import Finding +from google.cloud.securitycenter_v2.types.folder import Folder +from google.cloud.securitycenter_v2.types.group_membership import GroupMembership +from google.cloud.securitycenter_v2.types.iam_binding import IamBinding +from google.cloud.securitycenter_v2.types.indicator import Indicator +from google.cloud.securitycenter_v2.types.kernel_rootkit import KernelRootkit +from google.cloud.securitycenter_v2.types.kubernetes import Kubernetes +from google.cloud.securitycenter_v2.types.label import Label +from google.cloud.securitycenter_v2.types.load_balancer import LoadBalancer +from google.cloud.securitycenter_v2.types.log_entry import CloudLoggingEntry +from google.cloud.securitycenter_v2.types.log_entry import LogEntry +from google.cloud.securitycenter_v2.types.mitre_attack import MitreAttack +from google.cloud.securitycenter_v2.types.mute_config import MuteConfig +from google.cloud.securitycenter_v2.types.notebook import Notebook +from google.cloud.securitycenter_v2.types.notification_config import NotificationConfig +from google.cloud.securitycenter_v2.types.notification_message import NotificationMessage +from google.cloud.securitycenter_v2.types.org_policy import OrgPolicy +from google.cloud.securitycenter_v2.types.process import EnvironmentVariable +from google.cloud.securitycenter_v2.types.process import Process +from google.cloud.securitycenter_v2.types.resource import AwsMetadata +from google.cloud.securitycenter_v2.types.resource import AzureMetadata +from google.cloud.securitycenter_v2.types.resource import GcpMetadata +from google.cloud.securitycenter_v2.types.resource import Resource +from google.cloud.securitycenter_v2.types.resource import ResourcePath +from google.cloud.securitycenter_v2.types.resource import CloudProvider +from google.cloud.securitycenter_v2.types.resource_value_config import ResourceValueConfig +from google.cloud.securitycenter_v2.types.resource_value_config import ResourceValue +from google.cloud.securitycenter_v2.types.security_marks import SecurityMarks +from google.cloud.securitycenter_v2.types.security_posture import SecurityPosture +from google.cloud.securitycenter_v2.types.securitycenter_service import BatchCreateResourceValueConfigsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import BatchCreateResourceValueConfigsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import BulkMuteFindingsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import BulkMuteFindingsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import CreateBigQueryExportRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import CreateFindingRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import CreateMuteConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import CreateNotificationConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import CreateResourceValueConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import CreateSourceRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteBigQueryExportRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteMuteConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteNotificationConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteResourceValueConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetBigQueryExportRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetMuteConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetNotificationConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetResourceValueConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetSimulationRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetSourceRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetValuedResourceRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GroupFindingsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GroupFindingsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import GroupResult +from google.cloud.securitycenter_v2.types.securitycenter_service import ListAttackPathsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListAttackPathsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListBigQueryExportsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListBigQueryExportsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListFindingsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListFindingsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListMuteConfigsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListMuteConfigsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListNotificationConfigsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListNotificationConfigsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListResourceValueConfigsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListResourceValueConfigsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListSourcesRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListSourcesResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListValuedResourcesRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListValuedResourcesResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import SetFindingStateRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import SetMuteRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateBigQueryExportRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateExternalSystemRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateFindingRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateMuteConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateNotificationConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateResourceValueConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateSecurityMarksRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateSourceRequest +from google.cloud.securitycenter_v2.types.simulation import Simulation +from google.cloud.securitycenter_v2.types.source import Source +from google.cloud.securitycenter_v2.types.toxic_combination import ToxicCombination +from google.cloud.securitycenter_v2.types.valued_resource import ResourceValueConfigMetadata +from google.cloud.securitycenter_v2.types.valued_resource import ValuedResource +from google.cloud.securitycenter_v2.types.vulnerability import Cve +from google.cloud.securitycenter_v2.types.vulnerability import Cvssv3 +from google.cloud.securitycenter_v2.types.vulnerability import Package +from google.cloud.securitycenter_v2.types.vulnerability import Reference +from google.cloud.securitycenter_v2.types.vulnerability import SecurityBulletin +from google.cloud.securitycenter_v2.types.vulnerability import Vulnerability + +__all__ = ('SecurityCenterClient', + 'SecurityCenterAsyncClient', + 'Access', + 'Geolocation', + 'ServiceAccountDelegationInfo', + 'Application', + 'AttackExposure', + 'AttackPath', + 'BackupDisasterRecovery', + 'BigQueryExport', + 'AdaptiveProtection', + 'Attack', + 'CloudArmor', + 'Requests', + 'SecurityPolicy', + 'CloudDlpDataProfile', + 'CloudDlpInspection', + 'Compliance', + 'Connection', + 'Contact', + 'ContactDetails', + 'Container', + 'Database', + 'ExfilResource', + 'Exfiltration', + 'ExternalSystem', + 'File', + 'Finding', + 'Folder', + 'GroupMembership', + 'IamBinding', + 'Indicator', + 'KernelRootkit', + 'Kubernetes', + 'Label', + 'LoadBalancer', + 'CloudLoggingEntry', + 'LogEntry', + 'MitreAttack', + 'MuteConfig', + 'Notebook', + 'NotificationConfig', + 'NotificationMessage', + 'OrgPolicy', + 'EnvironmentVariable', + 'Process', + 'AwsMetadata', + 'AzureMetadata', + 'GcpMetadata', + 'Resource', + 'ResourcePath', + 'CloudProvider', + 'ResourceValueConfig', + 'ResourceValue', + 'SecurityMarks', + 'SecurityPosture', + 'BatchCreateResourceValueConfigsRequest', + 'BatchCreateResourceValueConfigsResponse', + 'BulkMuteFindingsRequest', + 'BulkMuteFindingsResponse', + 'CreateBigQueryExportRequest', + 'CreateFindingRequest', + 'CreateMuteConfigRequest', + 'CreateNotificationConfigRequest', + 'CreateResourceValueConfigRequest', + 'CreateSourceRequest', + 'DeleteBigQueryExportRequest', + 'DeleteMuteConfigRequest', + 'DeleteNotificationConfigRequest', + 'DeleteResourceValueConfigRequest', + 'GetBigQueryExportRequest', + 'GetMuteConfigRequest', + 'GetNotificationConfigRequest', + 'GetResourceValueConfigRequest', + 'GetSimulationRequest', + 'GetSourceRequest', + 'GetValuedResourceRequest', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAttackPathsRequest', + 'ListAttackPathsResponse', + 'ListBigQueryExportsRequest', + 'ListBigQueryExportsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListMuteConfigsRequest', + 'ListMuteConfigsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListResourceValueConfigsRequest', + 'ListResourceValueConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListValuedResourcesRequest', + 'ListValuedResourcesResponse', + 'SetFindingStateRequest', + 'SetMuteRequest', + 'UpdateBigQueryExportRequest', + 'UpdateExternalSystemRequest', + 'UpdateFindingRequest', + 'UpdateMuteConfigRequest', + 'UpdateNotificationConfigRequest', + 'UpdateResourceValueConfigRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Simulation', + 'Source', + 'ToxicCombination', + 'ResourceValueConfigMetadata', + 'ValuedResource', + 'Cve', + 'Cvssv3', + 'Package', + 'Reference', + 'SecurityBulletin', + 'Vulnerability', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/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-securitycenter/v2/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py new file mode 100644 index 000000000000..f27bfdd5500f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py @@ -0,0 +1,258 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.securitycenter_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + +from .types.access import Access +from .types.access import Geolocation +from .types.access import ServiceAccountDelegationInfo +from .types.application import Application +from .types.attack_exposure import AttackExposure +from .types.attack_path import AttackPath +from .types.backup_disaster_recovery import BackupDisasterRecovery +from .types.bigquery_export import BigQueryExport +from .types.cloud_armor import AdaptiveProtection +from .types.cloud_armor import Attack +from .types.cloud_armor import CloudArmor +from .types.cloud_armor import Requests +from .types.cloud_armor import SecurityPolicy +from .types.cloud_dlp_data_profile import CloudDlpDataProfile +from .types.cloud_dlp_inspection import CloudDlpInspection +from .types.compliance import Compliance +from .types.connection import Connection +from .types.contact_details import Contact +from .types.contact_details import ContactDetails +from .types.container import Container +from .types.database import Database +from .types.exfiltration import ExfilResource +from .types.exfiltration import Exfiltration +from .types.external_system import ExternalSystem +from .types.file import File +from .types.finding import Finding +from .types.folder import Folder +from .types.group_membership import GroupMembership +from .types.iam_binding import IamBinding +from .types.indicator import Indicator +from .types.kernel_rootkit import KernelRootkit +from .types.kubernetes import Kubernetes +from .types.label import Label +from .types.load_balancer import LoadBalancer +from .types.log_entry import CloudLoggingEntry +from .types.log_entry import LogEntry +from .types.mitre_attack import MitreAttack +from .types.mute_config import MuteConfig +from .types.notebook import Notebook +from .types.notification_config import NotificationConfig +from .types.notification_message import NotificationMessage +from .types.org_policy import OrgPolicy +from .types.process import EnvironmentVariable +from .types.process import Process +from .types.resource import AwsMetadata +from .types.resource import AzureMetadata +from .types.resource import GcpMetadata +from .types.resource import Resource +from .types.resource import ResourcePath +from .types.resource import CloudProvider +from .types.resource_value_config import ResourceValueConfig +from .types.resource_value_config import ResourceValue +from .types.security_marks import SecurityMarks +from .types.security_posture import SecurityPosture +from .types.securitycenter_service import BatchCreateResourceValueConfigsRequest +from .types.securitycenter_service import BatchCreateResourceValueConfigsResponse +from .types.securitycenter_service import BulkMuteFindingsRequest +from .types.securitycenter_service import BulkMuteFindingsResponse +from .types.securitycenter_service import CreateBigQueryExportRequest +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateMuteConfigRequest +from .types.securitycenter_service import CreateNotificationConfigRequest +from .types.securitycenter_service import CreateResourceValueConfigRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import DeleteBigQueryExportRequest +from .types.securitycenter_service import DeleteMuteConfigRequest +from .types.securitycenter_service import DeleteNotificationConfigRequest +from .types.securitycenter_service import DeleteResourceValueConfigRequest +from .types.securitycenter_service import GetBigQueryExportRequest +from .types.securitycenter_service import GetMuteConfigRequest +from .types.securitycenter_service import GetNotificationConfigRequest +from .types.securitycenter_service import GetResourceValueConfigRequest +from .types.securitycenter_service import GetSimulationRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GetValuedResourceRequest +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAttackPathsRequest +from .types.securitycenter_service import ListAttackPathsResponse +from .types.securitycenter_service import ListBigQueryExportsRequest +from .types.securitycenter_service import ListBigQueryExportsResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListMuteConfigsRequest +from .types.securitycenter_service import ListMuteConfigsResponse +from .types.securitycenter_service import ListNotificationConfigsRequest +from .types.securitycenter_service import ListNotificationConfigsResponse +from .types.securitycenter_service import ListResourceValueConfigsRequest +from .types.securitycenter_service import ListResourceValueConfigsResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import ListValuedResourcesRequest +from .types.securitycenter_service import ListValuedResourcesResponse +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import SetMuteRequest +from .types.securitycenter_service import UpdateBigQueryExportRequest +from .types.securitycenter_service import UpdateExternalSystemRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateMuteConfigRequest +from .types.securitycenter_service import UpdateNotificationConfigRequest +from .types.securitycenter_service import UpdateResourceValueConfigRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.simulation import Simulation +from .types.source import Source +from .types.toxic_combination import ToxicCombination +from .types.valued_resource import ResourceValueConfigMetadata +from .types.valued_resource import ValuedResource +from .types.vulnerability import Cve +from .types.vulnerability import Cvssv3 +from .types.vulnerability import Package +from .types.vulnerability import Reference +from .types.vulnerability import SecurityBulletin +from .types.vulnerability import Vulnerability + +__all__ = ( + 'SecurityCenterAsyncClient', +'Access', +'AdaptiveProtection', +'Application', +'Attack', +'AttackExposure', +'AttackPath', +'AwsMetadata', +'AzureMetadata', +'BackupDisasterRecovery', +'BatchCreateResourceValueConfigsRequest', +'BatchCreateResourceValueConfigsResponse', +'BigQueryExport', +'BulkMuteFindingsRequest', +'BulkMuteFindingsResponse', +'CloudArmor', +'CloudDlpDataProfile', +'CloudDlpInspection', +'CloudLoggingEntry', +'CloudProvider', +'Compliance', +'Connection', +'Contact', +'ContactDetails', +'Container', +'CreateBigQueryExportRequest', +'CreateFindingRequest', +'CreateMuteConfigRequest', +'CreateNotificationConfigRequest', +'CreateResourceValueConfigRequest', +'CreateSourceRequest', +'Cve', +'Cvssv3', +'Database', +'DeleteBigQueryExportRequest', +'DeleteMuteConfigRequest', +'DeleteNotificationConfigRequest', +'DeleteResourceValueConfigRequest', +'EnvironmentVariable', +'ExfilResource', +'Exfiltration', +'ExternalSystem', +'File', +'Finding', +'Folder', +'GcpMetadata', +'Geolocation', +'GetBigQueryExportRequest', +'GetMuteConfigRequest', +'GetNotificationConfigRequest', +'GetResourceValueConfigRequest', +'GetSimulationRequest', +'GetSourceRequest', +'GetValuedResourceRequest', +'GroupFindingsRequest', +'GroupFindingsResponse', +'GroupMembership', +'GroupResult', +'IamBinding', +'Indicator', +'KernelRootkit', +'Kubernetes', +'Label', +'ListAttackPathsRequest', +'ListAttackPathsResponse', +'ListBigQueryExportsRequest', +'ListBigQueryExportsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListMuteConfigsRequest', +'ListMuteConfigsResponse', +'ListNotificationConfigsRequest', +'ListNotificationConfigsResponse', +'ListResourceValueConfigsRequest', +'ListResourceValueConfigsResponse', +'ListSourcesRequest', +'ListSourcesResponse', +'ListValuedResourcesRequest', +'ListValuedResourcesResponse', +'LoadBalancer', +'LogEntry', +'MitreAttack', +'MuteConfig', +'Notebook', +'NotificationConfig', +'NotificationMessage', +'OrgPolicy', +'Package', +'Process', +'Reference', +'Requests', +'Resource', +'ResourcePath', +'ResourceValue', +'ResourceValueConfig', +'ResourceValueConfigMetadata', +'SecurityBulletin', +'SecurityCenterClient', +'SecurityMarks', +'SecurityPolicy', +'SecurityPosture', +'ServiceAccountDelegationInfo', +'SetFindingStateRequest', +'SetMuteRequest', +'Simulation', +'Source', +'ToxicCombination', +'UpdateBigQueryExportRequest', +'UpdateExternalSystemRequest', +'UpdateFindingRequest', +'UpdateMuteConfigRequest', +'UpdateNotificationConfigRequest', +'UpdateResourceValueConfigRequest', +'UpdateSecurityMarksRequest', +'UpdateSourceRequest', +'ValuedResource', +'Vulnerability', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json new file mode 100644 index 000000000000..517d51c03f32 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json @@ -0,0 +1,628 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v2", + "protoPackage": "google.cloud.securitycenter.v2", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "rest": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_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-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_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-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__init__.py new file mode 100644 index 000000000000..bffcff5da306 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + 'SecurityCenterClient', + 'SecurityCenterAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py new file mode 100644 index 000000000000..2d6ff6d7cf55 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py @@ -0,0 +1,5422 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.securitycenter_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.securitycenter_v2.services.security_center import pagers +from google.cloud.securitycenter_v2.types import access +from google.cloud.securitycenter_v2.types import application +from google.cloud.securitycenter_v2.types import attack_exposure +from google.cloud.securitycenter_v2.types import attack_path +from google.cloud.securitycenter_v2.types import backup_disaster_recovery +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import cloud_armor +from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile +from google.cloud.securitycenter_v2.types import cloud_dlp_inspection +from google.cloud.securitycenter_v2.types import compliance +from google.cloud.securitycenter_v2.types import connection +from google.cloud.securitycenter_v2.types import container +from google.cloud.securitycenter_v2.types import database +from google.cloud.securitycenter_v2.types import exfiltration +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import file +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import group_membership +from google.cloud.securitycenter_v2.types import iam_binding +from google.cloud.securitycenter_v2.types import indicator +from google.cloud.securitycenter_v2.types import kernel_rootkit +from google.cloud.securitycenter_v2.types import kubernetes +from google.cloud.securitycenter_v2.types import load_balancer +from google.cloud.securitycenter_v2.types import log_entry +from google.cloud.securitycenter_v2.types import mitre_attack +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notebook +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import org_policy +from google.cloud.securitycenter_v2.types import process +from google.cloud.securitycenter_v2.types import resource +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import security_posture +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import toxic_combination +from google.cloud.securitycenter_v2.types import valued_resource +from google.cloud.securitycenter_v2.types import vulnerability +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 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 SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V2 APIs for Security Center service.""" + + _client: SecurityCenterClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE + + attack_path_path = staticmethod(SecurityCenterClient.attack_path_path) + parse_attack_path_path = staticmethod(SecurityCenterClient.parse_attack_path_path) + big_query_export_path = staticmethod(SecurityCenterClient.big_query_export_path) + parse_big_query_export_path = staticmethod(SecurityCenterClient.parse_big_query_export_path) + dlp_job_path = staticmethod(SecurityCenterClient.dlp_job_path) + parse_dlp_job_path = staticmethod(SecurityCenterClient.parse_dlp_job_path) + external_system_path = staticmethod(SecurityCenterClient.external_system_path) + parse_external_system_path = staticmethod(SecurityCenterClient.parse_external_system_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) + parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) + mute_config_path = staticmethod(SecurityCenterClient.mute_config_path) + parse_mute_config_path = staticmethod(SecurityCenterClient.parse_mute_config_path) + notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) + parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) + policy_path = staticmethod(SecurityCenterClient.policy_path) + parse_policy_path = staticmethod(SecurityCenterClient.parse_policy_path) + resource_value_config_path = staticmethod(SecurityCenterClient.resource_value_config_path) + parse_resource_value_config_path = staticmethod(SecurityCenterClient.parse_resource_value_config_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) + simulation_path = staticmethod(SecurityCenterClient.simulation_path) + parse_simulation_path = staticmethod(SecurityCenterClient.parse_simulation_path) + source_path = staticmethod(SecurityCenterClient.source_path) + parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) + table_data_profile_path = staticmethod(SecurityCenterClient.table_data_profile_path) + parse_table_data_profile_path = staticmethod(SecurityCenterClient.parse_table_data_profile_path) + topic_path = staticmethod(SecurityCenterClient.topic_path) + parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) + valued_resource_path = staticmethod(SecurityCenterClient.valued_resource_path) + parse_valued_resource_path = staticmethod(SecurityCenterClient.parse_valued_resource_path) + common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) + parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) + common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) + parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) + common_project_path = staticmethod(SecurityCenterClient.common_project_path) + parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) + common_location_path = staticmethod(SecurityCenterClient.common_location_path) + parse_common_location_path = staticmethod(SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def batch_create_resource_value_configs(self, + request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + requests = securitycenter_v2.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + + request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest, dict]]): + The request object. Request message to create multiple + resource value configs + parent (:class:`str`): + Required. Resource name of the new + ResourceValueConfig's parent. The parent + field in the + CreateResourceValueConfigRequest + messages must either be empty or match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (:class:`MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]`): + Required. The resource value configs + to be created. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, requests]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): + request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests: + request.requests.extend(requests) + + # 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_resource_value_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, + ) + + # Done; return the response. + return response + + async def bulk_mute_findings(self, + request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off an LRO to bulk mute findings for a parent + based on a filter. If no location is specified, findings + are muted in global. The parent can be either an + organization, folder, or project. The findings matched + by the filter will be muted after the LRO is done. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest, dict]]): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + parent (:class:`str`): + Required. The parent, at which bulk action needs to be + applied. If no location is specified, findings are + updated in global. The following list shows some + examples: + + - ``organizations/[organization_id]`` + - ``organizations/[organization_id]/locations/[location_id]`` + - ``folders/[folder_id]`` + - ``folders/[folder_id]/locations/[location_id]`` + - ``projects/[project_id]`` + - ``projects/[project_id]/locations/[location_id]`` + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v2.types.BulkMuteFindingsResponse` + The response to a BulkMute request. Contains the LRO + 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]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): + request = securitycenter_service.BulkMuteFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.bulk_mute_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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + securitycenter_service.BulkMuteFindingsResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def create_big_query_export(self, + request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, + *, + parent: Optional[str] = None, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + big_query_export_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Creates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_create_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = await client.create_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest, dict]]): + The request object. Request message for creating a + BigQuery export. + parent (:class:`str`): + Required. The name of the parent resource of the new + BigQuery export. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export (:class:`google.cloud.securitycenter_v2.types.BigQueryExport`): + Required. The BigQuery export being + created. + + This corresponds to the ``big_query_export`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``big_query_export_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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): + request = securitycenter_service.CreateBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if big_query_export is not None: + request.big_query_export = big_query_export + if big_query_export_id is not None: + request.big_query_export_id = big_query_export_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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + finding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding in a location. The corresponding + source must exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_create_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateFindingRequest, dict]]): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. The + following list shows some examples of the format: + + ``organizations/[organization_id]/sources/[source_id]`` + + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`google.cloud.securitycenter_v2.types.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_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.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding, finding_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, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding is not None: + request.finding = finding + if finding_id is not None: + request.finding_id = finding_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_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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 create_mute_config(self, + request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + mute_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Creates a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_create_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = await client.create_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateMuteConfigRequest, dict]]): + The request object. Request message for creating a mute + config. + parent (:class:`str`): + Required. Resource name of the new mute configs's + parent. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config (:class:`google.cloud.securitycenter_v2.types.MuteConfig`): + Required. The mute config being + created. + + This corresponds to the ``mute_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``mute_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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): + request = securitycenter_service.CreateMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mute_config is not None: + request.mute_config = mute_config + if mute_config_id is not None: + request.mute_config_id = mute_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_mute_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 create_notification_config(self, + request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_create_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest, dict]]): + The request object. Request message for creating a + notification config. + parent (:class:`str`): + Required. Resource name of the new notification config's + parent. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (:class:`google.cloud.securitycenter_v2.types.NotificationConfig`): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (:class:`str`): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters and contain + alphanumeric characters, underscores, or + hyphens only. + + This corresponds to the ``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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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_config, 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, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if notification_config is not None: + request.notification_config = notification_config + if config_id is not None: + request.config_id = 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_notification_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 create_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v2 + + async def sample_create_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateSourceRequest, dict]]): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be ``organizations/[organization_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`google.cloud.securitycenter_v2.types.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = 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_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 delete_big_query_export(self, + request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + await client.delete_big_query_export(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest, dict]]): + The request object. Request message for deleting a + BigQuery export. + name (:class:`str`): + Required. The name of the BigQuery export to delete. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}/locations/{location}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): + request = securitycenter_service.DeleteBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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 delete_mute_config(self, + request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. If no location is + specified, default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_delete_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_mute_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest, dict]]): + The request object. Request message for deleting a mute + config. If no location is specified, + default is global. + name (:class:`str`): + Required. Name of the mute config to delete. The + following list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): + request = securitycenter_service.DeleteMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_mute_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 delete_notification_config(self, + request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest, dict]]): + The request object. Request message for deleting a + notification config. + name (:class:`str`): + Required. Name of the notification config to delete. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 delete_resource_value_config(self, + request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_resource_value_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest, dict]]): + The request object. Request message to delete resource + value config + name (:class:`str`): + Required. Name of the + ResourceValueConfig 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. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): + request = securitycenter_service.DeleteResourceValueConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_resource_value_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_big_query_export(self, + request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Gets a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_get_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetBigQueryExportRequest, dict]]): + The request object. Request message for retrieving a + BigQuery export. + name (:class:`str`): + Required. Name of the BigQuery export to retrieve. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}locations/{location}//bigQueryExports/{export_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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): + request = securitycenter_service.GetBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_simulation(self, + request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> simulation.Simulation: + r"""Get the simulation by name or the latest simulation + for the given organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_get_simulation(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_simulation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetSimulationRequest, dict]]): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + name (:class:`str`): + Required. The organization name or simulation name of + this simulation + + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.Simulation: + Attack path simulation + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSimulationRequest): + request = securitycenter_service.GetSimulationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_simulation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_valued_resource(self, + request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> valued_resource.ValuedResource: + r"""Get the valued resource by 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 import securitycenter_v2 + + async def sample_get_valued_resource(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_valued_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetValuedResourceRequest, dict]]): + The request object. Request message for getting a valued + resource. + name (:class:`str`): + Required. The name of this valued resource + + Valid format: + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v2.types.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetValuedResourceRequest): + request = securitycenter_service.GetValuedResourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_valued_resource] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 get_mute_config(self, + request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> mute_config.MuteConfig: + r"""Gets a mute config. If no location is specified, + default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_get_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetMuteConfigRequest, dict]]): + The request object. Request message for retrieving a mute + config. If no location is specified, + default is global. + name (:class:`str`): + Required. Name of the mute config to retrieve. The + following list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetMuteConfigRequest): + request = securitycenter_service.GetMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_mute_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 get_notification_config(self, + request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_get_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetNotificationConfigRequest, dict]]): + The request object. Request message for getting a + notification config. + name (:class:`str`): + Required. Name of the notification config to get. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 get_resource_value_config(self, + request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource_value_config.ResourceValueConfig: + r"""Gets a ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest, dict]]): + The request object. Request message to get resource value + config + name (:class:`str`): + Required. Name of the resource value config to retrieve. + Its format is + organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v2.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): + request = securitycenter_service.GetResourceValueConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_resource_value_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 get_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v2 + + async def sample_get_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetSourceRequest, dict]]): + The request object. Request message for getting a source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties in a location. If no location is + specified, findings are assumed to be in global + + To group across all sources provide a ``-`` as the source id. + The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + - ``/v2/folders/{folder_id}/sources/-/findings`` + - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` + - ``/v2/projects/{project_id}/sources/-/findings`` + - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_group_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GroupFindingsRequest, dict]]): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. If no location + is specified, finding is assumed to be in global. The + following list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To groupBy across all sources provide a source_id of + ``-``. The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/[location_id]`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-/locations/[location_id]`` + - ``projects/{project_id}/sources/-`` + - ``projects/{project_id}/sources/-/locations/[location_id]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping. The string value should follow SQL + syntax: comma separated list of fields. For example: + "parent,resource_name". + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_attack_paths(self, + request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsAsyncPager: + r"""Lists the attack paths for a set of simulation + results or valued resources and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_attack_paths(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListAttackPathsRequest, dict]]): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + parent (:class:`str`): + Required. Name of parent to list attack paths. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + + 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.securitycenter_v2.services.security_center.pagers.ListAttackPathsAsyncPager: + Response message for listing the + attack paths for a given simulation or + valued resource. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): + request = securitycenter_service.ListAttackPathsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_attack_paths] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListAttackPathsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_big_query_exports(self, + request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsAsyncPager: + r"""Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are 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 securitycenter_v2 + + async def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest, dict]]): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or project. + parent (:class:`str`): + Required. The parent, which owns the collection of + BigQuery exports. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + 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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsAsyncPager: + Response message for listing BigQuery + exports. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): + request = securitycenter_service.ListBigQueryExportsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_big_query_exports] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListBigQueryExportsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings(self, + request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsAsyncPager: + r"""Lists an organization or source's findings. + + To list across all sources for a given location provide a ``-`` + as the source id. If no location is specified, finding are + assumed to be in global. The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListFindingsRequest( + parent="parent_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.securitycenter_v2.types.ListFindingsRequest, dict]]): + The request object. Request message for listing findings. + parent (:class:`str`): + Required. Name of the source the findings belong to. If + no location is specified, the default is global. The + following list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To list across all sources provide a source_id of ``-``. + The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/{location_id}`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-locations/{location_id}`` + - ``projects/{projects_id}/sources/-`` + - ``projects/{projects_id}/sources/-/locations/{location_id}`` + + 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.securitycenter_v2.services.security_center.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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_mute_configs(self, + request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsAsyncPager: + r"""Lists mute configs. If no location is specified, + default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_mute_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListMuteConfigsRequest, dict]]): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or project. If no + location is specified, default is + global. + parent (:class:`str`): + Required. The parent, which owns the collection of mute + configs. Its format is + ``organizations/[organization_id]", "folders/[folder_id]``, + ``projects/[project_id]``, + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, + ``projects/[project_id]/locations/[location_id]``. + + 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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsAsyncPager: + Response message for listing mute + configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): + request = securitycenter_service.ListMuteConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_mute_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.ListMuteConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_notification_configs(self, + request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsAsyncPager: + r"""Lists notification configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest, dict]]): + The request object. Request message for listing + notification configs. + parent (:class:`str`): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + 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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsAsyncPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListNotificationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_resource_value_configs(self, + request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsAsyncPager: + r"""Lists all ResourceValueConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest, dict]]): + The request object. Request message to list resource + value configs of a parent + parent (:class:`str`): + Required. The parent, which owns the collection of + resource value configs. Its format is + ``organizations/[organization_id]`` + + 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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsAsyncPager: + Response message to list resource + value configs + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): + request = securitycenter_service.ListResourceValueConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_resource_value_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.ListResourceValueConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_sources(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListSourcesRequest, dict]]): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + 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.securitycenter_v2.services.security_center.pagers.ListSourcesAsyncPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_valued_resources(self, + request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesAsyncPager: + r"""Lists the valued resources for a set of simulation + results and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_valued_resources(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListValuedResourcesRequest, dict]]): + The request object. Request message for listing the + valued resources for a given simulation. + parent (:class:`str`): + Required. Name of parent to list exposed resources. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + + 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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesAsyncPager: + Response message for listing the + valued resources for a given simulation. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): + request = securitycenter_service.ListValuedResourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_valued_resources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListValuedResourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. If no location is + specified, finding is assumed to be in global + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_set_finding_state(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.SetFindingStateRequest, dict]]): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`google.cloud.securitycenter_v2.types.Finding.State`): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 set_mute(self, + request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, + *, + name: Optional[str] = None, + mute: Optional[finding.Finding.Mute] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the mute state of a finding. If no location + is specified, finding is assumed to be in global + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_set_mute(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = await client.set_mute(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.SetMuteRequest, dict]]): + The request object. Request message for updating a + finding's mute status. + name (:class:`str`): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute (:class:`google.cloud.securitycenter_v2.types.Finding.Mute`): + Required. The desired state of the + Mute. + + This corresponds to the ``mute`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, mute]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetMuteRequest): + request = securitycenter_service.SetMuteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if mute is not None: + request.mute = mute + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.set_mute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 update_big_query_export(self, + request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, + *, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + update_mask: 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]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Updates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateBigQueryExportRequest( + ) + + # Make the request + response = await client.update_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest, dict]]): + The request object. Request message for updating a + BigQuery export. + big_query_export (:class:`google.cloud.securitycenter_v2.types.BigQueryExport`): + Required. The BigQuery export being + updated. + + This corresponds to the ``big_query_export`` 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. + If empty all mutable fields 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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): + request = securitycenter_service.UpdateBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if big_query_export is not None: + request.big_query_export = big_query_export + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("big_query_export.name", request.big_query_export.name), + )), + ) + + # Validate the universe domain. + self._client._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_external_system(self, + request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, + *, + external_system: Optional[gcs_external_system.ExternalSystem] = None, + update_mask: 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]] = (), + ) -> gcs_external_system.ExternalSystem: + r"""Updates external system. This is for a given finding. + If no location is specified, finding is assumed to be in + global + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_external_system(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateExternalSystemRequest( + ) + + # Make the request + response = await client.update_external_system(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest, dict]]): + The request object. Request message for updating a + ExternalSystem resource. + external_system (:class:`google.cloud.securitycenter_v2.types.ExternalSystem`): + Required. The external system + resource to update. + + This corresponds to the ``external_system`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the external system resource. + If empty all mutable fields 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.cloud.securitycenter_v2.types.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): + request = securitycenter_service.UpdateExternalSystemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if external_system is not None: + request.external_system = external_system + 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_external_system] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("external_system.name", request.external_system.name), + )), + ) + + # Validate the universe domain. + self._client._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_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + update_mask: 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]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. If no location is + specified, finding is assumed to be in global. The + corresponding source must exist for a finding creation + to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateFindingRequest, dict]]): + The request object. Request message for updating or + creating a finding. + finding (:class:`google.cloud.securitycenter_v2.types.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + + 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.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + 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_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe domain. + self._client._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_mute_config(self, + request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, + *, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + update_mask: 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]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Updates a mute config. If no location is specified, + default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = await client.update_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest, dict]]): + The request object. Request message for updating a mute + config. + mute_config (:class:`google.cloud.securitycenter_v2.types.MuteConfig`): + Required. The mute config being + updated. + + This corresponds to the ``mute_config`` 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. + If empty all mutable fields 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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): + request = securitycenter_service.UpdateMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mute_config is not None: + request.mute_config = mute_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_mute_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("mute_config.name", request.mute_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 update_notification_config(self, + request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, + *, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + update_mask: 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest, dict]]): + The request object. Request message for updating a + notification config. + notification_config (:class:`google.cloud.securitycenter_v2.types.NotificationConfig`): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the notification config. + If empty all mutable fields 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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_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 update_resource_value_config(self, + request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, + *, + resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, + update_mask: 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]] = (), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Updates an existing ResourceValueConfigs with new + rules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateResourceValueConfigRequest( + ) + + # Make the request + response = await client.update_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest, dict]]): + The request object. Request message to update resource + value config + resource_value_config (:class:`google.cloud.securitycenter_v2.types.ResourceValueConfig`): + Required. The resource value config + being updated. + + This corresponds to the ``resource_value_config`` 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. If empty all mutable + fields will be updated. + + To update nested fields, include the top level field in + the mask For example, to update + gcp_metadata.resource_type, include the "gcp_metadata" + field mask + + 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.securitycenter_v2.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): + request = securitycenter_service.UpdateResourceValueConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if resource_value_config is not None: + request.resource_value_config = resource_value_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_resource_value_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource_value_config.name", request.resource_value_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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + update_mask: 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]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. For Finding Security marks, + if no location is specified, finding is assumed to be in + global. Assets Security Marks can only be accessed + through global endpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_security_marks(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest, dict]]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`google.cloud.securitycenter_v2.types.SecurityMarks`): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + + 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.securitycenter_v2.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + 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_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe domain. + self._client._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_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + update_mask: 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]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v2 + + async def sample_update_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateSourceRequest, dict]]): + The request object. Request message for updating a + source. + source (:class:`google.cloud.securitycenter_v2.types.Source`): + Required. The source resource to + update. + + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the source resource. + If empty all mutable fields 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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = 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_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "SecurityCenterAsyncClient": + 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__ = ( + "SecurityCenterAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py new file mode 100644 index 000000000000..550305f1c892 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py @@ -0,0 +1,5948 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.securitycenter_v2.services.security_center import pagers +from google.cloud.securitycenter_v2.types import access +from google.cloud.securitycenter_v2.types import application +from google.cloud.securitycenter_v2.types import attack_exposure +from google.cloud.securitycenter_v2.types import attack_path +from google.cloud.securitycenter_v2.types import backup_disaster_recovery +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import cloud_armor +from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile +from google.cloud.securitycenter_v2.types import cloud_dlp_inspection +from google.cloud.securitycenter_v2.types import compliance +from google.cloud.securitycenter_v2.types import connection +from google.cloud.securitycenter_v2.types import container +from google.cloud.securitycenter_v2.types import database +from google.cloud.securitycenter_v2.types import exfiltration +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import file +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import group_membership +from google.cloud.securitycenter_v2.types import iam_binding +from google.cloud.securitycenter_v2.types import indicator +from google.cloud.securitycenter_v2.types import kernel_rootkit +from google.cloud.securitycenter_v2.types import kubernetes +from google.cloud.securitycenter_v2.types import load_balancer +from google.cloud.securitycenter_v2.types import log_entry +from google.cloud.securitycenter_v2.types import mitre_attack +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notebook +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import org_policy +from google.cloud.securitycenter_v2.types import process +from google.cloud.securitycenter_v2.types import resource +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import security_posture +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import toxic_combination +from google.cloud.securitycenter_v2.types import valued_resource +from google.cloud.securitycenter_v2.types import vulnerability +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 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 SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .transports.rest import SecurityCenterRestTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + _transport_registry["rest"] = SecurityCenterRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SecurityCenterTransport]: + """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V2 APIs for Security Center 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 = "securitycenter.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: + SecurityCenterClient: 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: + SecurityCenterClient: 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) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def attack_path_path(organization: str,simulation: str,valued_resource: str,attack_path: str,) -> str: + """Returns a fully-qualified attack_path string.""" + return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) + + @staticmethod + def parse_attack_path_path(path: str) -> Dict[str,str]: + """Parses a attack_path path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?P.+?)/attackPaths/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def big_query_export_path(organization: str,location: str,export: str,) -> str: + """Returns a fully-qualified big_query_export string.""" + return "organizations/{organization}/locations/{location}/bigQueryExports/{export}".format(organization=organization, location=location, export=export, ) + + @staticmethod + def parse_big_query_export_path(path: str) -> Dict[str,str]: + """Parses a big_query_export path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/locations/(?P.+?)/bigQueryExports/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def dlp_job_path(project: str,dlp_job: str,) -> str: + """Returns a fully-qualified dlp_job string.""" + return "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) + + @staticmethod + def parse_dlp_job_path(path: str) -> Dict[str,str]: + """Parses a dlp_job path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/dlpJobs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def external_system_path(organization: str,source: str,finding: str,externalsystem: str,) -> str: + """Returns a fully-qualified external_system string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) + + @staticmethod + def parse_external_system_path(path: str) -> Dict[str,str]: + """Parses a external_system path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)/externalSystems/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def finding_path(organization: str,source: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def mute_config_path(organization: str,mute_config: str,) -> str: + """Returns a fully-qualified mute_config string.""" + return "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) + + @staticmethod + def parse_mute_config_path(path: str) -> Dict[str,str]: + """Parses a mute_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/muteConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def notification_config_path(organization: str,location: str,notification_config: str,) -> str: + """Returns a fully-qualified notification_config string.""" + return "organizations/{organization}/locations/{location}/notificationConfigs/{notification_config}".format(organization=organization, location=location, notification_config=notification_config, ) + + @staticmethod + def parse_notification_config_path(path: str) -> Dict[str,str]: + """Parses a notification_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/locations/(?P.+?)/notificationConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def policy_path(organization: str,constraint_name: str,) -> str: + """Returns a fully-qualified policy string.""" + return "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) + + @staticmethod + def parse_policy_path(path: str) -> Dict[str,str]: + """Parses a policy path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/policies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def resource_value_config_path(organization: str,resource_value_config: str,) -> str: + """Returns a fully-qualified resource_value_config string.""" + return "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) + + @staticmethod + def parse_resource_value_config_path(path: str) -> Dict[str,str]: + """Parses a resource_value_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/resourceValueConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str,str]: + """Parses a security_marks path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) + return m.groupdict() if m else {} + + @staticmethod + def simulation_path(organization: str,simulation: str,) -> str: + """Returns a fully-qualified simulation string.""" + return "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) + + @staticmethod + def parse_simulation_path(path: str) -> Dict[str,str]: + """Parses a simulation path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str,source: str,) -> str: + """Returns a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str,str]: + """Parses a source path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def table_data_profile_path(project: str,table_profile: str,) -> str: + """Returns a fully-qualified table_data_profile string.""" + return "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) + + @staticmethod + def parse_table_data_profile_path(path: str) -> Dict[str,str]: + """Parses a table_data_profile path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/tableProfiles/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def topic_path(project: str,topic: str,) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str,str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def valued_resource_path(organization: str,simulation: str,valued_resource: str,) -> str: + """Returns a fully-qualified valued_resource string.""" + return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) + + @staticmethod + def parse_valued_resource_path(path: str) -> Dict[str,str]: + """Parses a valued_resource path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 + SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient._read_environment_variables() + self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) + if transport_provided: + # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SecurityCenterTransport], 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 batch_create_resource_value_configs(self, + request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + requests = securitycenter_v2.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + + request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest, dict]): + The request object. Request message to create multiple + resource value configs + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. The parent + field in the + CreateResourceValueConfigRequest + messages must either be empty or match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]): + Required. The resource value configs + to be created. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, requests]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): + request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_resource_value_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, + ) + + # Done; return the response. + return response + + def bulk_mute_findings(self, + request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), + ) -> operation.Operation: + r"""Kicks off an LRO to bulk mute findings for a parent + based on a filter. If no location is specified, findings + are muted in global. The parent can be either an + organization, folder, or project. The findings matched + by the filter will be muted after the LRO is done. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest, dict]): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + parent (str): + Required. The parent, at which bulk action needs to be + applied. If no location is specified, findings are + updated in global. The following list shows some + examples: + + - ``organizations/[organization_id]`` + - ``organizations/[organization_id]/locations/[location_id]`` + - ``folders/[folder_id]`` + - ``folders/[folder_id]/locations/[location_id]`` + - ``projects/[project_id]`` + - ``projects/[project_id]/locations/[location_id]`` + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v2.types.BulkMuteFindingsResponse` + The response to a BulkMute request. Contains the LRO + 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): + request = securitycenter_service.BulkMuteFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.bulk_mute_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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + securitycenter_service.BulkMuteFindingsResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def create_big_query_export(self, + request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, + *, + parent: Optional[str] = None, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + big_query_export_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Creates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_create_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = client.create_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest, dict]): + The request object. Request message for creating a + BigQuery export. + parent (str): + Required. The name of the parent resource of the new + BigQuery export. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): + Required. The BigQuery export being + created. + + This corresponds to the ``big_query_export`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``big_query_export_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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): + request = securitycenter_service.CreateBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if big_query_export is not None: + request.big_query_export = big_query_export + if big_query_export_id is not None: + request.big_query_export_id = big_query_export_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + finding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding in a location. The corresponding + source must exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_create_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateFindingRequest, dict]): + The request object. Request message for creating a + finding. + parent (str): + Required. Resource name of the new finding's parent. The + following list shows some examples of the format: + + ``organizations/[organization_id]/sources/[source_id]`` + + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (google.cloud.securitycenter_v2.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_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.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding, finding_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, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding is not None: + request.finding = finding + if finding_id is not None: + request.finding_id = finding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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 create_mute_config(self, + request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + mute_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Creates a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_create_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = client.create_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateMuteConfigRequest, dict]): + The request object. Request message for creating a mute + config. + parent (str): + Required. Resource name of the new mute configs's + parent. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config (google.cloud.securitycenter_v2.types.MuteConfig): + Required. The mute config being + created. + + This corresponds to the ``mute_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``mute_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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): + request = securitycenter_service.CreateMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mute_config is not None: + request.mute_config = mute_config + if mute_config_id is not None: + request.mute_config_id = mute_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_mute_config] + + header_params = {} + + routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + 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_notification_config(self, + request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_create_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest, dict]): + The request object. Request message for creating a + notification config. + parent (str): + Required. Resource name of the new notification config's + parent. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (str): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters and contain + alphanumeric characters, underscores, or + hyphens only. + + This corresponds to the ``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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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_config, 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, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if notification_config is not None: + request.notification_config = notification_config + if config_id is not None: + request.config_id = config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_notification_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 create_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v2 + + def sample_create_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateSourceRequest, dict]): + The request object. Request message for creating a + source. + parent (str): + Required. Resource name of the new source's parent. Its + format should be ``organizations/[organization_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (google.cloud.securitycenter_v2.types.Source): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_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 delete_big_query_export(self, + request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + client.delete_big_query_export(request=request) + + Args: + request (Union[google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest, dict]): + The request object. Request message for deleting a + BigQuery export. + name (str): + Required. The name of the BigQuery export to delete. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}/locations/{location}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): + request = securitycenter_service.DeleteBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + 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 delete_mute_config(self, + request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. If no location is + specified, default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_delete_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_mute_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest, dict]): + The request object. Request message for deleting a mute + config. If no location is specified, + default is global. + name (str): + Required. Name of the mute config to delete. The + following list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): + request = securitycenter_service.DeleteMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_mute_config] + + header_params = {} + + routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + 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 delete_notification_config(self, + request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_delete_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest, dict]): + The request object. Request message for deleting a + notification config. + name (str): + Required. Name of the notification config to delete. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 delete_resource_value_config(self, + request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_resource_value_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest, dict]): + The request object. Request message to delete resource + value config + name (str): + Required. Name of the + ResourceValueConfig 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. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): + request = securitycenter_service.DeleteResourceValueConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_resource_value_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_big_query_export(self, + request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Gets a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_get_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = client.get_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetBigQueryExportRequest, dict]): + The request object. Request message for retrieving a + BigQuery export. + name (str): + Required. Name of the BigQuery export to retrieve. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}locations/{location}//bigQueryExports/{export_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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): + request = securitycenter_service.GetBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_simulation(self, + request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> simulation.Simulation: + r"""Get the simulation by name or the latest simulation + for the given organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_get_simulation(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = client.get_simulation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetSimulationRequest, dict]): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + name (str): + Required. The organization name or simulation name of + this simulation + + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.Simulation: + Attack path simulation + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSimulationRequest): + request = securitycenter_service.GetSimulationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_simulation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_valued_resource(self, + request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> valued_resource.ValuedResource: + r"""Get the valued resource by 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 import securitycenter_v2 + + def sample_get_valued_resource(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_valued_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetValuedResourceRequest, dict]): + The request object. Request message for getting a valued + resource. + name (str): + Required. The name of this valued resource + + Valid format: + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v2.types.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetValuedResourceRequest): + request = securitycenter_service.GetValuedResourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_valued_resource] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 get_mute_config(self, + request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> mute_config.MuteConfig: + r"""Gets a mute config. If no location is specified, + default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_get_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetMuteConfigRequest, dict]): + The request object. Request message for retrieving a mute + config. If no location is specified, + default is global. + name (str): + Required. Name of the mute config to retrieve. The + following list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetMuteConfigRequest): + request = securitycenter_service.GetMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_mute_config] + + header_params = {} + + routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + 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_notification_config(self, + request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_get_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetNotificationConfigRequest, dict]): + The request object. Request message for getting a + notification config. + name (str): + Required. Name of the notification config to get. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 get_resource_value_config(self, + request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource_value_config.ResourceValueConfig: + r"""Gets a ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest, dict]): + The request object. Request message to get resource value + config + name (str): + Required. Name of the resource value config to retrieve. + Its format is + organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v2.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): + request = securitycenter_service.GetResourceValueConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_resource_value_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 get_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v2 + + def sample_get_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetSourceRequest, dict]): + The request object. Request message for getting a source. + name (str): + Required. Relative resource name of the source. Its + format is + ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties in a location. If no location is + specified, findings are assumed to be in global + + To group across all sources provide a ``-`` as the source id. + The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + - ``/v2/folders/{folder_id}/sources/-/findings`` + - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` + - ``/v2/projects/{project_id}/sources/-/findings`` + - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_group_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GroupFindingsRequest, dict]): + The request object. Request message for grouping by + findings. + parent (str): + Required. Name of the source to groupBy. If no location + is specified, finding is assumed to be in global. The + following list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To groupBy across all sources provide a source_id of + ``-``. The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/[location_id]`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-/locations/[location_id]`` + - ``projects/{project_id}/sources/-`` + - ``projects/{project_id}/sources/-/locations/[location_id]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (str): + Required. Expression that defines what assets fields to + use for grouping. The string value should follow SQL + syntax: comma separated list of fields. For example: + "parent,resource_name". + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_attack_paths(self, + request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsPager: + r"""Lists the attack paths for a set of simulation + results or valued resources and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_attack_paths(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListAttackPathsRequest, dict]): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + parent (str): + Required. Name of parent to list attack paths. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + + 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.securitycenter_v2.services.security_center.pagers.ListAttackPathsPager: + Response message for listing the + attack paths for a given simulation or + valued resource. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): + request = securitycenter_service.ListAttackPathsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_attack_paths] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListAttackPathsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_big_query_exports(self, + request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsPager: + r"""Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are 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 securitycenter_v2 + + def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest, dict]): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or project. + parent (str): + Required. The parent, which owns the collection of + BigQuery exports. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + 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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsPager: + Response message for listing BigQuery + exports. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): + request = securitycenter_service.ListBigQueryExportsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_big_query_exports] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListBigQueryExportsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings(self, + request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsPager: + r"""Lists an organization or source's findings. + + To list across all sources for a given location provide a ``-`` + as the source id. If no location is specified, finding are + assumed to be in global. The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListFindingsRequest( + parent="parent_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.securitycenter_v2.types.ListFindingsRequest, dict]): + The request object. Request message for listing findings. + parent (str): + Required. Name of the source the findings belong to. If + no location is specified, the default is global. The + following list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To list across all sources provide a source_id of ``-``. + The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/{location_id}`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-locations/{location_id}`` + - ``projects/{projects_id}/sources/-`` + - ``projects/{projects_id}/sources/-/locations/{location_id}`` + + 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.securitycenter_v2.services.security_center.pagers.ListFindingsPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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_mute_configs(self, + request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsPager: + r"""Lists mute configs. If no location is specified, + default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_mute_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListMuteConfigsRequest, dict]): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or project. If no + location is specified, default is + global. + parent (str): + Required. The parent, which owns the collection of mute + configs. Its format is + ``organizations/[organization_id]", "folders/[folder_id]``, + ``projects/[project_id]``, + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, + ``projects/[project_id]/locations/[location_id]``. + + 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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsPager: + Response message for listing mute + configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): + request = securitycenter_service.ListMuteConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_mute_configs] + + header_params = {} + + routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + 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.ListMuteConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_notification_configs(self, + request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsPager: + r"""Lists notification configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_notification_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest, dict]): + The request object. Request message for listing + notification configs. + parent (str): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + 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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListNotificationConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_resource_value_configs(self, + request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsPager: + r"""Lists all ResourceValueConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest, dict]): + The request object. Request message to list resource + value configs of a parent + parent (str): + Required. The parent, which owns the collection of + resource value configs. Its format is + ``organizations/[organization_id]`` + + 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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsPager: + Response message to list resource + value configs + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): + request = securitycenter_service.ListResourceValueConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_resource_value_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.ListResourceValueConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_sources(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListSourcesRequest, dict]): + The request object. Request message for listing sources. + parent (str): + Required. Resource name of the parent of sources to + list. Its format should be + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + 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.securitycenter_v2.services.security_center.pagers.ListSourcesPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_valued_resources(self, + request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesPager: + r"""Lists the valued resources for a set of simulation + results and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_valued_resources(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListValuedResourcesRequest, dict]): + The request object. Request message for listing the + valued resources for a given simulation. + parent (str): + Required. Name of parent to list exposed resources. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + + 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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesPager: + Response message for listing the + valued resources for a given simulation. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): + request = securitycenter_service.ListValuedResourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_valued_resources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListValuedResourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. If no location is + specified, finding is assumed to be in global + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_set_finding_state(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.SetFindingStateRequest, dict]): + The request object. Request message for updating a + finding's state. + name (str): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (google.cloud.securitycenter_v2.types.Finding.State): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 set_mute(self, + request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, + *, + name: Optional[str] = None, + mute: Optional[finding.Finding.Mute] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the mute state of a finding. If no location + is specified, finding is assumed to be in global + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_set_mute(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = client.set_mute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.SetMuteRequest, dict]): + The request object. Request message for updating a + finding's mute status. + name (str): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute (google.cloud.securitycenter_v2.types.Finding.Mute): + Required. The desired state of the + Mute. + + This corresponds to the ``mute`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, mute]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetMuteRequest): + request = securitycenter_service.SetMuteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if mute is not None: + request.mute = mute + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_mute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # 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 + + def update_big_query_export(self, + request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, + *, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + update_mask: 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]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Updates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateBigQueryExportRequest( + ) + + # Make the request + response = client.update_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest, dict]): + The request object. Request message for updating a + BigQuery export. + big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): + Required. The BigQuery export being + updated. + + This corresponds to the ``big_query_export`` 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. + If empty all mutable fields 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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): + request = securitycenter_service.UpdateBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if big_query_export is not None: + request.big_query_export = big_query_export + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("big_query_export.name", request.big_query_export.name), + )), + ) + + # Validate the universe 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_external_system(self, + request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, + *, + external_system: Optional[gcs_external_system.ExternalSystem] = None, + update_mask: 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]] = (), + ) -> gcs_external_system.ExternalSystem: + r"""Updates external system. This is for a given finding. + If no location is specified, finding is assumed to be in + global + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_external_system(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateExternalSystemRequest( + ) + + # Make the request + response = client.update_external_system(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest, dict]): + The request object. Request message for updating a + ExternalSystem resource. + external_system (google.cloud.securitycenter_v2.types.ExternalSystem): + Required. The external system + resource to update. + + This corresponds to the ``external_system`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the external system resource. + If empty all mutable fields 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.cloud.securitycenter_v2.types.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): + request = securitycenter_service.UpdateExternalSystemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if external_system is not None: + request.external_system = external_system + 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_external_system] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("external_system.name", request.external_system.name), + )), + ) + + # Validate the universe 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_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + update_mask: 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]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. If no location is + specified, finding is assumed to be in global. The + corresponding source must exist for a finding creation + to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateFindingRequest, dict]): + The request object. Request message for updating or + creating a finding. + finding (google.cloud.securitycenter_v2.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + + 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.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + 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_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe 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_mute_config(self, + request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, + *, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + update_mask: 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]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Updates a mute config. If no location is specified, + default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = client.update_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest, dict]): + The request object. Request message for updating a mute + config. + mute_config (google.cloud.securitycenter_v2.types.MuteConfig): + Required. The mute config being + updated. + + This corresponds to the ``mute_config`` 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. + If empty all mutable fields 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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): + request = securitycenter_service.UpdateMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mute_config is not None: + request.mute_config = mute_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_mute_config] + + header_params = {} + + routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.mute_config.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.mute_config.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.mute_config.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + 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_notification_config(self, + request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, + *, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + update_mask: 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest, dict]): + The request object. Request message for updating a + notification config. + notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the notification config. + If empty all mutable fields 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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_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 update_resource_value_config(self, + request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, + *, + resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, + update_mask: 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]] = (), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Updates an existing ResourceValueConfigs with new + rules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateResourceValueConfigRequest( + ) + + # Make the request + response = client.update_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest, dict]): + The request object. Request message to update resource + value config + resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): + Required. The resource value config + being updated. + + This corresponds to the ``resource_value_config`` 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. If empty all mutable + fields will be updated. + + To update nested fields, include the top level field in + the mask For example, to update + gcp_metadata.resource_type, include the "gcp_metadata" + field mask + + 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.securitycenter_v2.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): + request = securitycenter_service.UpdateResourceValueConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if resource_value_config is not None: + request.resource_value_config = resource_value_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_resource_value_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource_value_config.name", request.resource_value_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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + update_mask: 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]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. For Finding Security marks, + if no location is specified, finding is assumed to be in + global. Assets Security Marks can only be accessed + through global endpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_security_marks(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest, dict]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + + 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.securitycenter_v2.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + 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_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe 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_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + update_mask: 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]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v2 + + def sample_update_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateSourceRequest, dict]): + The request object. Request message for updating a + source. + source (google.cloud.securitycenter_v2.types.Source): + Required. The source resource to + update. + + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the source resource. + If empty all mutable fields 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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = 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_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 __enter__(self) -> "SecurityCenterClient": + 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 = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + 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 = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SecurityCenterClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py new file mode 100644 index 000000000000..59d34c60c0a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py @@ -0,0 +1,1249 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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.securitycenter_v2.types import attack_path +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import valued_resource + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v2.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` + attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v2.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAttackPathsPager: + """A pager for iterating through ``list_attack_paths`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``attack_paths`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAttackPaths`` requests and continue to iterate + through the ``attack_paths`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListAttackPathsResponse], + request: securitycenter_service.ListAttackPathsRequest, + response: securitycenter_service.ListAttackPathsResponse, + *, + 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.securitycenter_v2.types.ListAttackPathsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListAttackPathsResponse): + 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 = securitycenter_service.ListAttackPathsRequest(request) + 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[securitycenter_service.ListAttackPathsResponse]: + 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[attack_path.AttackPath]: + for page in self.pages: + yield from page.attack_paths + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAttackPathsAsyncPager: + """A pager for iterating through ``list_attack_paths`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``attack_paths`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAttackPaths`` requests and continue to iterate + through the ``attack_paths`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` + attributes are available on the 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[securitycenter_service.ListAttackPathsResponse]], + request: securitycenter_service.ListAttackPathsRequest, + response: securitycenter_service.ListAttackPathsResponse, + *, + 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.securitycenter_v2.types.ListAttackPathsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListAttackPathsResponse): + 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 = securitycenter_service.ListAttackPathsRequest(request) + 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[securitycenter_service.ListAttackPathsResponse]: + 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[attack_path.AttackPath]: + async def async_generator(): + async for page in self.pages: + for response in page.attack_paths: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBigQueryExportsPager: + """A pager for iterating through ``list_big_query_exports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``big_query_exports`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBigQueryExports`` requests and continue to iterate + through the ``big_query_exports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListBigQueryExportsResponse], + request: securitycenter_service.ListBigQueryExportsRequest, + response: securitycenter_service.ListBigQueryExportsResponse, + *, + 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.securitycenter_v2.types.ListBigQueryExportsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse): + 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 = securitycenter_service.ListBigQueryExportsRequest(request) + 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[securitycenter_service.ListBigQueryExportsResponse]: + 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[bigquery_export.BigQueryExport]: + for page in self.pages: + yield from page.big_query_exports + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBigQueryExportsAsyncPager: + """A pager for iterating through ``list_big_query_exports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``big_query_exports`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBigQueryExports`` requests and continue to iterate + through the ``big_query_exports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` + attributes are available on the 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[securitycenter_service.ListBigQueryExportsResponse]], + request: securitycenter_service.ListBigQueryExportsRequest, + response: securitycenter_service.ListBigQueryExportsResponse, + *, + 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.securitycenter_v2.types.ListBigQueryExportsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse): + 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 = securitycenter_service.ListBigQueryExportsRequest(request) + 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[securitycenter_service.ListBigQueryExportsResponse]: + 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[bigquery_export.BigQueryExport]: + async def async_generator(): + async for page in self.pages: + for response in page.big_query_exports: + 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.securitycenter_v2.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.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[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v2.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + for page in self.pages: + yield from page.list_findings_results + + 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.securitycenter_v2.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.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[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v2.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_findings_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMuteConfigsPager: + """A pager for iterating through ``list_mute_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``mute_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMuteConfigs`` requests and continue to iterate + through the ``mute_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListMuteConfigsResponse], + request: securitycenter_service.ListMuteConfigsRequest, + response: securitycenter_service.ListMuteConfigsResponse, + *, + 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.securitycenter_v2.types.ListMuteConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListMuteConfigsResponse): + 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 = securitycenter_service.ListMuteConfigsRequest(request) + 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[securitycenter_service.ListMuteConfigsResponse]: + 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[mute_config.MuteConfig]: + for page in self.pages: + yield from page.mute_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMuteConfigsAsyncPager: + """A pager for iterating through ``list_mute_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``mute_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMuteConfigs`` requests and continue to iterate + through the ``mute_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` + attributes are available on the 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[securitycenter_service.ListMuteConfigsResponse]], + request: securitycenter_service.ListMuteConfigsRequest, + response: securitycenter_service.ListMuteConfigsResponse, + *, + 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.securitycenter_v2.types.ListMuteConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListMuteConfigsResponse): + 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 = securitycenter_service.ListMuteConfigsRequest(request) + 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[securitycenter_service.ListMuteConfigsResponse]: + 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[mute_config.MuteConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.mute_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v2.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + 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[securitycenter_service.ListNotificationConfigsResponse]: + 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[notification_config.NotificationConfig]: + for page in self.pages: + yield from page.notification_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsAsyncPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` + attributes are available on the 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[securitycenter_service.ListNotificationConfigsResponse]], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v2.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + 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[securitycenter_service.ListNotificationConfigsResponse]: + 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[notification_config.NotificationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.notification_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourceValueConfigsPager: + """A pager for iterating through ``list_resource_value_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resource_value_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListResourceValueConfigs`` requests and continue to iterate + through the ``resource_value_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListResourceValueConfigsResponse], + request: securitycenter_service.ListResourceValueConfigsRequest, + response: securitycenter_service.ListResourceValueConfigsResponse, + *, + 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.securitycenter_v2.types.ListResourceValueConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse): + 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 = securitycenter_service.ListResourceValueConfigsRequest(request) + 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[securitycenter_service.ListResourceValueConfigsResponse]: + 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[resource_value_config.ResourceValueConfig]: + for page in self.pages: + yield from page.resource_value_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourceValueConfigsAsyncPager: + """A pager for iterating through ``list_resource_value_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resource_value_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListResourceValueConfigs`` requests and continue to iterate + through the ``resource_value_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` + attributes are available on the 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[securitycenter_service.ListResourceValueConfigsResponse]], + request: securitycenter_service.ListResourceValueConfigsRequest, + response: securitycenter_service.ListResourceValueConfigsResponse, + *, + 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.securitycenter_v2.types.ListResourceValueConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse): + 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 = securitycenter_service.ListResourceValueConfigsRequest(request) + 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[securitycenter_service.ListResourceValueConfigsResponse]: + 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[resource_value_config.ResourceValueConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.resource_value_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v2.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` + attributes are available on the 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[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v2.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.sources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListValuedResourcesPager: + """A pager for iterating through ``list_valued_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``valued_resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListValuedResources`` requests and continue to iterate + through the ``valued_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListValuedResourcesResponse], + request: securitycenter_service.ListValuedResourcesRequest, + response: securitycenter_service.ListValuedResourcesResponse, + *, + 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.securitycenter_v2.types.ListValuedResourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListValuedResourcesResponse): + 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 = securitycenter_service.ListValuedResourcesRequest(request) + 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[securitycenter_service.ListValuedResourcesResponse]: + 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[valued_resource.ValuedResource]: + for page in self.pages: + yield from page.valued_resources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListValuedResourcesAsyncPager: + """A pager for iterating through ``list_valued_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``valued_resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListValuedResources`` requests and continue to iterate + through the ``valued_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` + attributes are available on the 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[securitycenter_service.ListValuedResourcesResponse]], + request: securitycenter_service.ListValuedResourcesRequest, + response: securitycenter_service.ListValuedResourcesResponse, + *, + 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.securitycenter_v2.types.ListValuedResourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListValuedResourcesResponse): + 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 = securitycenter_service.ListValuedResourcesRequest(request) + 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[securitycenter_service.ListValuedResourcesResponse]: + 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[valued_resource.ValuedResource]: + async def async_generator(): + async for page in self.pages: + for response in page.valued_resources: + 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-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py new file mode 100644 index 000000000000..9d36139c1a9b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/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 SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .rest import SecurityCenterRestTransport +from .rest import SecurityCenterRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry['grpc'] = SecurityCenterGrpcTransport +_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport +_transport_registry['rest'] = SecurityCenterRestTransport + +__all__ = ( + 'SecurityCenterTransport', + 'SecurityCenterGrpcTransport', + 'SecurityCenterGrpcAsyncIOTransport', + 'SecurityCenterRestTransport', + 'SecurityCenterRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py new file mode 100644 index 000000000000..817f5b747cd0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py @@ -0,0 +1,761 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.securitycenter_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.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.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource +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 empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'securitycenter.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.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: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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.batch_create_resource_value_configs: gapic_v1.method.wrap_method( + self.batch_create_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.bulk_mute_findings: gapic_v1.method.wrap_method( + self.bulk_mute_findings, + default_timeout=None, + client_info=client_info, + ), + self.create_big_query_export: gapic_v1.method.wrap_method( + self.create_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, + default_timeout=None, + client_info=client_info, + ), + self.create_mute_config: gapic_v1.method.wrap_method( + self.create_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method.wrap_method( + self.create_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.create_source: gapic_v1.method.wrap_method( + self.create_source, + default_timeout=None, + client_info=client_info, + ), + self.delete_big_query_export: gapic_v1.method.wrap_method( + self.delete_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.delete_mute_config: gapic_v1.method.wrap_method( + self.delete_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method.wrap_method( + self.delete_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_resource_value_config: gapic_v1.method.wrap_method( + self.delete_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_big_query_export: gapic_v1.method.wrap_method( + self.get_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.get_simulation: gapic_v1.method.wrap_method( + self.get_simulation, + default_timeout=None, + client_info=client_info, + ), + self.get_valued_resource: gapic_v1.method.wrap_method( + self.get_valued_resource, + default_timeout=None, + 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.get_mute_config: gapic_v1.method.wrap_method( + self.get_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.get_notification_config: gapic_v1.method.wrap_method( + self.get_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.get_resource_value_config: gapic_v1.method.wrap_method( + self.get_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_source: gapic_v1.method.wrap_method( + self.get_source, + default_timeout=None, + client_info=client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_findings, + default_timeout=None, + client_info=client_info, + ), + self.list_attack_paths: gapic_v1.method.wrap_method( + self.list_attack_paths, + default_timeout=None, + client_info=client_info, + ), + self.list_big_query_exports: gapic_v1.method.wrap_method( + self.list_big_query_exports, + default_timeout=None, + client_info=client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + default_timeout=None, + client_info=client_info, + ), + self.list_mute_configs: gapic_v1.method.wrap_method( + self.list_mute_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method.wrap_method( + self.list_notification_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_resource_value_configs: gapic_v1.method.wrap_method( + self.list_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_sources: gapic_v1.method.wrap_method( + self.list_sources, + default_timeout=None, + client_info=client_info, + ), + self.list_valued_resources: gapic_v1.method.wrap_method( + self.list_valued_resources, + default_timeout=None, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, + 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.set_mute: gapic_v1.method.wrap_method( + self.set_mute, + 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.update_big_query_export: gapic_v1.method.wrap_method( + self.update_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.update_external_system: gapic_v1.method.wrap_method( + self.update_external_system, + default_timeout=None, + client_info=client_info, + ), + self.update_finding: gapic_v1.method.wrap_method( + self.update_finding, + default_timeout=None, + client_info=client_info, + ), + self.update_mute_config: gapic_v1.method.wrap_method( + self.update_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method.wrap_method( + self.update_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.update_resource_value_config: gapic_v1.method.wrap_method( + self.update_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=None, + client_info=client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + Union[ + securitycenter_service.BatchCreateResourceValueConfigsResponse, + Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, + Awaitable[bigquery_export.BigQueryExport] + ]]: + raise NotImplementedError() + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + Union[ + gcs_mute_config.MuteConfig, + Awaitable[gcs_mute_config.MuteConfig] + ]]: + raise NotImplementedError() + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, + Awaitable[bigquery_export.BigQueryExport] + ]]: + raise NotImplementedError() + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + Union[ + simulation.Simulation, + Awaitable[simulation.Simulation] + ]]: + raise NotImplementedError() + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + Union[ + valued_resource.ValuedResource, + Awaitable[valued_resource.ValuedResource] + ]]: + 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 get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + Union[ + mute_config.MuteConfig, + Awaitable[mute_config.MuteConfig] + ]]: + raise NotImplementedError() + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Union[ + notification_config.NotificationConfig, + Awaitable[notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + Union[ + resource_value_config.ResourceValueConfig, + Awaitable[resource_value_config.ResourceValueConfig] + ]]: + raise NotImplementedError() + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Union[ + source.Source, + Awaitable[source.Source] + ]]: + raise NotImplementedError() + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Union[ + securitycenter_service.GroupFindingsResponse, + Awaitable[securitycenter_service.GroupFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + Union[ + securitycenter_service.ListAttackPathsResponse, + Awaitable[securitycenter_service.ListAttackPathsResponse] + ]]: + raise NotImplementedError() + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + Union[ + securitycenter_service.ListBigQueryExportsResponse, + Awaitable[securitycenter_service.ListBigQueryExportsResponse] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Union[ + securitycenter_service.ListFindingsResponse, + Awaitable[securitycenter_service.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + Union[ + securitycenter_service.ListMuteConfigsResponse, + Awaitable[securitycenter_service.ListMuteConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Union[ + securitycenter_service.ListNotificationConfigsResponse, + Awaitable[securitycenter_service.ListNotificationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + Union[ + securitycenter_service.ListResourceValueConfigsResponse, + Awaitable[securitycenter_service.ListResourceValueConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Union[ + securitycenter_service.ListSourcesResponse, + Awaitable[securitycenter_service.ListSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + Union[ + securitycenter_service.ListValuedResourcesResponse, + Awaitable[securitycenter_service.ListValuedResourcesResponse] + ]]: + raise NotImplementedError() + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + 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 set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + 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 update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, + Awaitable[bigquery_export.BigQueryExport] + ]]: + raise NotImplementedError() + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + Union[ + gcs_external_system.ExternalSystem, + Awaitable[gcs_external_system.ExternalSystem] + ]]: + raise NotImplementedError() + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + Union[ + gcs_mute_config.MuteConfig, + Awaitable[gcs_mute_config.MuteConfig] + ]]: + raise NotImplementedError() + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + Union[ + gcs_resource_value_config.ResourceValueConfig, + Awaitable[gcs_resource_value_config.ResourceValueConfig] + ]]: + raise NotImplementedError() + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Union[ + gcs_security_marks.SecurityMarks, + Awaitable[gcs_security_marks.SecurityMarks] + ]]: + raise NotImplementedError() + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SecurityCenterTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py new file mode 100644 index 000000000000..3ab2b66d9b6e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py @@ -0,0 +1,1452 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource +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 empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V2 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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 batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + securitycenter_service.BatchCreateResourceValueConfigsResponse]: + r"""Return a callable for the batch create resource value + configs method over gRPC. + + Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + Returns: + Callable[[~.BatchCreateResourceValueConfigsRequest], + ~.BatchCreateResourceValueConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: + self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/BatchCreateResourceValueConfigs', + request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, + ) + return self._stubs['batch_create_resource_value_configs'] + + @property + def bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + operations_pb2.Operation]: + r"""Return a callable for the bulk mute findings method over gRPC. + + Kicks off an LRO to bulk mute findings for a parent + based on a filter. If no location is specified, findings + are muted in global. The parent can be either an + organization, folder, or project. The findings matched + by the filter will be muted after the LRO is done. + + Returns: + Callable[[~.BulkMuteFindingsRequest], + ~.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 'bulk_mute_findings' not in self._stubs: + self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/BulkMuteFindings', + request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['bulk_mute_findings'] + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + r"""Return a callable for the create big query export method over gRPC. + + Creates a BigQuery export. + + Returns: + Callable[[~.CreateBigQueryExportRequest], + ~.BigQueryExport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateBigQueryExport', + request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['create_big_query_export'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding in a location. The corresponding + source must exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + r"""Return a callable for the create mute config method over gRPC. + + Creates a mute config. + + Returns: + Callable[[~.CreateMuteConfigRequest], + ~.MuteConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateMuteConfig', + request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['create_mute_config'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete big query export method over gRPC. + + Deletes an existing BigQuery export. + + Returns: + Callable[[~.DeleteBigQueryExportRequest], + ~.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_big_query_export' not in self._stubs: + self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteBigQueryExport', + request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_big_query_export'] + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete mute config method over gRPC. + + Deletes an existing mute config. If no location is + specified, default is global. + + Returns: + Callable[[~.DeleteMuteConfigRequest], + ~.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_mute_config' not in self._stubs: + self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteMuteConfig', + request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_mute_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + ~.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_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete resource value config method over gRPC. + + Deletes a ResourceValueConfig. + + Returns: + Callable[[~.DeleteResourceValueConfigRequest], + ~.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_resource_value_config' not in self._stubs: + self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteResourceValueConfig', + request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_resource_value_config'] + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + bigquery_export.BigQueryExport]: + r"""Return a callable for the get big query export method over gRPC. + + Gets a BigQuery export. + + Returns: + Callable[[~.GetBigQueryExportRequest], + ~.BigQueryExport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_big_query_export' not in self._stubs: + self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetBigQueryExport', + request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['get_big_query_export'] + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + simulation.Simulation]: + r"""Return a callable for the get simulation method over gRPC. + + Get the simulation by name or the latest simulation + for the given organization. + + Returns: + Callable[[~.GetSimulationRequest], + ~.Simulation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_simulation' not in self._stubs: + self._stubs['get_simulation'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetSimulation', + request_serializer=securitycenter_service.GetSimulationRequest.serialize, + response_deserializer=simulation.Simulation.deserialize, + ) + return self._stubs['get_simulation'] + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + valued_resource.ValuedResource]: + r"""Return a callable for the get valued resource method over gRPC. + + Get the valued resource by name + + Returns: + Callable[[~.GetValuedResourceRequest], + ~.ValuedResource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_valued_resource' not in self._stubs: + self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetValuedResource', + request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, + response_deserializer=valued_resource.ValuedResource.deserialize, + ) + return self._stubs['get_valued_resource'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v2.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + mute_config.MuteConfig]: + r"""Return a callable for the get mute config method over gRPC. + + Gets a mute config. If no location is specified, + default is global. + + Returns: + Callable[[~.GetMuteConfigRequest], + ~.MuteConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_mute_config' not in self._stubs: + self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetMuteConfig', + request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, + response_deserializer=mute_config.MuteConfig.deserialize, + ) + return self._stubs['get_mute_config'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + resource_value_config.ResourceValueConfig]: + r"""Return a callable for the get resource value config method over gRPC. + + Gets a ResourceValueConfig. + + Returns: + Callable[[~.GetResourceValueConfigRequest], + ~.ResourceValueConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_resource_value_config' not in self._stubs: + self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetResourceValueConfig', + request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, + response_deserializer=resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['get_resource_value_config'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties in a location. If no location is + specified, findings are assumed to be in global + + To group across all sources provide a ``-`` as the source id. + The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + - ``/v2/folders/{folder_id}/sources/-/findings`` + - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` + - ``/v2/projects/{project_id}/sources/-/findings`` + - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + securitycenter_service.ListAttackPathsResponse]: + r"""Return a callable for the list attack paths method over gRPC. + + Lists the attack paths for a set of simulation + results or valued resources and filter. + + Returns: + Callable[[~.ListAttackPathsRequest], + ~.ListAttackPathsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_attack_paths' not in self._stubs: + self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListAttackPaths', + request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, + response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, + ) + return self._stubs['list_attack_paths'] + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + securitycenter_service.ListBigQueryExportsResponse]: + r"""Return a callable for the list big query exports method over gRPC. + + Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are returned. + + Returns: + Callable[[~.ListBigQueryExportsRequest], + ~.ListBigQueryExportsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_big_query_exports' not in self._stubs: + self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListBigQueryExports', + request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, + response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, + ) + return self._stubs['list_big_query_exports'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources for a given location provide a ``-`` + as the source id. If no location is specified, finding are + assumed to be in global. The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + 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.securitycenter.v2.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + securitycenter_service.ListMuteConfigsResponse]: + r"""Return a callable for the list mute configs method over gRPC. + + Lists mute configs. If no location is specified, + default is global. + + Returns: + Callable[[~.ListMuteConfigsRequest], + ~.ListMuteConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_mute_configs' not in self._stubs: + self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListMuteConfigs', + request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, + ) + return self._stubs['list_mute_configs'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + ~.ListNotificationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + securitycenter_service.ListResourceValueConfigsResponse]: + r"""Return a callable for the list resource value configs method over gRPC. + + Lists all ResourceValueConfigs. + + Returns: + Callable[[~.ListResourceValueConfigsRequest], + ~.ListResourceValueConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_resource_value_configs' not in self._stubs: + self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListResourceValueConfigs', + request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, + ) + return self._stubs['list_resource_value_configs'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + securitycenter_service.ListValuedResourcesResponse]: + r"""Return a callable for the list valued resources method over gRPC. + + Lists the valued resources for a set of simulation + results and filter. + + Returns: + Callable[[~.ListValuedResourcesRequest], + ~.ListValuedResourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_valued_resources' not in self._stubs: + self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListValuedResources', + request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, + response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, + ) + return self._stubs['list_valued_resources'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. If no location is + specified, finding is assumed to be in global + + Returns: + Callable[[~.SetFindingStateRequest], + ~.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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v2.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + finding.Finding]: + r"""Return a callable for the set mute method over gRPC. + + Updates the mute state of a finding. If no location + is specified, finding is assumed to be in global + + Returns: + Callable[[~.SetMuteRequest], + ~.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 'set_mute' not in self._stubs: + self._stubs['set_mute'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/SetMute', + request_serializer=securitycenter_service.SetMuteRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_mute'] + + @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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v2.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + r"""Return a callable for the update big query export method over gRPC. + + Updates a BigQuery export. + + Returns: + Callable[[~.UpdateBigQueryExportRequest], + ~.BigQueryExport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateBigQueryExport', + request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['update_big_query_export'] + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + gcs_external_system.ExternalSystem]: + r"""Return a callable for the update external system method over gRPC. + + Updates external system. This is for a given finding. + If no location is specified, finding is assumed to be in + global + + Returns: + Callable[[~.UpdateExternalSystemRequest], + ~.ExternalSystem]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_external_system' not in self._stubs: + self._stubs['update_external_system'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateExternalSystem', + request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, + response_deserializer=gcs_external_system.ExternalSystem.deserialize, + ) + return self._stubs['update_external_system'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. If no location is + specified, finding is assumed to be in global. The + corresponding source must exist for a finding creation + to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + r"""Return a callable for the update mute config method over gRPC. + + Updates a mute config. If no location is specified, + default is global. + + Returns: + Callable[[~.UpdateMuteConfigRequest], + ~.MuteConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateMuteConfig', + request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['update_mute_config'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + gcs_resource_value_config.ResourceValueConfig]: + r"""Return a callable for the update resource value config method over gRPC. + + Updates an existing ResourceValueConfigs with new + rules. + + Returns: + Callable[[~.UpdateResourceValueConfigRequest], + ~.ResourceValueConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: + self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateResourceValueConfig', + request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, + response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['update_resource_value_config'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. For Finding Security marks, + if no location is specified, finding is assumed to be in + global. Assets Security Marks can only be accessed + through global endpoint. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + 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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SecurityCenterGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 000000000000..b83a55a9f90c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,1657 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource +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 empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V2 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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._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 batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse]]: + r"""Return a callable for the batch create resource value + configs method over gRPC. + + Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + Returns: + Callable[[~.BatchCreateResourceValueConfigsRequest], + Awaitable[~.BatchCreateResourceValueConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: + self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/BatchCreateResourceValueConfigs', + request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, + ) + return self._stubs['batch_create_resource_value_configs'] + + @property + def bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the bulk mute findings method over gRPC. + + Kicks off an LRO to bulk mute findings for a parent + based on a filter. If no location is specified, findings + are muted in global. The parent can be either an + organization, folder, or project. The findings matched + by the filter will be muted after the LRO is done. + + Returns: + Callable[[~.BulkMuteFindingsRequest], + 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 'bulk_mute_findings' not in self._stubs: + self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/BulkMuteFindings', + request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['bulk_mute_findings'] + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport]]: + r"""Return a callable for the create big query export method over gRPC. + + Creates a BigQuery export. + + Returns: + Callable[[~.CreateBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateBigQueryExport', + request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['create_big_query_export'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding in a location. The corresponding + source must exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + 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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + Awaitable[gcs_mute_config.MuteConfig]]: + r"""Return a callable for the create mute config method over gRPC. + + Creates a mute config. + + Returns: + Callable[[~.CreateMuteConfigRequest], + Awaitable[~.MuteConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateMuteConfig', + request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['create_mute_config'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete big query export method over gRPC. + + Deletes an existing BigQuery export. + + Returns: + Callable[[~.DeleteBigQueryExportRequest], + 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_big_query_export' not in self._stubs: + self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteBigQueryExport', + request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_big_query_export'] + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete mute config method over gRPC. + + Deletes an existing mute config. If no location is + specified, default is global. + + Returns: + Callable[[~.DeleteMuteConfigRequest], + 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_mute_config' not in self._stubs: + self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteMuteConfig', + request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_mute_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + 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_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete resource value config method over gRPC. + + Deletes a ResourceValueConfig. + + Returns: + Callable[[~.DeleteResourceValueConfigRequest], + 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_resource_value_config' not in self._stubs: + self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteResourceValueConfig', + request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_resource_value_config'] + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport]]: + r"""Return a callable for the get big query export method over gRPC. + + Gets a BigQuery export. + + Returns: + Callable[[~.GetBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_big_query_export' not in self._stubs: + self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetBigQueryExport', + request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['get_big_query_export'] + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + Awaitable[simulation.Simulation]]: + r"""Return a callable for the get simulation method over gRPC. + + Get the simulation by name or the latest simulation + for the given organization. + + Returns: + Callable[[~.GetSimulationRequest], + Awaitable[~.Simulation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_simulation' not in self._stubs: + self._stubs['get_simulation'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetSimulation', + request_serializer=securitycenter_service.GetSimulationRequest.serialize, + response_deserializer=simulation.Simulation.deserialize, + ) + return self._stubs['get_simulation'] + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + Awaitable[valued_resource.ValuedResource]]: + r"""Return a callable for the get valued resource method over gRPC. + + Get the valued resource by name + + Returns: + Callable[[~.GetValuedResourceRequest], + Awaitable[~.ValuedResource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_valued_resource' not in self._stubs: + self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetValuedResource', + request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, + response_deserializer=valued_resource.ValuedResource.deserialize, + ) + return self._stubs['get_valued_resource'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v2.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + Awaitable[mute_config.MuteConfig]]: + r"""Return a callable for the get mute config method over gRPC. + + Gets a mute config. If no location is specified, + default is global. + + Returns: + Callable[[~.GetMuteConfigRequest], + Awaitable[~.MuteConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_mute_config' not in self._stubs: + self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetMuteConfig', + request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, + response_deserializer=mute_config.MuteConfig.deserialize, + ) + return self._stubs['get_mute_config'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Awaitable[notification_config.NotificationConfig]]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + Awaitable[resource_value_config.ResourceValueConfig]]: + r"""Return a callable for the get resource value config method over gRPC. + + Gets a ResourceValueConfig. + + Returns: + Callable[[~.GetResourceValueConfigRequest], + Awaitable[~.ResourceValueConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_resource_value_config' not in self._stubs: + self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetResourceValueConfig', + request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, + response_deserializer=resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['get_resource_value_config'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse]]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties in a location. If no location is + specified, findings are assumed to be in global + + To group across all sources provide a ``-`` as the source id. + The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + - ``/v2/folders/{folder_id}/sources/-/findings`` + - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` + - ``/v2/projects/{project_id}/sources/-/findings`` + - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + Awaitable[securitycenter_service.ListAttackPathsResponse]]: + r"""Return a callable for the list attack paths method over gRPC. + + Lists the attack paths for a set of simulation + results or valued resources and filter. + + Returns: + Callable[[~.ListAttackPathsRequest], + Awaitable[~.ListAttackPathsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_attack_paths' not in self._stubs: + self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListAttackPaths', + request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, + response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, + ) + return self._stubs['list_attack_paths'] + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + Awaitable[securitycenter_service.ListBigQueryExportsResponse]]: + r"""Return a callable for the list big query exports method over gRPC. + + Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are returned. + + Returns: + Callable[[~.ListBigQueryExportsRequest], + Awaitable[~.ListBigQueryExportsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_big_query_exports' not in self._stubs: + self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListBigQueryExports', + request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, + response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, + ) + return self._stubs['list_big_query_exports'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources for a given location provide a ``-`` + as the source id. If no location is specified, finding are + assumed to be in global. The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + 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.securitycenter.v2.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + Awaitable[securitycenter_service.ListMuteConfigsResponse]]: + r"""Return a callable for the list mute configs method over gRPC. + + Lists mute configs. If no location is specified, + default is global. + + Returns: + Callable[[~.ListMuteConfigsRequest], + Awaitable[~.ListMuteConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_mute_configs' not in self._stubs: + self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListMuteConfigs', + request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, + ) + return self._stubs['list_mute_configs'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + Awaitable[~.ListNotificationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + Awaitable[securitycenter_service.ListResourceValueConfigsResponse]]: + r"""Return a callable for the list resource value configs method over gRPC. + + Lists all ResourceValueConfigs. + + Returns: + Callable[[~.ListResourceValueConfigsRequest], + Awaitable[~.ListResourceValueConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_resource_value_configs' not in self._stubs: + self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListResourceValueConfigs', + request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, + ) + return self._stubs['list_resource_value_configs'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse]]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + Awaitable[securitycenter_service.ListValuedResourcesResponse]]: + r"""Return a callable for the list valued resources method over gRPC. + + Lists the valued resources for a set of simulation + results and filter. + + Returns: + Callable[[~.ListValuedResourcesRequest], + Awaitable[~.ListValuedResourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_valued_resources' not in self._stubs: + self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListValuedResources', + request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, + response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, + ) + return self._stubs['list_valued_resources'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. If no location is + specified, finding is assumed to be in global + + Returns: + Callable[[~.SetFindingStateRequest], + 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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v2.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set mute method over gRPC. + + Updates the mute state of a finding. If no location + is specified, finding is assumed to be in global + + Returns: + Callable[[~.SetMuteRequest], + 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 'set_mute' not in self._stubs: + self._stubs['set_mute'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/SetMute', + request_serializer=securitycenter_service.SetMuteRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_mute'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.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.cloud.securitycenter.v2.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport]]: + r"""Return a callable for the update big query export method over gRPC. + + Updates a BigQuery export. + + Returns: + Callable[[~.UpdateBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateBigQueryExport', + request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['update_big_query_export'] + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + Awaitable[gcs_external_system.ExternalSystem]]: + r"""Return a callable for the update external system method over gRPC. + + Updates external system. This is for a given finding. + If no location is specified, finding is assumed to be in + global + + Returns: + Callable[[~.UpdateExternalSystemRequest], + Awaitable[~.ExternalSystem]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_external_system' not in self._stubs: + self._stubs['update_external_system'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateExternalSystem', + request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, + response_deserializer=gcs_external_system.ExternalSystem.deserialize, + ) + return self._stubs['update_external_system'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. If no location is + specified, finding is assumed to be in global. The + corresponding source must exist for a finding creation + to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + 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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + Awaitable[gcs_mute_config.MuteConfig]]: + r"""Return a callable for the update mute config method over gRPC. + + Updates a mute config. If no location is specified, + default is global. + + Returns: + Callable[[~.UpdateMuteConfigRequest], + Awaitable[~.MuteConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateMuteConfig', + request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['update_mute_config'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + Awaitable[gcs_resource_value_config.ResourceValueConfig]]: + r"""Return a callable for the update resource value config method over gRPC. + + Updates an existing ResourceValueConfigs with new + rules. + + Returns: + Callable[[~.UpdateResourceValueConfigRequest], + Awaitable[~.ResourceValueConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: + self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateResourceValueConfig', + request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, + response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['update_resource_value_config'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks]]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. For Finding Security marks, + if no location is specified, finding is assumed to be in + global. Assets Security Marks can only be accessed + through global endpoint. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_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.batch_create_resource_value_configs: gapic_v1.method_async.wrap_method( + self.batch_create_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.bulk_mute_findings: gapic_v1.method_async.wrap_method( + self.bulk_mute_findings, + default_timeout=None, + client_info=client_info, + ), + self.create_big_query_export: gapic_v1.method_async.wrap_method( + self.create_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.create_finding: gapic_v1.method_async.wrap_method( + self.create_finding, + default_timeout=None, + client_info=client_info, + ), + self.create_mute_config: gapic_v1.method_async.wrap_method( + self.create_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method_async.wrap_method( + self.create_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.create_source: gapic_v1.method_async.wrap_method( + self.create_source, + default_timeout=None, + client_info=client_info, + ), + self.delete_big_query_export: gapic_v1.method_async.wrap_method( + self.delete_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.delete_mute_config: gapic_v1.method_async.wrap_method( + self.delete_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method_async.wrap_method( + self.delete_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_resource_value_config: gapic_v1.method_async.wrap_method( + self.delete_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_big_query_export: gapic_v1.method_async.wrap_method( + self.get_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.get_simulation: gapic_v1.method_async.wrap_method( + self.get_simulation, + default_timeout=None, + client_info=client_info, + ), + self.get_valued_resource: gapic_v1.method_async.wrap_method( + self.get_valued_resource, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_mute_config: gapic_v1.method_async.wrap_method( + self.get_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.get_notification_config: gapic_v1.method_async.wrap_method( + self.get_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.get_resource_value_config: gapic_v1.method_async.wrap_method( + self.get_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_source: gapic_v1.method_async.wrap_method( + self.get_source, + default_timeout=None, + client_info=client_info, + ), + self.group_findings: gapic_v1.method_async.wrap_method( + self.group_findings, + default_timeout=None, + client_info=client_info, + ), + self.list_attack_paths: gapic_v1.method_async.wrap_method( + self.list_attack_paths, + default_timeout=None, + client_info=client_info, + ), + self.list_big_query_exports: gapic_v1.method_async.wrap_method( + self.list_big_query_exports, + default_timeout=None, + client_info=client_info, + ), + self.list_findings: gapic_v1.method_async.wrap_method( + self.list_findings, + default_timeout=None, + client_info=client_info, + ), + self.list_mute_configs: gapic_v1.method_async.wrap_method( + self.list_mute_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method_async.wrap_method( + self.list_notification_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_resource_value_configs: gapic_v1.method_async.wrap_method( + self.list_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_sources: gapic_v1.method_async.wrap_method( + self.list_sources, + default_timeout=None, + client_info=client_info, + ), + self.list_valued_resources: gapic_v1.method_async.wrap_method( + self.list_valued_resources, + default_timeout=None, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method_async.wrap_method( + self.set_finding_state, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_mute: gapic_v1.method_async.wrap_method( + self.set_mute, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.update_big_query_export: gapic_v1.method_async.wrap_method( + self.update_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.update_external_system: gapic_v1.method_async.wrap_method( + self.update_external_system, + default_timeout=None, + client_info=client_info, + ), + self.update_finding: gapic_v1.method_async.wrap_method( + self.update_finding, + default_timeout=None, + client_info=client_info, + ), + self.update_mute_config: gapic_v1.method_async.wrap_method( + self.update_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method_async.wrap_method( + self.update_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.update_resource_value_config: gapic_v1.method_async.wrap_method( + self.update_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method_async.wrap_method( + self.update_security_marks, + default_timeout=None, + client_info=client_info, + ), + self.update_source: gapic_v1.method_async.wrap_method( + self.update_source, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return 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"] + + +__all__ = ( + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py new file mode 100644 index 000000000000..251cc55815bd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py @@ -0,0 +1,5820 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # 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 path_template +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 +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SecurityCenterRestInterceptor: + """Interceptor for SecurityCenter. + + 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 SecurityCenterRestTransport. + + .. code-block:: python + class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): + def pre_batch_create_resource_value_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_resource_value_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_bulk_mute_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_bulk_mute_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_resource_value_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_simulation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_simulation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_valued_resource(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_valued_resource(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_attack_paths(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_attack_paths(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_big_query_exports(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_big_query_exports(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_mute_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_mute_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_notification_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_notification_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_resource_value_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_resource_value_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_valued_resources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_valued_resources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_finding_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_finding_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_mute(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_mute(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_external_system(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_external_system(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_resource_value_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_security_marks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_security_marks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_source(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) + client = SecurityCenterClient(transport=transport) + + + """ + def pre_batch_create_resource_value_configs(self, request: securitycenter_service.BatchCreateResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BatchCreateResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_create_resource_value_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_batch_create_resource_value_configs(self, response: securitycenter_service.BatchCreateResourceValueConfigsResponse) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + """Post-rpc interceptor for batch_create_resource_value_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_bulk_mute_findings(self, request: securitycenter_service.BulkMuteFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BulkMuteFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for bulk_mute_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_bulk_mute_findings(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for bulk_mute_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_big_query_export(self, request: securitycenter_service.CreateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for create_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for create_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_mute_config(self, request: securitycenter_service.CreateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: + """Post-rpc interceptor for create_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_notification_config(self, request: securitycenter_service.CreateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for create_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_delete_big_query_export(self, request: securitycenter_service.DeleteBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_mute_config(self, request: securitycenter_service.DeleteMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_notification_config(self, request: securitycenter_service.DeleteNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_resource_value_config(self, request: securitycenter_service.DeleteResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteResourceValueConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_get_big_query_export(self, request: securitycenter_service.GetBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for get_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_mute_config(self, request: securitycenter_service.GetMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_mute_config(self, response: mute_config.MuteConfig) -> mute_config.MuteConfig: + """Post-rpc interceptor for get_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_notification_config(self, request: securitycenter_service.GetNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_notification_config(self, response: notification_config.NotificationConfig) -> notification_config.NotificationConfig: + """Post-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_resource_value_config(self, request: securitycenter_service.GetResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetResourceValueConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_resource_value_config(self, response: resource_value_config.ResourceValueConfig) -> resource_value_config.ResourceValueConfig: + """Post-rpc interceptor for get_resource_value_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_simulation(self, request: securitycenter_service.GetSimulationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSimulationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_simulation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_simulation(self, response: simulation.Simulation) -> simulation.Simulation: + """Post-rpc interceptor for get_simulation + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_source(self, response: source.Source) -> source.Source: + """Post-rpc interceptor for get_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_valued_resource(self, request: securitycenter_service.GetValuedResourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetValuedResourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_valued_resource + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_valued_resource(self, response: valued_resource.ValuedResource) -> valued_resource.ValuedResource: + """Post-rpc interceptor for get_valued_resource + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: + """Post-rpc interceptor for group_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_attack_paths(self, request: securitycenter_service.ListAttackPathsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAttackPathsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_attack_paths + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_attack_paths(self, response: securitycenter_service.ListAttackPathsResponse) -> securitycenter_service.ListAttackPathsResponse: + """Post-rpc interceptor for list_attack_paths + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_big_query_exports(self, request: securitycenter_service.ListBigQueryExportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListBigQueryExportsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_big_query_exports + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_big_query_exports(self, response: securitycenter_service.ListBigQueryExportsResponse) -> securitycenter_service.ListBigQueryExportsResponse: + """Post-rpc interceptor for list_big_query_exports + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. + """ + return request, metadata + + def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_mute_configs(self, request: securitycenter_service.ListMuteConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListMuteConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_mute_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_mute_configs(self, response: securitycenter_service.ListMuteConfigsResponse) -> securitycenter_service.ListMuteConfigsResponse: + """Post-rpc interceptor for list_mute_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_notification_configs(self, request: securitycenter_service.ListNotificationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListNotificationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_notification_configs(self, response: securitycenter_service.ListNotificationConfigsResponse) -> securitycenter_service.ListNotificationConfigsResponse: + """Post-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_resource_value_configs(self, request: securitycenter_service.ListResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_resource_value_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_resource_value_configs(self, response: securitycenter_service.ListResourceValueConfigsResponse) -> securitycenter_service.ListResourceValueConfigsResponse: + """Post-rpc interceptor for list_resource_value_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_sources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: + """Post-rpc interceptor for list_sources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_valued_resources(self, request: securitycenter_service.ListValuedResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListValuedResourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_valued_resources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_valued_resources(self, response: securitycenter_service.ListValuedResourcesResponse) -> securitycenter_service.ListValuedResourcesResponse: + """Post-rpc interceptor for list_valued_resources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_set_mute(self, request: securitycenter_service.SetMuteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetMuteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_mute + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_mute(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_mute + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_big_query_export(self, request: securitycenter_service.UpdateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for update_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_external_system(self, request: securitycenter_service.UpdateExternalSystemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateExternalSystemRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_external_system + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_external_system(self, response: gcs_external_system.ExternalSystem) -> gcs_external_system.ExternalSystem: + """Post-rpc interceptor for update_external_system + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for update_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_mute_config(self, request: securitycenter_service.UpdateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: + """Post-rpc interceptor for update_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_notification_config(self, request: securitycenter_service.UpdateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_resource_value_config(self, request: securitycenter_service.UpdateResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateResourceValueConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_resource_value_config(self, response: gcs_resource_value_config.ResourceValueConfig) -> gcs_resource_value_config.ResourceValueConfig: + """Post-rpc interceptor for update_resource_value_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: + """Post-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for update_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SecurityCenterRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SecurityCenterRestInterceptor + + +class SecurityCenterRestTransport(SecurityCenterTransport): + """REST backend transport for SecurityCenter. + + V2 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[SecurityCenterRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 + 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 + ) + 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 SecurityCenterRestInterceptor() + 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': '/v2/{name=organizations/*/operations/*}:cancel', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v2/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v2/{name=organizations/*/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="v2") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _BatchCreateResourceValueConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("BatchCreateResourceValueConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.BatchCreateResourceValueConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Call the batch create resource + value configs method over HTTP. + + Args: + request (~.securitycenter_service.BatchCreateResourceValueConfigsRequest): + The request object. Request message to create multiple + resource value configs + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*}/resourceValueConfigs:batchCreate', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/locations/*}/resourceValueConfigs:batchCreate', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_batch_create_resource_value_configs(request, metadata) + pb_request = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.BatchCreateResourceValueConfigsResponse() + pb_resp = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_create_resource_value_configs(resp) + return resp + + class _BulkMuteFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("BulkMuteFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.BulkMuteFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the bulk mute findings method over HTTP. + + Args: + request (~.securitycenter_service.BulkMuteFindingsRequest): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/locations/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*/locations/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*/locations/*}/findings:bulkMute', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_bulk_mute_findings(request, metadata) + pb_request = securitycenter_service.BulkMuteFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_bulk_mute_findings(resp) + return resp + + class _CreateBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "bigQueryExportId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> bigquery_export.BigQueryExport: + r"""Call the create big query export method over HTTP. + + Args: + request (~.securitycenter_service.CreateBigQueryExportRequest): + The request object. Request message for creating a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/locations/*}/bigQueryExports', + 'body': 'big_query_export', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*/locations/*}/bigQueryExports', + 'body': 'big_query_export', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*/locations/*}/bigQueryExports', + 'body': 'big_query_export', + }, + ] + request, metadata = self._interceptor.pre_create_big_query_export(request, metadata) + pb_request = securitycenter_service.CreateBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_big_query_export(resp) + return resp + + class _CreateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "findingId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the create finding method over HTTP. + + Args: + request (~.securitycenter_service.CreateFindingRequest): + The request object. Request message for creating a + finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/sources/*/locations/*}/findings', + 'body': 'finding', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/sources/*}/findings', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_create_finding(request, metadata) + pb_request = securitycenter_service.CreateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_finding(resp) + return resp + + class _CreateMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "muteConfigId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_mute_config.MuteConfig: + r"""Call the create mute config method over HTTP. + + Args: + request (~.securitycenter_service.CreateMuteConfigRequest): + The request object. Request message for creating a mute + config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/locations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*/locations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*/locations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*}/muteConfigs', + 'body': 'mute_config', + }, + ] + request, metadata = self._interceptor.pre_create_mute_config(request, metadata) + pb_request = securitycenter_service.CreateMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_mute_config.MuteConfig() + pb_resp = gcs_mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_mute_config(resp) + return resp + + class _CreateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "configId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the create notification + config method over HTTP. + + Args: + request (~.securitycenter_service.CreateNotificationConfigRequest): + The request object. Request message for creating a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/locations/*}/notificationConfigs', + 'body': 'notification_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*/locations/*}/notificationConfigs', + 'body': 'notification_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*/locations/*}/notificationConfigs', + 'body': 'notification_config', + }, + ] + request, metadata = self._interceptor.pre_create_notification_config(request, metadata) + pb_request = securitycenter_service.CreateNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_notification_config(resp) + return resp + + class _CreateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the create source method over HTTP. + + Args: + request (~.securitycenter_service.CreateSourceRequest): + The request object. Request message for creating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*}/sources', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_create_source(request, metadata) + pb_request = securitycenter_service.CreateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_source(resp) + return resp + + class _DeleteBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete big query export method over HTTP. + + Args: + request (~.securitycenter_service.DeleteBigQueryExportRequest): + The request object. Request message for deleting a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/locations/*/bigQueryExports/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=folders/*/locations/*/bigQueryExports/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=projects/*/locations/*/bigQueryExports/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_big_query_export(request, metadata) + pb_request = securitycenter_service.DeleteBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete mute config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteMuteConfigRequest): + The request object. Request message for deleting a mute + config. If no location is specified, + default is global. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=folders/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=folders/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=projects/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=projects/*/locations/*/muteConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_mute_config(request, metadata) + pb_request = securitycenter_service.DeleteMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete notification + config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteNotificationConfigRequest): + The request object. Request message for deleting a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/locations/*/notificationConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=folders/*/locations/*/notificationConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=projects/*/locations/*/notificationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_notification_config(request, metadata) + pb_request = securitycenter_service.DeleteNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteResourceValueConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteResourceValueConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete resource value + config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteResourceValueConfigRequest): + The request object. Request message to delete resource + value config + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/resourceValueConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/locations/*/resourceValueConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_resource_value_config(request, metadata) + pb_request = securitycenter_service.DeleteResourceValueConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _GetBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("GetBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> bigquery_export.BigQueryExport: + r"""Call the get big query export method over HTTP. + + Args: + request (~.securitycenter_service.GetBigQueryExportRequest): + The request object. Request message for retrieving a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/locations/*/bigQueryExports/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=folders/*/locations/*/bigQueryExports/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=projects/*/locations/*/bigQueryExports/*}', + }, + ] + request, metadata = self._interceptor.pre_get_big_query_export(request, metadata) + pb_request = securitycenter_service.GetBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_big_query_export(resp) + return resp + + class _GetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{resource=organizations/*/sources/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> mute_config.MuteConfig: + r"""Call the get mute config method over HTTP. + + Args: + request (~.securitycenter_service.GetMuteConfigRequest): + The request object. Request message for retrieving a mute + config. If no location is specified, + default is global. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=folders/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=folders/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=projects/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=projects/*/locations/*/muteConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_mute_config(request, metadata) + pb_request = securitycenter_service.GetMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = mute_config.MuteConfig() + pb_resp = mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_mute_config(resp) + return resp + + class _GetNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> notification_config.NotificationConfig: + r"""Call the get notification config method over HTTP. + + Args: + request (~.securitycenter_service.GetNotificationConfigRequest): + The request object. Request message for getting a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/locations/*/notificationConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=folders/*/locations/*/notificationConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=projects/*/locations/*/notificationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_notification_config(request, metadata) + pb_request = securitycenter_service.GetNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = notification_config.NotificationConfig() + pb_resp = notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_notification_config(resp) + return resp + + class _GetResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetResourceValueConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetResourceValueConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resource_value_config.ResourceValueConfig: + r"""Call the get resource value config method over HTTP. + + Args: + request (~.securitycenter_service.GetResourceValueConfigRequest): + The request object. Request message to get resource value + config + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource_value_config.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/resourceValueConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/locations/*/resourceValueConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_resource_value_config(request, metadata) + pb_request = securitycenter_service.GetResourceValueConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource_value_config.ResourceValueConfig() + pb_resp = resource_value_config.ResourceValueConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_resource_value_config(resp) + return resp + + class _GetSimulation(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSimulation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSimulationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> simulation.Simulation: + r"""Call the get simulation method over HTTP. + + Args: + request (~.securitycenter_service.GetSimulationRequest): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.simulation.Simulation: + Attack path simulation + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/simulations/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/locations/*/simulations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_simulation(request, metadata) + pb_request = securitycenter_service.GetSimulationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = simulation.Simulation() + pb_resp = simulation.Simulation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_simulation(resp) + return resp + + class _GetSource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> source.Source: + r"""Call the get source method over HTTP. + + Args: + request (~.securitycenter_service.GetSourceRequest): + The request object. Request message for getting a source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/sources/*}', + }, + ] + request, metadata = self._interceptor.pre_get_source(request, metadata) + pb_request = securitycenter_service.GetSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = source.Source() + pb_resp = source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_source(resp) + return resp + + class _GetValuedResource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetValuedResource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetValuedResourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> valued_resource.ValuedResource: + r"""Call the get valued resource method over HTTP. + + Args: + request (~.securitycenter_service.GetValuedResourceRequest): + The request object. Request message for getting a valued + resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.valued_resource.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/simulations/*/valuedResources/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/locations/*/simulations/*/valuedResources/*}', + }, + ] + request, metadata = self._interceptor.pre_get_valued_resource(request, metadata) + pb_request = securitycenter_service.GetValuedResourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = valued_resource.ValuedResource() + pb_resp = valued_resource.ValuedResource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_valued_resource(resp) + return resp + + class _GroupFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupFindingsResponse: + r"""Call the group findings method over HTTP. + + Args: + request (~.securitycenter_service.GroupFindingsRequest): + The request object. Request message for grouping by + findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupFindingsResponse: + Response message for group by + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/sources/*/locations/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*/sources/*/locations/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*/sources/*/locations/*}/findings:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_findings(request, metadata) + pb_request = securitycenter_service.GroupFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupFindingsResponse() + pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_findings(resp) + return resp + + class _ListAttackPaths(SecurityCenterRestStub): + def __hash__(self): + return hash("ListAttackPaths") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListAttackPathsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListAttackPathsResponse: + r"""Call the list attack paths method over HTTP. + + Args: + request (~.securitycenter_service.ListAttackPathsRequest): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListAttackPathsResponse: + Response message for listing the + attack paths for a given simulation or + valued resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/simulations/*}/attackPaths', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/simulations/*/valuedResources/*}/attackPaths', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/locations/*/simulations/*/valuedResources/*}/attackPaths', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/simulations/*/attackExposureResults/*}/attackPaths', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/locations/*/simulations/*/attackExposureResults/*}/attackPaths', + }, + ] + request, metadata = self._interceptor.pre_list_attack_paths(request, metadata) + pb_request = securitycenter_service.ListAttackPathsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListAttackPathsResponse() + pb_resp = securitycenter_service.ListAttackPathsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_attack_paths(resp) + return resp + + class _ListBigQueryExports(SecurityCenterRestStub): + def __hash__(self): + return hash("ListBigQueryExports") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListBigQueryExportsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListBigQueryExportsResponse: + r"""Call the list big query exports method over HTTP. + + Args: + request (~.securitycenter_service.ListBigQueryExportsRequest): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or 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: + ~.securitycenter_service.ListBigQueryExportsResponse: + Response message for listing BigQuery + exports. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/locations/*}/bigQueryExports', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*/locations/*}/bigQueryExports', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*/locations/*}/bigQueryExports', + }, + ] + request, metadata = self._interceptor.pre_list_big_query_exports(request, metadata) + pb_request = securitycenter_service.ListBigQueryExportsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListBigQueryExportsResponse() + pb_resp = securitycenter_service.ListBigQueryExportsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_big_query_exports(resp) + return resp + + class _ListFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("ListFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.securitycenter_service.ListFindingsRequest): + The request object. Request message for listing findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListFindingsResponse: + Response message for listing + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/sources/*/locations/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*/sources/*/locations/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*/sources/*/locations/*}/findings', + }, + ] + request, metadata = self._interceptor.pre_list_findings(request, metadata) + pb_request = securitycenter_service.ListFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListFindingsResponse() + pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListMuteConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListMuteConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListMuteConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListMuteConfigsResponse: + r"""Call the list mute configs method over HTTP. + + Args: + request (~.securitycenter_service.ListMuteConfigsRequest): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or project. If no + location is specified, default is + global. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListMuteConfigsResponse: + Response message for listing mute + configs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/locations/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*/locations/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*/locations/*}/muteConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_mute_configs(request, metadata) + pb_request = securitycenter_service.ListMuteConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListMuteConfigsResponse() + pb_resp = securitycenter_service.ListMuteConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_mute_configs(resp) + return resp + + class _ListNotificationConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListNotificationConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListNotificationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListNotificationConfigsResponse: + r"""Call the list notification configs method over HTTP. + + Args: + request (~.securitycenter_service.ListNotificationConfigsRequest): + The request object. Request message for listing + notification configs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListNotificationConfigsResponse: + Response message for listing + notification configs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/locations/*}/notificationConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*/locations/*}/notificationConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*/locations/*}/notificationConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_notification_configs(request, metadata) + pb_request = securitycenter_service.ListNotificationConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListNotificationConfigsResponse() + pb_resp = securitycenter_service.ListNotificationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_notification_configs(resp) + return resp + + class _ListResourceValueConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListResourceValueConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListResourceValueConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListResourceValueConfigsResponse: + r"""Call the list resource value + configs method over HTTP. + + Args: + request (~.securitycenter_service.ListResourceValueConfigsRequest): + The request object. Request message to list resource + value configs of a parent + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListResourceValueConfigsResponse: + Response message to list resource + value configs + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*}/resourceValueConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/locations/*}/resourceValueConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_resource_value_configs(request, metadata) + pb_request = securitycenter_service.ListResourceValueConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListResourceValueConfigsResponse() + pb_resp = securitycenter_service.ListResourceValueConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_resource_value_configs(resp) + return resp + + class _ListSources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListSources") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListSourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListSourcesResponse: + r"""Call the list sources method over HTTP. + + Args: + request (~.securitycenter_service.ListSourcesRequest): + The request object. Request message for listing sources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListSourcesResponse: + Response message for listing sources. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*}/sources', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*}/sources', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*}/sources', + }, + ] + request, metadata = self._interceptor.pre_list_sources(request, metadata) + pb_request = securitycenter_service.ListSourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListSourcesResponse() + pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sources(resp) + return resp + + class _ListValuedResources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListValuedResources") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListValuedResourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListValuedResourcesResponse: + r"""Call the list valued resources method over HTTP. + + Args: + request (~.securitycenter_service.ListValuedResourcesRequest): + The request object. Request message for listing the + valued resources for a given simulation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListValuedResourcesResponse: + Response message for listing the + valued resources for a given simulation. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/simulations/*}/valuedResources', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/simulations/*/attackExposureResults/*}/valuedResources', + }, + ] + request, metadata = self._interceptor.pre_list_valued_resources(request, metadata) + pb_request = securitycenter_service.ListValuedResourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListValuedResourcesResponse() + pb_resp = securitycenter_service.ListValuedResourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_valued_resources(resp) + return resp + + class _SetFindingState(SecurityCenterRestStub): + def __hash__(self): + return hash("SetFindingState") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SetFindingStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the set finding state method over HTTP. + + Args: + request (~.securitycenter_service.SetFindingStateRequest): + The request object. Request message for updating a + finding's state. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{name=organizations/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=organizations/*/sources/*/locations/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=folders/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=folders/*/sources/*/locations/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=projects/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=projects/*/sources/*/locations/*/findings/*}:setState', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_finding_state(request, metadata) + pb_request = securitycenter_service.SetFindingStateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_set_finding_state(resp) + return resp + + class _SetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{resource=organizations/*/sources/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _SetMute(SecurityCenterRestStub): + def __hash__(self): + return hash("SetMute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SetMuteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the set mute method over HTTP. + + Args: + request (~.securitycenter_service.SetMuteRequest): + The request object. Request message for updating a + finding's mute status. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{name=organizations/*/sources/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=organizations/*/sources/*/locations/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=folders/*/sources/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=folders/*/sources/*/locations/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=projects/*/sources/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=projects/*/sources/*/locations/*/findings/*}:setMute', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_mute(request, metadata) + pb_request = securitycenter_service.SetMuteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_set_mute(resp) + return resp + + class _TestIamPermissions(SecurityCenterRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{resource=organizations/*/sources/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UpdateBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> bigquery_export.BigQueryExport: + r"""Call the update big query export method over HTTP. + + Args: + request (~.securitycenter_service.UpdateBigQueryExportRequest): + The request object. Request message for updating a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{big_query_export.name=organizations/*/locations/*/bigQueryExports/*}', + 'body': 'big_query_export', + }, +{ + 'method': 'patch', + 'uri': '/v2/{big_query_export.name=folders/*/locations/*/bigQueryExports/*}', + 'body': 'big_query_export', + }, +{ + 'method': 'patch', + 'uri': '/v2/{big_query_export.name=projects/*/locations/*/bigQueryExports/*}', + 'body': 'big_query_export', + }, + ] + request, metadata = self._interceptor.pre_update_big_query_export(request, metadata) + pb_request = securitycenter_service.UpdateBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_big_query_export(resp) + return resp + + class _UpdateExternalSystem(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateExternalSystem") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateExternalSystemRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_external_system.ExternalSystem: + r"""Call the update external system method over HTTP. + + Args: + request (~.securitycenter_service.UpdateExternalSystemRequest): + The request object. Request message for updating a + ExternalSystem resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_external_system.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v2/{external_system.name=organizations/*/sources/*/locations/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v2/{external_system.name=folders/*/sources/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v2/{external_system.name=folders/*/sources/*/locations/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v2/{external_system.name=projects/*/sources/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v2/{external_system.name=projects/*/sources/*/locations/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, + ] + request, metadata = self._interceptor.pre_update_external_system(request, metadata) + pb_request = securitycenter_service.UpdateExternalSystemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_external_system.ExternalSystem() + pb_resp = gcs_external_system.ExternalSystem.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_external_system(resp) + return resp + + class _UpdateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the update finding method over HTTP. + + Args: + request (~.securitycenter_service.UpdateFindingRequest): + The request object. Request message for updating or + creating a finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{finding.name=organizations/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v2/{finding.name=organizations/*/sources/*/locations/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v2/{finding.name=folders/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v2/{finding.name=folders/*/sources/*/locations/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v2/{finding.name=projects/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v2/{finding.name=projects/*/sources/*/locations/*/findings/*}', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_update_finding(request, metadata) + pb_request = securitycenter_service.UpdateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_finding(resp) + return resp + + class _UpdateMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_mute_config.MuteConfig: + r"""Call the update mute config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateMuteConfigRequest): + The request object. Request message for updating a mute + config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{mute_config.name=organizations/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{mute_config.name=organizations/*/locations/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{mute_config.name=folders/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{mute_config.name=folders/*/locations/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{mute_config.name=projects/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{mute_config.name=projects/*/locations/*/muteConfigs/*}', + 'body': 'mute_config', + }, + ] + request, metadata = self._interceptor.pre_update_mute_config(request, metadata) + pb_request = securitycenter_service.UpdateMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_mute_config.MuteConfig() + pb_resp = gcs_mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_mute_config(resp) + return resp + + class _UpdateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the update notification + config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateNotificationConfigRequest): + The request object. Request message for updating a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{notification_config.name=organizations/*/locations/*/notificationConfigs/*}', + 'body': 'notification_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{notification_config.name=folders/*/locations/*/notificationConfigs/*}', + 'body': 'notification_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{notification_config.name=projects/*/locations/*/notificationConfigs/*}', + 'body': 'notification_config', + }, + ] + request, metadata = self._interceptor.pre_update_notification_config(request, metadata) + pb_request = securitycenter_service.UpdateNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_notification_config(resp) + return resp + + class _UpdateResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateResourceValueConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateResourceValueConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Call the update resource value + config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateResourceValueConfigRequest): + The request object. Request message to update resource + value config + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_resource_value_config.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{resource_value_config.name=organizations/*/resourceValueConfigs/*}', + 'body': 'resource_value_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{resource_value_config.name=organizations/*/locations/*/resourceValueConfigs/*}', + 'body': 'resource_value_config', + }, + ] + request, metadata = self._interceptor.pre_update_resource_value_config(request, metadata) + pb_request = securitycenter_service.UpdateResourceValueConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_resource_value_config.ResourceValueConfig() + pb_resp = gcs_resource_value_config.ResourceValueConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_resource_value_config(resp) + return resp + + class _UpdateSecurityMarks(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSecurityMarks") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSecurityMarksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_security_marks.SecurityMarks: + r"""Call the update security marks method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSecurityMarksRequest): + The request object. Request message for updating a + SecurityMarks resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=organizations/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=organizations/*/sources/*/locations/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=folders/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=folders/*/sources/*/locations/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=projects/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=projects/*/sources/*/locations/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, + ] + request, metadata = self._interceptor.pre_update_security_marks(request, metadata) + pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_security_marks.SecurityMarks() + pb_resp = gcs_security_marks.SecurityMarks.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_security_marks(resp) + return resp + + class _UpdateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the update source method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSourceRequest): + The request object. Request message for updating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{source.name=organizations/*/sources/*}', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_update_source(request, metadata) + pb_request = securitycenter_service.UpdateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_source(resp) + return resp + + @property + def batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + securitycenter_service.BatchCreateResourceValueConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreateResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + 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._BulkMuteFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + 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._DeleteBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + 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._DeleteMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + 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._DeleteNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + 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._DeleteResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + bigquery_export.BigQueryExport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + mute_config.MuteConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + resource_value_config.ResourceValueConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + simulation.Simulation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSimulation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + valued_resource.ValuedResource]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetValuedResource(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + securitycenter_service.ListAttackPathsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAttackPaths(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + securitycenter_service.ListBigQueryExportsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBigQueryExports(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.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_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + securitycenter_service.ListMuteConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMuteConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListNotificationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + securitycenter_service.ListResourceValueConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + securitycenter_service.ListValuedResourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListValuedResources(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + 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._SetMute(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + gcs_external_system.ExternalSystem]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateExternalSystem(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + gcs_resource_value_config.ResourceValueConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{name=organizations/*/operations/*}:cancel', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In 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(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In 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(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), 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(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/operations}', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SecurityCenterRestTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.py new file mode 100644 index 000000000000..bb1db5459f13 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.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. +# +from .access import ( + Access, + Geolocation, + ServiceAccountDelegationInfo, +) +from .application import ( + Application, +) +from .attack_exposure import ( + AttackExposure, +) +from .attack_path import ( + AttackPath, +) +from .backup_disaster_recovery import ( + BackupDisasterRecovery, +) +from .bigquery_export import ( + BigQueryExport, +) +from .cloud_armor import ( + AdaptiveProtection, + Attack, + CloudArmor, + Requests, + SecurityPolicy, +) +from .cloud_dlp_data_profile import ( + CloudDlpDataProfile, +) +from .cloud_dlp_inspection import ( + CloudDlpInspection, +) +from .compliance import ( + Compliance, +) +from .connection import ( + Connection, +) +from .contact_details import ( + Contact, + ContactDetails, +) +from .container import ( + Container, +) +from .database import ( + Database, +) +from .exfiltration import ( + ExfilResource, + Exfiltration, +) +from .external_system import ( + ExternalSystem, +) +from .file import ( + File, +) +from .finding import ( + Finding, +) +from .folder import ( + Folder, +) +from .group_membership import ( + GroupMembership, +) +from .iam_binding import ( + IamBinding, +) +from .indicator import ( + Indicator, +) +from .kernel_rootkit import ( + KernelRootkit, +) +from .kubernetes import ( + Kubernetes, +) +from .label import ( + Label, +) +from .load_balancer import ( + LoadBalancer, +) +from .log_entry import ( + CloudLoggingEntry, + LogEntry, +) +from .mitre_attack import ( + MitreAttack, +) +from .mute_config import ( + MuteConfig, +) +from .notebook import ( + Notebook, +) +from .notification_config import ( + NotificationConfig, +) +from .notification_message import ( + NotificationMessage, +) +from .org_policy import ( + OrgPolicy, +) +from .process import ( + EnvironmentVariable, + Process, +) +from .resource import ( + AwsMetadata, + AzureMetadata, + GcpMetadata, + Resource, + ResourcePath, + CloudProvider, +) +from .resource_value_config import ( + ResourceValueConfig, + ResourceValue, +) +from .security_marks import ( + SecurityMarks, +) +from .security_posture import ( + SecurityPosture, +) +from .securitycenter_service import ( + BatchCreateResourceValueConfigsRequest, + BatchCreateResourceValueConfigsResponse, + BulkMuteFindingsRequest, + BulkMuteFindingsResponse, + CreateBigQueryExportRequest, + CreateFindingRequest, + CreateMuteConfigRequest, + CreateNotificationConfigRequest, + CreateResourceValueConfigRequest, + CreateSourceRequest, + DeleteBigQueryExportRequest, + DeleteMuteConfigRequest, + DeleteNotificationConfigRequest, + DeleteResourceValueConfigRequest, + GetBigQueryExportRequest, + GetMuteConfigRequest, + GetNotificationConfigRequest, + GetResourceValueConfigRequest, + GetSimulationRequest, + GetSourceRequest, + GetValuedResourceRequest, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListAttackPathsRequest, + ListAttackPathsResponse, + ListBigQueryExportsRequest, + ListBigQueryExportsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListMuteConfigsRequest, + ListMuteConfigsResponse, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListResourceValueConfigsRequest, + ListResourceValueConfigsResponse, + ListSourcesRequest, + ListSourcesResponse, + ListValuedResourcesRequest, + ListValuedResourcesResponse, + SetFindingStateRequest, + SetMuteRequest, + UpdateBigQueryExportRequest, + UpdateExternalSystemRequest, + UpdateFindingRequest, + UpdateMuteConfigRequest, + UpdateNotificationConfigRequest, + UpdateResourceValueConfigRequest, + UpdateSecurityMarksRequest, + UpdateSourceRequest, +) +from .simulation import ( + Simulation, +) +from .source import ( + Source, +) +from .toxic_combination import ( + ToxicCombination, +) +from .valued_resource import ( + ResourceValueConfigMetadata, + ValuedResource, +) +from .vulnerability import ( + Cve, + Cvssv3, + Package, + Reference, + SecurityBulletin, + Vulnerability, +) + +__all__ = ( + 'Access', + 'Geolocation', + 'ServiceAccountDelegationInfo', + 'Application', + 'AttackExposure', + 'AttackPath', + 'BackupDisasterRecovery', + 'BigQueryExport', + 'AdaptiveProtection', + 'Attack', + 'CloudArmor', + 'Requests', + 'SecurityPolicy', + 'CloudDlpDataProfile', + 'CloudDlpInspection', + 'Compliance', + 'Connection', + 'Contact', + 'ContactDetails', + 'Container', + 'Database', + 'ExfilResource', + 'Exfiltration', + 'ExternalSystem', + 'File', + 'Finding', + 'Folder', + 'GroupMembership', + 'IamBinding', + 'Indicator', + 'KernelRootkit', + 'Kubernetes', + 'Label', + 'LoadBalancer', + 'CloudLoggingEntry', + 'LogEntry', + 'MitreAttack', + 'MuteConfig', + 'Notebook', + 'NotificationConfig', + 'NotificationMessage', + 'OrgPolicy', + 'EnvironmentVariable', + 'Process', + 'AwsMetadata', + 'AzureMetadata', + 'GcpMetadata', + 'Resource', + 'ResourcePath', + 'CloudProvider', + 'ResourceValueConfig', + 'ResourceValue', + 'SecurityMarks', + 'SecurityPosture', + 'BatchCreateResourceValueConfigsRequest', + 'BatchCreateResourceValueConfigsResponse', + 'BulkMuteFindingsRequest', + 'BulkMuteFindingsResponse', + 'CreateBigQueryExportRequest', + 'CreateFindingRequest', + 'CreateMuteConfigRequest', + 'CreateNotificationConfigRequest', + 'CreateResourceValueConfigRequest', + 'CreateSourceRequest', + 'DeleteBigQueryExportRequest', + 'DeleteMuteConfigRequest', + 'DeleteNotificationConfigRequest', + 'DeleteResourceValueConfigRequest', + 'GetBigQueryExportRequest', + 'GetMuteConfigRequest', + 'GetNotificationConfigRequest', + 'GetResourceValueConfigRequest', + 'GetSimulationRequest', + 'GetSourceRequest', + 'GetValuedResourceRequest', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAttackPathsRequest', + 'ListAttackPathsResponse', + 'ListBigQueryExportsRequest', + 'ListBigQueryExportsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListMuteConfigsRequest', + 'ListMuteConfigsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListResourceValueConfigsRequest', + 'ListResourceValueConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListValuedResourcesRequest', + 'ListValuedResourcesResponse', + 'SetFindingStateRequest', + 'SetMuteRequest', + 'UpdateBigQueryExportRequest', + 'UpdateExternalSystemRequest', + 'UpdateFindingRequest', + 'UpdateMuteConfigRequest', + 'UpdateNotificationConfigRequest', + 'UpdateResourceValueConfigRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Simulation', + 'Source', + 'ToxicCombination', + 'ResourceValueConfigMetadata', + 'ValuedResource', + 'Cve', + 'Cvssv3', + 'Package', + 'Reference', + 'SecurityBulletin', + 'Vulnerability', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py new file mode 100644 index 000000000000..e617c4170012 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v2', + manifest={ + 'Access', + 'ServiceAccountDelegationInfo', + 'Geolocation', + }, +) + + +class Access(proto.Message): + r"""Represents an access event. + + Attributes: + principal_email (str): + Associated email, such as "foo@google.com". + + The email address of the authenticated user or a service + account acting on behalf of a third party principal making + the request. For third party identity callers, the + ``principal_subject`` field is populated instead of this + field. For privacy reasons, the principal email address is + sometimes redacted. For more information, see `Caller + identities in audit + logs `__. + caller_ip (str): + Caller's IP address, such as "1.1.1.1". + caller_ip_geo (google.cloud.securitycenter_v2.types.Geolocation): + The caller IP's geolocation, which identifies + where the call came from. + user_agent_family (str): + Type of user agent associated with the + finding. For example, an operating system shell + or an embedded or standalone application. + user_agent (str): + The caller's user agent string associated + with the finding. + service_name (str): + This is the API service that the service + account made a call to, e.g. + "iam.googleapis.com". + method_name (str): + The method that the service account called, + e.g. "SetIamPolicy". + principal_subject (str): + A string that represents the principal_subject that is + associated with the identity. Unlike ``principal_email``, + ``principal_subject`` supports principals that aren't + associated with email addresses, such as third party + principals. For most identities, the format is + ``principal://iam.googleapis.com/{identity pool name}/subject/{subject}``. + Some GKE identities, such as GKE_WORKLOAD, FREEFORM, and + GKE_HUB_WORKLOAD, still use the legacy format + ``serviceAccount:{identity pool name}[{subject}]``. + service_account_key_name (str): + The name of the service account key that was used to create + or exchange credentials when authenticating the service + account that made the request. This is a scheme-less URI + full resource name. For example: + + "//iam.googleapis.com/projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}". + service_account_delegation_info (MutableSequence[google.cloud.securitycenter_v2.types.ServiceAccountDelegationInfo]): + The identity delegation history of an authenticated service + account that made the request. The + ``serviceAccountDelegationInfo[]`` object contains + information about the real authorities that try to access + Google Cloud resources by delegating on a service account. + When multiple authorities are present, they are guaranteed + to be sorted based on the original ordering of the identity + delegation events. + user_name (str): + A string that represents a username. The + username provided depends on the type of the + finding and is likely not an IAM principal. For + example, this can be a system username if the + finding is related to a virtual machine, or it + can be an application login username. + """ + + principal_email: str = proto.Field( + proto.STRING, + number=1, + ) + caller_ip: str = proto.Field( + proto.STRING, + number=2, + ) + caller_ip_geo: 'Geolocation' = proto.Field( + proto.MESSAGE, + number=3, + message='Geolocation', + ) + user_agent_family: str = proto.Field( + proto.STRING, + number=4, + ) + user_agent: str = proto.Field( + proto.STRING, + number=5, + ) + service_name: str = proto.Field( + proto.STRING, + number=6, + ) + method_name: str = proto.Field( + proto.STRING, + number=7, + ) + principal_subject: str = proto.Field( + proto.STRING, + number=8, + ) + service_account_key_name: str = proto.Field( + proto.STRING, + number=9, + ) + service_account_delegation_info: MutableSequence['ServiceAccountDelegationInfo'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='ServiceAccountDelegationInfo', + ) + user_name: str = proto.Field( + proto.STRING, + number=11, + ) + + +class ServiceAccountDelegationInfo(proto.Message): + r"""Identity delegation history of an authenticated service + account. + + Attributes: + principal_email (str): + The email address of a Google account. + principal_subject (str): + A string representing the principal_subject associated with + the identity. As compared to ``principal_email``, supports + principals that aren't associated with email addresses, such + as third party principals. For most identities, the format + will be + ``principal://iam.googleapis.com/{identity pool name}/subjects/{subject}`` + except for some GKE identities (GKE_WORKLOAD, FREEFORM, + GKE_HUB_WORKLOAD) that are still in the legacy format + ``serviceAccount:{identity pool name}[{subject}]`` + """ + + principal_email: str = proto.Field( + proto.STRING, + number=1, + ) + principal_subject: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Geolocation(proto.Message): + r"""Represents a geographical location for a given access. + + Attributes: + region_code (str): + A CLDR. + """ + + region_code: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.py new file mode 100644 index 000000000000..b77f5993987b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Application', + }, +) + + +class Application(proto.Message): + r"""Represents an application associated with a finding. + + Attributes: + base_uri (str): + The base URI that identifies the network location of the + application in which the vulnerability was detected. For + example, ``http://example.com``. + full_uri (str): + The full URI with payload that could be used to reproduce + the vulnerability. For example, + ``http://example.com?p=aMmYgI6H``. + """ + + base_uri: str = proto.Field( + proto.STRING, + number=1, + ) + full_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.py new file mode 100644 index 000000000000..600d1a66d91e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'AttackExposure', + }, +) + + +class AttackExposure(proto.Message): + r"""An attack exposure contains the results of an attack path + simulation run. + + Attributes: + score (float): + A number between 0 (inclusive) and infinity + that represents how important this finding is to + remediate. The higher the score, the more + important it is to remediate. + latest_calculation_time (google.protobuf.timestamp_pb2.Timestamp): + The most recent time the attack exposure was + updated on this finding. + attack_exposure_result (str): + The resource name of the attack path simulation result that + contains the details regarding this attack exposure score. + Example: + ``organizations/123/simulations/456/attackExposureResults/789`` + state (google.cloud.securitycenter_v2.types.AttackExposure.State): + Output only. What state this AttackExposure + is in. This captures whether or not an attack + exposure has been calculated or not. + exposed_high_value_resources_count (int): + The number of high value resources that are + exposed as a result of this finding. + exposed_medium_value_resources_count (int): + The number of medium value resources that are + exposed as a result of this finding. + exposed_low_value_resources_count (int): + The number of high value resources that are + exposed as a result of this finding. + """ + class State(proto.Enum): + r"""This enum defines the various states an AttackExposure can be + in. + + Values: + STATE_UNSPECIFIED (0): + The state is not specified. + CALCULATED (1): + The attack exposure has been calculated. + NOT_CALCULATED (2): + The attack exposure has not been calculated. + """ + STATE_UNSPECIFIED = 0 + CALCULATED = 1 + NOT_CALCULATED = 2 + + score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + latest_calculation_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + attack_exposure_result: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + exposed_high_value_resources_count: int = proto.Field( + proto.INT32, + number=5, + ) + exposed_medium_value_resources_count: int = proto.Field( + proto.INT32, + number=6, + ) + exposed_low_value_resources_count: int = proto.Field( + proto.INT32, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py new file mode 100644 index 000000000000..433afe1a5eee --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v2', + manifest={ + 'AttackPath', + }, +) + + +class AttackPath(proto.Message): + r"""A path that an attacker could take to reach an exposed + resource. + + Attributes: + name (str): + The attack path name, for example, + ``organizations/12/simulations/34/valuedResources/56/attackPaths/78`` + path_nodes (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode]): + A list of nodes that exist in this attack + path. + edges (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathEdge]): + A list of the edges between nodes in this + attack path. + """ + + class AttackPathNode(proto.Message): + r"""Represents one point that an attacker passes through in this + attack path. + + Attributes: + resource (str): + The name of the resource at this point in the attack path. + The format of the name follows the Cloud Asset Inventory + `resource name + format `__ + resource_type (str): + The `supported resource + type `__ + display_name (str): + Human-readable name of this resource. + associated_findings (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.PathNodeAssociatedFinding]): + The findings associated with this node in the + attack path. + uuid (str): + Unique id of the attack path node. + attack_steps (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.AttackStepNode]): + A list of attack step nodes that exist in + this attack path node. + """ + class NodeType(proto.Enum): + r"""The type of the incoming attack step node. + + Values: + NODE_TYPE_UNSPECIFIED (0): + Type not specified + NODE_TYPE_AND (1): + Incoming edge joined with AND + NODE_TYPE_OR (2): + Incoming edge joined with OR + NODE_TYPE_DEFENSE (3): + Incoming edge is defense + NODE_TYPE_ATTACKER (4): + Incoming edge is attacker + """ + NODE_TYPE_UNSPECIFIED = 0 + NODE_TYPE_AND = 1 + NODE_TYPE_OR = 2 + NODE_TYPE_DEFENSE = 3 + NODE_TYPE_ATTACKER = 4 + + class PathNodeAssociatedFinding(proto.Message): + r"""A finding that is associated with this node in the attack + path. + + Attributes: + canonical_finding (str): + Canonical name of the associated findings. Example: + ``organizations/123/sources/456/findings/789`` + finding_category (str): + The additional taxonomy group within findings + from a given source. + name (str): + Full resource name of the finding. + """ + + canonical_finding: str = proto.Field( + proto.STRING, + number=1, + ) + finding_category: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class AttackStepNode(proto.Message): + r"""Detailed steps the attack can take between path nodes. + + Attributes: + uuid (str): + Unique ID for one Node + type_ (google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.NodeType): + Attack step type. Can be either AND, OR or + DEFENSE + display_name (str): + User friendly name of the attack step + labels (MutableMapping[str, str]): + Attack step labels for metadata + description (str): + Attack step description + """ + + uuid: str = proto.Field( + proto.STRING, + number=1, + ) + type_: 'AttackPath.AttackPathNode.NodeType' = proto.Field( + proto.ENUM, + number=2, + enum='AttackPath.AttackPathNode.NodeType', + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + + resource: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + associated_findings: MutableSequence['AttackPath.AttackPathNode.PathNodeAssociatedFinding'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AttackPath.AttackPathNode.PathNodeAssociatedFinding', + ) + uuid: str = proto.Field( + proto.STRING, + number=5, + ) + attack_steps: MutableSequence['AttackPath.AttackPathNode.AttackStepNode'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='AttackPath.AttackPathNode.AttackStepNode', + ) + + class AttackPathEdge(proto.Message): + r"""Represents a connection between a source node and a + destination node in this attack path. + + Attributes: + source (str): + The attack node uuid of the source node. + destination (str): + The attack node uuid of the destination node. + """ + + source: str = proto.Field( + proto.STRING, + number=1, + ) + destination: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + path_nodes: MutableSequence[AttackPathNode] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=AttackPathNode, + ) + edges: MutableSequence[AttackPathEdge] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=AttackPathEdge, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py new file mode 100644 index 000000000000..0c1d44505179 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v2', + manifest={ + 'BackupDisasterRecovery', + }, +) + + +class BackupDisasterRecovery(proto.Message): + r"""Information related to Google Cloud Backup and DR Service + findings. + + Attributes: + backup_template (str): + The name of a Backup and DR template which comprises one or + more backup policies. See the `Backup and DR + documentation `__ + for more information. For example, ``snap-ov``. + policies (MutableSequence[str]): + The names of Backup and DR policies that are associated with + a template and that define when to run a backup, how + frequently to run a backup, and how long to retain the + backup image. For example, ``onvaults``. + host (str): + The name of a Backup and DR host, which is managed by the + backup and recovery appliance and known to the management + console. The host can be of type Generic (for example, + Compute Engine, SQL Server, Oracle DB, SMB file system, + etc.), vCenter, or an ESX server. See the `Backup and DR + documentation on + hosts `__ + for more information. For example, ``centos7-01``. + applications (MutableSequence[str]): + The names of Backup and DR applications. An application is a + VM, database, or file system on a managed host monitored by + a backup and recovery appliance. For example, + ``centos7-01-vol00``, ``centos7-01-vol01``, + ``centos7-01-vol02``. + storage_pool (str): + The name of the Backup and DR storage pool that the backup + and recovery appliance is storing data in. The storage pool + could be of type Cloud, Primary, Snapshot, or OnVault. See + the `Backup and DR documentation on storage + pools `__. + For example, ``DiskPoolOne``. + policy_options (MutableSequence[str]): + The names of Backup and DR advanced policy options of a + policy applying to an application. See the `Backup and DR + documentation on policy + options `__. + For example, ``skipofflineappsincongrp, nounmap``. + profile (str): + The name of the Backup and DR resource profile that + specifies the storage media for backups of application and + VM data. See the `Backup and DR documentation on + profiles `__. + For example, ``GCP``. + appliance (str): + The name of the Backup and DR appliance that captures, + moves, and manages the lifecycle of backup data. For + example, ``backup-server-57137``. + backup_type (str): + The backup type of the Backup and DR image. For example, + ``Snapshot``, ``Remote Snapshot``, ``OnVault``. + backup_create_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp at which the Backup and DR + backup was created. + """ + + backup_template: str = proto.Field( + proto.STRING, + number=1, + ) + policies: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + host: str = proto.Field( + proto.STRING, + number=3, + ) + applications: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + storage_pool: str = proto.Field( + proto.STRING, + number=5, + ) + policy_options: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + profile: str = proto.Field( + proto.STRING, + number=7, + ) + appliance: str = proto.Field( + proto.STRING, + number=8, + ) + backup_type: str = proto.Field( + proto.STRING, + number=9, + ) + backup_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py new file mode 100644 index 000000000000..01d3971a5bd5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v2', + manifest={ + 'BigQueryExport', + }, +) + + +class BigQueryExport(proto.Message): + r"""Configures how to deliver Findings to BigQuery Instance. + + Attributes: + name (str): + Identifier. The relative resource name of this export. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name. + The following list shows some examples: + + - + + ``organizations/{organization_id}/locations/{location_id}/bigQueryExports/{export_id}`` + + - ``folders/{folder_id}/locations/{location_id}/bigQueryExports/{export_id}`` + - + + ``projects/{project_id}/locations/{location_id}/bigQueryExports/{export_id}`` + + This field is provided in responses, and is ignored when + provided in create requests. + description (str): + The description of the export (max of 1024 + characters). + filter (str): + Expression that defines the filter to apply across + create/update events of findings. The expression is a list + of zero or more restrictions combined via logical operators + ``AND`` and ``OR``. Parentheses are supported, and ``OR`` + has higher precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + dataset (str): + The dataset to write findings' updates to. Its format is + "projects/[project_id]/datasets/[bigquery_dataset_id]". + BigQuery dataset unique ID must contain only letters (a-z, + A-Z), numbers (0-9), or underscores (_). + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the BigQuery + export was created. This field is set by the + server and will be ignored if provided on export + on creation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time at which + the BigQuery export was updated. This field is + set by the server and will be ignored if + provided on export creation or update. + most_recent_editor (str): + Output only. Email address of the user who + last edited the BigQuery export. This field is + set by the server and will be ignored if + provided on export creation or update. + principal (str): + Output only. The service account that needs + permission to create table and upload data to + the BigQuery dataset. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + dataset: 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, + ) + most_recent_editor: str = proto.Field( + proto.STRING, + number=7, + ) + principal: str = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.py new file mode 100644 index 000000000000..2bf900e3af1c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.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.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'CloudArmor', + 'SecurityPolicy', + 'Requests', + 'AdaptiveProtection', + 'Attack', + }, +) + + +class CloudArmor(proto.Message): + r"""Fields related to Google Cloud Armor findings. + + Attributes: + security_policy (google.cloud.securitycenter_v2.types.SecurityPolicy): + Information about the `Google Cloud Armor security + policy `__ + relevant to the finding. + requests (google.cloud.securitycenter_v2.types.Requests): + Information about incoming requests evaluated by `Google + Cloud Armor security + policies `__. + adaptive_protection (google.cloud.securitycenter_v2.types.AdaptiveProtection): + Information about potential Layer 7 DDoS attacks identified + by `Google Cloud Armor Adaptive + Protection `__. + attack (google.cloud.securitycenter_v2.types.Attack): + Information about DDoS attack volume and + classification. + threat_vector (str): + Distinguish between volumetric & protocol DDoS attack and + application layer attacks. For example, "L3_4" for Layer 3 + and Layer 4 DDoS attacks, or "L_7" for Layer 7 DDoS attacks. + duration (google.protobuf.duration_pb2.Duration): + Duration of attack from the start until the + current moment (updated every 5 minutes). + """ + + security_policy: 'SecurityPolicy' = proto.Field( + proto.MESSAGE, + number=1, + message='SecurityPolicy', + ) + requests: 'Requests' = proto.Field( + proto.MESSAGE, + number=2, + message='Requests', + ) + adaptive_protection: 'AdaptiveProtection' = proto.Field( + proto.MESSAGE, + number=3, + message='AdaptiveProtection', + ) + attack: 'Attack' = proto.Field( + proto.MESSAGE, + number=4, + message='Attack', + ) + threat_vector: str = proto.Field( + proto.STRING, + number=5, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + + +class SecurityPolicy(proto.Message): + r"""Information about the `Google Cloud Armor security + policy `__ + relevant to the finding. + + Attributes: + name (str): + The name of the Google Cloud Armor security + policy, for example, "my-security-policy". + type_ (str): + The type of Google Cloud Armor security + policy for example, 'backend security policy', + 'edge security policy', 'network edge security + policy', or 'always-on DDoS protection'. + preview (bool): + Whether or not the associated rule or policy + is in preview mode. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + preview: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class Requests(proto.Message): + r"""Information about the requests relevant to the finding. + + Attributes: + ratio (float): + For 'Increasing deny ratio', the ratio is the + denied traffic divided by the allowed traffic. + For 'Allowed traffic spike', the ratio is the + allowed traffic in the short term divided by + allowed traffic in the long term. + short_term_allowed (int): + Allowed RPS (requests per second) in the + short term. + long_term_allowed (int): + Allowed RPS (requests per second) over the + long term. + long_term_denied (int): + Denied RPS (requests per second) over the + long term. + """ + + ratio: float = proto.Field( + proto.DOUBLE, + number=1, + ) + short_term_allowed: int = proto.Field( + proto.INT32, + number=2, + ) + long_term_allowed: int = proto.Field( + proto.INT32, + number=3, + ) + long_term_denied: int = proto.Field( + proto.INT32, + number=4, + ) + + +class AdaptiveProtection(proto.Message): + r"""Information about `Google Cloud Armor Adaptive + Protection `__. + + Attributes: + confidence (float): + A score of 0 means that there is low confidence that the + detected event is an actual attack. A score of 1 means that + there is high confidence that the detected event is an + attack. See the `Adaptive Protection + documentation `__ + for further explanation. + """ + + confidence: float = proto.Field( + proto.DOUBLE, + number=1, + ) + + +class Attack(proto.Message): + r"""Information about DDoS attack volume and classification. + + Attributes: + volume_pps (int): + Total PPS (packets per second) volume of + attack. + volume_bps (int): + Total BPS (bytes per second) volume of + attack. + classification (str): + Type of attack, for example, 'SYN-flood', + 'NTP-udp', or 'CHARGEN-udp'. + """ + + volume_pps: int = proto.Field( + proto.INT32, + number=1, + ) + volume_bps: int = proto.Field( + proto.INT32, + number=2, + ) + classification: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py new file mode 100644 index 000000000000..1b41c5f6d040 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.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.cloud.securitycenter.v2', + manifest={ + 'CloudDlpDataProfile', + }, +) + + +class CloudDlpDataProfile(proto.Message): + r"""The `data + profile `__ + associated with the finding. + + Attributes: + data_profile (str): + Name of the data profile, for example, + ``projects/123/locations/europe/tableProfiles/8383929``. + parent_type (google.cloud.securitycenter_v2.types.CloudDlpDataProfile.ParentType): + The resource hierarchy level at which the + data profile was generated. + """ + class ParentType(proto.Enum): + r"""Parents for configurations that produce data profile + findings. + + Values: + PARENT_TYPE_UNSPECIFIED (0): + Unspecified parent type. + ORGANIZATION (1): + Organization-level configurations. + PROJECT (2): + Project-level configurations. + """ + PARENT_TYPE_UNSPECIFIED = 0 + ORGANIZATION = 1 + PROJECT = 2 + + data_profile: str = proto.Field( + proto.STRING, + number=1, + ) + parent_type: ParentType = proto.Field( + proto.ENUM, + number=2, + enum=ParentType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py new file mode 100644 index 000000000000..c98af340d22a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'CloudDlpInspection', + }, +) + + +class CloudDlpInspection(proto.Message): + r"""Details about the Cloud Data Loss Prevention (Cloud DLP) `inspection + job `__ + that produced the finding. + + Attributes: + inspect_job (str): + Name of the inspection job, for example, + ``projects/123/locations/europe/dlpJobs/i-8383929``. + info_type (str): + The type of information (or + `infoType `__) + found, for example, ``EMAIL_ADDRESS`` or ``STREET_ADDRESS``. + info_type_count (int): + The number of times Cloud DLP found this + infoType within this job and resource. + full_scan (bool): + Whether Cloud DLP scanned the complete + resource or a sampled subset. + """ + + inspect_job: str = proto.Field( + proto.STRING, + number=1, + ) + info_type: str = proto.Field( + proto.STRING, + number=2, + ) + info_type_count: int = proto.Field( + proto.INT64, + number=3, + ) + full_scan: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.py new file mode 100644 index 000000000000..64f5c99ef06b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Compliance', + }, +) + + +class Compliance(proto.Message): + r"""Contains compliance information about a security standard + indicating unmet recommendations. + + Attributes: + standard (str): + Industry-wide compliance standards or + benchmarks, such as CIS, PCI, and OWASP. + version (str): + Version of the standard or benchmark, for + example, 1.1 + ids (MutableSequence[str]): + Policies within the standard or benchmark, + for example, A.12.4.1 + """ + + standard: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.py new file mode 100644 index 000000000000..1e0ff52947d5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.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.cloud.securitycenter.v2', + manifest={ + 'Connection', + }, +) + + +class Connection(proto.Message): + r"""Contains information about the IP connection associated with + the finding. + + Attributes: + destination_ip (str): + Destination IP address. Not present for + sockets that are listening and not connected. + destination_port (int): + Destination port. Not present for sockets + that are listening and not connected. + source_ip (str): + Source IP address. + source_port (int): + Source port. + protocol (google.cloud.securitycenter_v2.types.Connection.Protocol): + IANA Internet Protocol Number such as TCP(6) + and UDP(17). + """ + class Protocol(proto.Enum): + r"""IANA Internet Protocol Number such as TCP(6) and UDP(17). + + Values: + PROTOCOL_UNSPECIFIED (0): + Unspecified protocol (not HOPOPT). + ICMP (1): + Internet Control Message Protocol. + TCP (6): + Transmission Control Protocol. + UDP (17): + User Datagram Protocol. + GRE (47): + Generic Routing Encapsulation. + ESP (50): + Encap Security Payload. + """ + PROTOCOL_UNSPECIFIED = 0 + ICMP = 1 + TCP = 6 + UDP = 17 + GRE = 47 + ESP = 50 + + destination_ip: str = proto.Field( + proto.STRING, + number=1, + ) + destination_port: int = proto.Field( + proto.INT32, + number=2, + ) + source_ip: str = proto.Field( + proto.STRING, + number=3, + ) + source_port: int = proto.Field( + proto.INT32, + number=4, + ) + protocol: Protocol = proto.Field( + proto.ENUM, + number=5, + enum=Protocol, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.py new file mode 100644 index 000000000000..f7e49e2e4392 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'ContactDetails', + 'Contact', + }, +) + + +class ContactDetails(proto.Message): + r"""Details about specific contacts + + Attributes: + contacts (MutableSequence[google.cloud.securitycenter_v2.types.Contact]): + A list of contacts + """ + + contacts: MutableSequence['Contact'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Contact', + ) + + +class Contact(proto.Message): + r"""The email address of a contact. + + Attributes: + email (str): + An email address. For example, "``person123@company.com``". + """ + + email: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.py new file mode 100644 index 000000000000..de1e6fd55be0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v2.types import label +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Container', + }, +) + + +class Container(proto.Message): + r"""Container associated with the finding. + + Attributes: + name (str): + Name of the container. + uri (str): + Container image URI provided when configuring + a pod or container. This string can identify a + container image version using mutable tags. + image_id (str): + Optional container image ID, if provided by + the container runtime. Uniquely identifies the + container image launched using a container image + digest. + labels (MutableSequence[google.cloud.securitycenter_v2.types.Label]): + Container labels, as provided by the + container runtime. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time that the container was created. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + image_id: str = proto.Field( + proto.STRING, + number=3, + ) + labels: MutableSequence[label.Label] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=label.Label, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.py new file mode 100644 index 000000000000..59f3eefcf9e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Database', + }, +) + + +class Database(proto.Message): + r"""Represents database access information, such as queries. A database + may be a sub-resource of an instance (as in the case of Cloud SQL + instances or Cloud Spanner instances), or the database instance + itself. Some database resources might not have the `full resource + name `__ populated + because these resource types, such as Cloud SQL databases, are not + yet supported by Cloud Asset Inventory. In these cases only the + display name is provided. + + Attributes: + name (str): + Some database resources may not have the `full resource + name `__ + populated because these resource types are not yet supported + by Cloud Asset Inventory (e.g. Cloud SQL databases). In + these cases only the display name will be provided. The + `full resource + name `__ of + the database that the user connected to, if it is supported + by Cloud Asset Inventory. + display_name (str): + The human-readable name of the database that + the user connected to. + user_name (str): + The username used to connect to the database. + The username might not be an IAM principal and + does not have a set format. + query (str): + The SQL statement that is associated with the + database access. + grantees (MutableSequence[str]): + The target usernames, roles, or groups of an + SQL privilege grant, which is not an IAM policy + change. + version (str): + The version of the database, for example, POSTGRES_14. See + `the complete + list `__. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + user_name: str = proto.Field( + proto.STRING, + number=3, + ) + query: str = proto.Field( + proto.STRING, + number=4, + ) + grantees: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + version: str = proto.Field( + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.py new file mode 100644 index 000000000000..8a3c83a21200 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Exfiltration', + 'ExfilResource', + }, +) + + +class Exfiltration(proto.Message): + r"""Exfiltration represents a data exfiltration attempt from one or more + sources to one or more targets. The ``sources`` attribute lists the + sources of the exfiltrated data. The ``targets`` attribute lists the + destinations the data was copied to. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v2.types.ExfilResource]): + If there are multiple sources, then the data + is considered "joined" between them. For + instance, BigQuery can join multiple tables, and + each table would be considered a source. + targets (MutableSequence[google.cloud.securitycenter_v2.types.ExfilResource]): + If there are multiple targets, each target + would get a complete copy of the "joined" source + data. + total_exfiltrated_bytes (int): + Total exfiltrated bytes processed for the + entire job. + """ + + sources: MutableSequence['ExfilResource'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ExfilResource', + ) + targets: MutableSequence['ExfilResource'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ExfilResource', + ) + total_exfiltrated_bytes: int = proto.Field( + proto.INT64, + number=3, + ) + + +class ExfilResource(proto.Message): + r"""Resource where data was exfiltrated from or exfiltrated to. + + Attributes: + name (str): + The resource's `full resource + name `__. + components (MutableSequence[str]): + Subcomponents of the asset that was + exfiltrated, like URIs used during exfiltration, + table names, databases, and filenames. For + example, multiple tables might have been + exfiltrated from the same Cloud SQL instance, or + multiple files might have been exfiltrated from + the same Cloud Storage bucket. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + components: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py new file mode 100644 index 000000000000..780eb3c24edf --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py @@ -0,0 +1,192 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v2', + manifest={ + 'ExternalSystem', + }, +) + + +class ExternalSystem(proto.Message): + r"""Representation of third party SIEM/SOAR fields within SCC. + + Attributes: + name (str): + Full resource name of the external system. The following + list shows some examples: + + - ``organizations/1234/sources/5678/findings/123456/externalSystems/jira`` + - + + ``organizations/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` + + - ``folders/1234/sources/5678/findings/123456/externalSystems/jira`` + - + + ``folders/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` + + - ``projects/1234/sources/5678/findings/123456/externalSystems/jira`` + - + + ``projects/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` + assignees (MutableSequence[str]): + References primary/secondary etc assignees in + the external system. + external_uid (str): + The identifier that's used to track the + finding's corresponding case in the external + system. + status (str): + The most recent status of the finding's + corresponding case, as reported by the external + system. + external_system_update_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was last updated, as + reported by the external system. + case_uri (str): + The link to the finding's corresponding case + in the external system. + case_priority (str): + The priority of the finding's corresponding + case in the external system. + case_sla (google.protobuf.timestamp_pb2.Timestamp): + The SLA of the finding's corresponding case + in the external system. + case_create_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was created, as + reported by the external system. + case_close_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was closed, as + reported by the external system. + ticket_info (google.cloud.securitycenter_v2.types.ExternalSystem.TicketInfo): + Information about the ticket, if any, that is + being used to track the resolution of the issue + that is identified by this finding. + """ + + class TicketInfo(proto.Message): + r"""Information about the ticket, if any, that is being used to + track the resolution of the issue that is identified by this + finding. + + Attributes: + id (str): + The identifier of the ticket in the ticket + system. + assignee (str): + The assignee of the ticket in the ticket + system. + description (str): + The description of the ticket in the ticket + system. + uri (str): + The link to the ticket in the ticket system. + status (str): + The latest status of the ticket, as reported + by the ticket system. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the ticket was last updated, as + reported by the ticket system. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + assignee: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + uri: str = proto.Field( + proto.STRING, + number=4, + ) + status: str = proto.Field( + proto.STRING, + number=5, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + assignees: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + external_uid: str = proto.Field( + proto.STRING, + number=3, + ) + status: str = proto.Field( + proto.STRING, + number=4, + ) + external_system_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + case_uri: str = proto.Field( + proto.STRING, + number=6, + ) + case_priority: str = proto.Field( + proto.STRING, + number=7, + ) + case_sla: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + case_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + case_close_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + ticket_info: TicketInfo = proto.Field( + proto.MESSAGE, + number=8, + message=TicketInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.py new file mode 100644 index 000000000000..5bb6f2f70ef0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'File', + }, +) + + +class File(proto.Message): + r"""File information about the related binary/library used by an + executable, or the script used by a script interpreter + + Attributes: + path (str): + Absolute path of the file as a JSON encoded + string. + size (int): + Size of the file in bytes. + sha256 (str): + SHA256 hash of the first hashed_size bytes of the file + encoded as a hex string. If hashed_size == size, sha256 + represents the SHA256 hash of the entire file. + hashed_size (int): + The length in bytes of the file prefix that was hashed. If + hashed_size == size, any hashes reported represent the + entire file. + partially_hashed (bool): + True when the hash covers only a prefix of + the file. + contents (str): + Prefix of the file contents as a JSON-encoded + string. + disk_path (google.cloud.securitycenter_v2.types.File.DiskPath): + Path of the file in terms of underlying + disk/partition identifiers. + """ + + class DiskPath(proto.Message): + r"""Path of the file in terms of underlying disk/partition + identifiers. + + Attributes: + partition_uuid (str): + UUID of the partition (format + https://wiki.archlinux.org/title/persistent_block_device_naming#by-uuid) + relative_path (str): + Relative path of the file in the partition as a JSON encoded + string. Example: /home/user1/executable_file.sh + """ + + partition_uuid: str = proto.Field( + proto.STRING, + number=1, + ) + relative_path: str = proto.Field( + proto.STRING, + number=2, + ) + + path: str = proto.Field( + proto.STRING, + number=1, + ) + size: int = proto.Field( + proto.INT64, + number=2, + ) + sha256: str = proto.Field( + proto.STRING, + number=3, + ) + hashed_size: int = proto.Field( + proto.INT64, + number=4, + ) + partially_hashed: bool = proto.Field( + proto.BOOL, + number=5, + ) + contents: str = proto.Field( + proto.STRING, + number=6, + ) + disk_path: DiskPath = proto.Field( + proto.MESSAGE, + number=7, + message=DiskPath, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.py new file mode 100644 index 000000000000..4e18ac0eb8ae --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v2.types import access as gcs_access +from google.cloud.securitycenter_v2.types import application as gcs_application +from google.cloud.securitycenter_v2.types import attack_exposure as gcs_attack_exposure +from google.cloud.securitycenter_v2.types import backup_disaster_recovery as gcs_backup_disaster_recovery +from google.cloud.securitycenter_v2.types import cloud_armor as gcs_cloud_armor +from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile as gcs_cloud_dlp_data_profile +from google.cloud.securitycenter_v2.types import cloud_dlp_inspection as gcs_cloud_dlp_inspection +from google.cloud.securitycenter_v2.types import compliance +from google.cloud.securitycenter_v2.types import connection +from google.cloud.securitycenter_v2.types import contact_details +from google.cloud.securitycenter_v2.types import container +from google.cloud.securitycenter_v2.types import database as gcs_database +from google.cloud.securitycenter_v2.types import exfiltration as gcs_exfiltration +from google.cloud.securitycenter_v2.types import external_system +from google.cloud.securitycenter_v2.types import file +from google.cloud.securitycenter_v2.types import group_membership +from google.cloud.securitycenter_v2.types import iam_binding +from google.cloud.securitycenter_v2.types import indicator as gcs_indicator +from google.cloud.securitycenter_v2.types import kernel_rootkit as gcs_kernel_rootkit +from google.cloud.securitycenter_v2.types import kubernetes as gcs_kubernetes +from google.cloud.securitycenter_v2.types import load_balancer +from google.cloud.securitycenter_v2.types import log_entry +from google.cloud.securitycenter_v2.types import mitre_attack as gcs_mitre_attack +from google.cloud.securitycenter_v2.types import notebook as gcs_notebook +from google.cloud.securitycenter_v2.types import org_policy +from google.cloud.securitycenter_v2.types import process +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import security_posture as gcs_security_posture +from google.cloud.securitycenter_v2.types import toxic_combination as gcs_toxic_combination +from google.cloud.securitycenter_v2.types import vulnerability as gcs_vulnerability +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + + A finding is a record of assessment data like security, risk, + health, or privacy, that is ingested into Security Command + Center for presentation, notification, analysis, policy testing, + and enforcement. For example, a cross-site scripting (XSS) + vulnerability in an App Engine application is a finding. + + Attributes: + name (str): + The `relative resource + name `__ + of the finding. The following list shows some examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + canonical_name (str): + Output only. The canonical name of the finding. The + following list shows some examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + The prefix is the closest CRM ancestor of the resource + associated with the finding. + parent (str): + The relative resource name of the source and location the + finding belongs to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. The following + list shows some examples: + + - ``organizations/{organization_id}/sources/{source_id}`` + - ``folders/{folders_id}/sources/{source_id}`` + - ``projects/{projects_id}/sources/{source_id}`` + - + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}`` + + - ``folders/{folders_id}/sources/{source_id}/locations/{location_id}`` + - ``projects/{projects_id}/sources/{source_id}/locations/{location_id}`` + resource_name (str): + Immutable. For findings on Google Cloud resources, the full + resource name of the Google Cloud resource this finding is + for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + state (google.cloud.securitycenter_v2.types.Finding.State): + Output only. The state of the finding. + category (str): + Immutable. The additional taxonomy group within findings + from a given source. Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (google.protobuf.timestamp_pb2.Timestamp): + The time the finding was first detected. If + an existing finding is updated, then this is the + time the update occurred. For example, if the + finding represents an open firewall, this + property captures the time the detector believes + the firewall became open. The accuracy is + determined by the detector. If the finding is + later resolved, then this time reflects when the + finding was resolved. This must not be set to a + value greater than the current timestamp. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the finding + was created in Security Command Center. + severity (google.cloud.securitycenter_v2.types.Finding.Severity): + The severity of the finding. This field is + managed by the source that writes the finding. + mute (google.cloud.securitycenter_v2.types.Finding.Mute): + Indicates the mute state of a finding (either + muted, unmuted or undefined). Unlike other + attributes of a finding, a finding provider + shouldn't set the value of mute. + mute_info (google.cloud.securitycenter_v2.types.Finding.MuteInfo): + Output only. The mute information regarding + this finding. + finding_class (google.cloud.securitycenter_v2.types.Finding.FindingClass): + The class of the finding. + indicator (google.cloud.securitycenter_v2.types.Indicator): + Represents what's commonly known as an *indicator of + compromise* (IoC) in computer forensics. This is an artifact + observed on a network or in an operating system that, with + high confidence, indicates a computer intrusion. For more + information, see `Indicator of + compromise `__. + vulnerability (google.cloud.securitycenter_v2.types.Vulnerability): + Represents vulnerability-specific fields like + CVE and CVSS scores. CVE stands for Common + Vulnerabilities and Exposures + (https://cve.mitre.org/about/) + mute_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time this + finding was muted or unmuted. + external_systems (MutableMapping[str, google.cloud.securitycenter_v2.types.ExternalSystem]): + Output only. Third party SIEM/SOAR fields + within SCC, contains external system information + and external system finding fields. + mitre_attack (google.cloud.securitycenter_v2.types.MitreAttack): + MITRE ATT&CK tactics and techniques related + to this finding. See: https://attack.mitre.org + access (google.cloud.securitycenter_v2.types.Access): + Access details associated with the finding, + such as more information on the caller, which + method was accessed, and from where. + connections (MutableSequence[google.cloud.securitycenter_v2.types.Connection]): + Contains information about the IP connection + associated with the finding. + mute_initiator (str): + Records additional information about the mute operation, for + example, the `mute + configuration `__ + that muted the finding and the user who muted the finding. + processes (MutableSequence[google.cloud.securitycenter_v2.types.Process]): + Represents operating system processes + associated with the Finding. + contacts (MutableMapping[str, google.cloud.securitycenter_v2.types.ContactDetails]): + Output only. Map containing the points of contact for the + given finding. The key represents the type of contact, while + the value contains a list of all the contacts that pertain. + Please refer to: + https://cloud.google.com/resource-manager/docs/managing-notification-contacts#notification-categories + + :: + + { + "security": { + "contacts": [ + { + "email": "person1@company.com" + }, + { + "email": "person2@company.com" + } + ] + } + } + compliances (MutableSequence[google.cloud.securitycenter_v2.types.Compliance]): + Contains compliance information for security + standards associated to the finding. + parent_display_name (str): + Output only. The human readable display name + of the finding source such as "Event Threat + Detection" or "Security Health Analytics". + description (str): + Contains more details about the finding. + exfiltration (google.cloud.securitycenter_v2.types.Exfiltration): + Represents exfiltrations associated with the + finding. + iam_bindings (MutableSequence[google.cloud.securitycenter_v2.types.IamBinding]): + Represents IAM bindings associated with the + finding. + next_steps (str): + Steps to address the finding. + module_name (str): + Unique identifier of the module which + generated the finding. Example: + + folders/598186756061/securityHealthAnalyticsSettings/customModules/56799441161885 + containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): + Containers associated with the finding. This + field provides information for both Kubernetes + and non-Kubernetes containers. + kubernetes (google.cloud.securitycenter_v2.types.Kubernetes): + Kubernetes resources associated with the + finding. + database (google.cloud.securitycenter_v2.types.Database): + Database associated with the finding. + attack_exposure (google.cloud.securitycenter_v2.types.AttackExposure): + The results of an attack path simulation + relevant to this finding. + files (MutableSequence[google.cloud.securitycenter_v2.types.File]): + File associated with the finding. + cloud_dlp_inspection (google.cloud.securitycenter_v2.types.CloudDlpInspection): + Cloud Data Loss Prevention (Cloud DLP) + inspection results that are associated with the + finding. + cloud_dlp_data_profile (google.cloud.securitycenter_v2.types.CloudDlpDataProfile): + Cloud DLP data profile that is associated + with the finding. + kernel_rootkit (google.cloud.securitycenter_v2.types.KernelRootkit): + Signature of the kernel rootkit. + org_policies (MutableSequence[google.cloud.securitycenter_v2.types.OrgPolicy]): + Contains information about the org policies + associated with the finding. + application (google.cloud.securitycenter_v2.types.Application): + Represents an application associated with the + finding. + backup_disaster_recovery (google.cloud.securitycenter_v2.types.BackupDisasterRecovery): + Fields related to Backup and DR findings. + security_posture (google.cloud.securitycenter_v2.types.SecurityPosture): + The security posture associated with the + finding. + log_entries (MutableSequence[google.cloud.securitycenter_v2.types.LogEntry]): + Log entries that are relevant to the finding. + load_balancers (MutableSequence[google.cloud.securitycenter_v2.types.LoadBalancer]): + The load balancers associated with the + finding. + cloud_armor (google.cloud.securitycenter_v2.types.CloudArmor): + Fields related to Cloud Armor findings. + notebook (google.cloud.securitycenter_v2.types.Notebook): + Notebook associated with the finding. + toxic_combination (google.cloud.securitycenter_v2.types.ToxicCombination): + Contains details about a group of security + issues that, when the issues occur together, + represent a greater risk than when the issues + occur independently. A group of such issues is + referred to as a toxic combination. + This field cannot be updated. Its value is + ignored in all update requests. + group_memberships (MutableSequence[google.cloud.securitycenter_v2.types.GroupMembership]): + Contains details about groups of which this + finding is a member. A group is a collection of + findings that are related in some way. This + field cannot be updated. Its value is ignored in + all update requests. + """ + class State(proto.Enum): + r"""The state of the finding. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + ACTIVE (1): + The finding requires attention and has not + been addressed yet. + INACTIVE (2): + The finding has been fixed, triaged as a + non-issue or otherwise addressed and is no + longer active. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + class Severity(proto.Enum): + r"""The severity of the finding. + + Values: + SEVERITY_UNSPECIFIED (0): + This value is used for findings when a source + doesn't write a severity value. + CRITICAL (1): + Vulnerability: + + A critical vulnerability is easily discoverable + by an external actor, exploitable, and results + in the direct ability to execute arbitrary code, + exfiltrate data, and otherwise gain additional + access and privileges to cloud resources and + workloads. Examples include publicly accessible + unprotected user data and public SSH access with + weak or no passwords. + + Threat: + + Indicates a threat that is able to access, + modify, or delete data or execute unauthorized + code within existing resources. + HIGH (2): + Vulnerability: + + A high risk vulnerability can be easily + discovered and exploited in combination with + other vulnerabilities in order to gain direct + access and the ability to execute arbitrary + code, exfiltrate data, and otherwise gain + additional access and privileges to cloud + resources and workloads. An example is a + database with weak or no passwords that is only + accessible internally. This database could + easily be compromised by an actor that had + access to the internal network. + + Threat: + + Indicates a threat that is able to create new + computational resources in an environment but + not able to access data or execute code in + existing resources. + MEDIUM (3): + Vulnerability: + + A medium risk vulnerability could be used by an + actor to gain access to resources or privileges + that enable them to eventually (through multiple + steps or a complex exploit) gain access and the + ability to execute arbitrary code or exfiltrate + data. An example is a service account with + access to more projects than it should have. If + an actor gains access to the service account, + they could potentially use that access to + manipulate a project the service account was not + intended to. + + Threat: + + Indicates a threat that is able to cause + operational impact but may not access data or + execute unauthorized code. + LOW (4): + Vulnerability: + + A low risk vulnerability hampers a security + organization's ability to detect vulnerabilities + or active threats in their deployment, or + prevents the root cause investigation of + security issues. An example is monitoring and + logs being disabled for resource configurations + and access. + + Threat: + + Indicates a threat that has obtained minimal + access to an environment but is not able to + access data, execute code, or create resources. + """ + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + HIGH = 2 + MEDIUM = 3 + LOW = 4 + + class Mute(proto.Enum): + r"""Mute state a finding can be in. + + Values: + MUTE_UNSPECIFIED (0): + Unspecified. + MUTED (1): + Finding has been muted. + UNMUTED (2): + Finding has been unmuted. + UNDEFINED (3): + Finding has never been muted/unmuted. + """ + MUTE_UNSPECIFIED = 0 + MUTED = 1 + UNMUTED = 2 + UNDEFINED = 3 + + class FindingClass(proto.Enum): + r"""Represents what kind of Finding it is. + + Values: + FINDING_CLASS_UNSPECIFIED (0): + Unspecified finding class. + THREAT (1): + Describes unwanted or malicious activity. + VULNERABILITY (2): + Describes a potential weakness in software + that increases risk to Confidentiality & + Integrity & Availability. + MISCONFIGURATION (3): + Describes a potential weakness in cloud + resource/asset configuration that increases + risk. + OBSERVATION (4): + Describes a security observation that is for + informational purposes. + SCC_ERROR (5): + Describes an error that prevents some SCC + functionality. + POSTURE_VIOLATION (6): + Describes a potential security risk due to a + change in the security posture. + TOXIC_COMBINATION (7): + Describes a combination of security issues + that represent a more severe security problem + when taken together. + """ + FINDING_CLASS_UNSPECIFIED = 0 + THREAT = 1 + VULNERABILITY = 2 + MISCONFIGURATION = 3 + OBSERVATION = 4 + SCC_ERROR = 5 + POSTURE_VIOLATION = 6 + TOXIC_COMBINATION = 7 + + class MuteInfo(proto.Message): + r"""Mute information about the finding, including whether the + finding has a static mute or any matching dynamic mute rules. + + Attributes: + static_mute (google.cloud.securitycenter_v2.types.Finding.MuteInfo.StaticMute): + If set, the static mute applied to this + finding. Static mutes override dynamic mutes. If + unset, there is no static mute. + dynamic_mute_records (MutableSequence[google.cloud.securitycenter_v2.types.Finding.MuteInfo.DynamicMuteRecord]): + The list of dynamic mute rules that currently + match the finding. + """ + + class StaticMute(proto.Message): + r"""Information about the static mute state. A static mute state + overrides any dynamic mute rules that apply to this finding. The + static mute state can be set by a static mute rule or by muting + the finding directly. + + Attributes: + state (google.cloud.securitycenter_v2.types.Finding.Mute): + The static mute state. If the value is ``MUTED`` or + ``UNMUTED``, then the finding's overall mute state will have + the same value. + apply_time (google.protobuf.timestamp_pb2.Timestamp): + When the static mute was applied. + """ + + state: 'Finding.Mute' = proto.Field( + proto.ENUM, + number=1, + enum='Finding.Mute', + ) + apply_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + class DynamicMuteRecord(proto.Message): + r"""The record of a dynamic mute rule that matches the finding. + + Attributes: + mute_config (str): + The relative resource name of the mute rule, represented by + a mute config, that created this record, for example + ``organizations/123/muteConfigs/mymuteconfig`` or + ``organizations/123/locations/global/muteConfigs/mymuteconfig``. + match_time (google.protobuf.timestamp_pb2.Timestamp): + When the dynamic mute rule first matched the + finding. + """ + + mute_config: str = proto.Field( + proto.STRING, + number=1, + ) + match_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + static_mute: 'Finding.MuteInfo.StaticMute' = proto.Field( + proto.MESSAGE, + number=1, + message='Finding.MuteInfo.StaticMute', + ) + dynamic_mute_records: MutableSequence['Finding.MuteInfo.DynamicMuteRecord'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Finding.MuteInfo.DynamicMuteRecord', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=2, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + resource_name: str = proto.Field( + proto.STRING, + number=4, + ) + state: State = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + category: str = proto.Field( + proto.STRING, + number=7, + ) + external_uri: str = proto.Field( + proto.STRING, + number=8, + ) + source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=9, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=10, + message=gcs_security_marks.SecurityMarks, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=14, + enum=Severity, + ) + mute: Mute = proto.Field( + proto.ENUM, + number=15, + enum=Mute, + ) + mute_info: MuteInfo = proto.Field( + proto.MESSAGE, + number=53, + message=MuteInfo, + ) + finding_class: FindingClass = proto.Field( + proto.ENUM, + number=16, + enum=FindingClass, + ) + indicator: gcs_indicator.Indicator = proto.Field( + proto.MESSAGE, + number=17, + message=gcs_indicator.Indicator, + ) + vulnerability: gcs_vulnerability.Vulnerability = proto.Field( + proto.MESSAGE, + number=18, + message=gcs_vulnerability.Vulnerability, + ) + mute_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + external_systems: MutableMapping[str, external_system.ExternalSystem] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=20, + message=external_system.ExternalSystem, + ) + mitre_attack: gcs_mitre_attack.MitreAttack = proto.Field( + proto.MESSAGE, + number=21, + message=gcs_mitre_attack.MitreAttack, + ) + access: gcs_access.Access = proto.Field( + proto.MESSAGE, + number=22, + message=gcs_access.Access, + ) + connections: MutableSequence[connection.Connection] = proto.RepeatedField( + proto.MESSAGE, + number=23, + message=connection.Connection, + ) + mute_initiator: str = proto.Field( + proto.STRING, + number=24, + ) + processes: MutableSequence[process.Process] = proto.RepeatedField( + proto.MESSAGE, + number=25, + message=process.Process, + ) + contacts: MutableMapping[str, contact_details.ContactDetails] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=26, + message=contact_details.ContactDetails, + ) + compliances: MutableSequence[compliance.Compliance] = proto.RepeatedField( + proto.MESSAGE, + number=27, + message=compliance.Compliance, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=29, + ) + description: str = proto.Field( + proto.STRING, + number=30, + ) + exfiltration: gcs_exfiltration.Exfiltration = proto.Field( + proto.MESSAGE, + number=31, + message=gcs_exfiltration.Exfiltration, + ) + iam_bindings: MutableSequence[iam_binding.IamBinding] = proto.RepeatedField( + proto.MESSAGE, + number=32, + message=iam_binding.IamBinding, + ) + next_steps: str = proto.Field( + proto.STRING, + number=33, + ) + module_name: str = proto.Field( + proto.STRING, + number=34, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=35, + message=container.Container, + ) + kubernetes: gcs_kubernetes.Kubernetes = proto.Field( + proto.MESSAGE, + number=36, + message=gcs_kubernetes.Kubernetes, + ) + database: gcs_database.Database = proto.Field( + proto.MESSAGE, + number=37, + message=gcs_database.Database, + ) + attack_exposure: gcs_attack_exposure.AttackExposure = proto.Field( + proto.MESSAGE, + number=38, + message=gcs_attack_exposure.AttackExposure, + ) + files: MutableSequence[file.File] = proto.RepeatedField( + proto.MESSAGE, + number=39, + message=file.File, + ) + cloud_dlp_inspection: gcs_cloud_dlp_inspection.CloudDlpInspection = proto.Field( + proto.MESSAGE, + number=40, + message=gcs_cloud_dlp_inspection.CloudDlpInspection, + ) + cloud_dlp_data_profile: gcs_cloud_dlp_data_profile.CloudDlpDataProfile = proto.Field( + proto.MESSAGE, + number=41, + message=gcs_cloud_dlp_data_profile.CloudDlpDataProfile, + ) + kernel_rootkit: gcs_kernel_rootkit.KernelRootkit = proto.Field( + proto.MESSAGE, + number=42, + message=gcs_kernel_rootkit.KernelRootkit, + ) + org_policies: MutableSequence[org_policy.OrgPolicy] = proto.RepeatedField( + proto.MESSAGE, + number=43, + message=org_policy.OrgPolicy, + ) + application: gcs_application.Application = proto.Field( + proto.MESSAGE, + number=45, + message=gcs_application.Application, + ) + backup_disaster_recovery: gcs_backup_disaster_recovery.BackupDisasterRecovery = proto.Field( + proto.MESSAGE, + number=47, + message=gcs_backup_disaster_recovery.BackupDisasterRecovery, + ) + security_posture: gcs_security_posture.SecurityPosture = proto.Field( + proto.MESSAGE, + number=48, + message=gcs_security_posture.SecurityPosture, + ) + log_entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( + proto.MESSAGE, + number=49, + message=log_entry.LogEntry, + ) + load_balancers: MutableSequence[load_balancer.LoadBalancer] = proto.RepeatedField( + proto.MESSAGE, + number=50, + message=load_balancer.LoadBalancer, + ) + cloud_armor: gcs_cloud_armor.CloudArmor = proto.Field( + proto.MESSAGE, + number=51, + message=gcs_cloud_armor.CloudArmor, + ) + notebook: gcs_notebook.Notebook = proto.Field( + proto.MESSAGE, + number=55, + message=gcs_notebook.Notebook, + ) + toxic_combination: gcs_toxic_combination.ToxicCombination = proto.Field( + proto.MESSAGE, + number=56, + message=gcs_toxic_combination.ToxicCombination, + ) + group_memberships: MutableSequence[group_membership.GroupMembership] = proto.RepeatedField( + proto.MESSAGE, + number=57, + message=group_membership.GroupMembership, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.py new file mode 100644 index 000000000000..2f26d5d13947 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.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.securitycenter.v2', + manifest={ + 'Folder', + }, +) + + +class Folder(proto.Message): + r"""Message that contains the resource name and display name of a + folder resource. + + Attributes: + resource_folder (str): + Full resource name of this folder. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_folder_display_name (str): + The user defined display name for this + folder. + """ + + resource_folder: str = proto.Field( + proto.STRING, + number=1, + ) + resource_folder_display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.py new file mode 100644 index 000000000000..bfe69eac6001 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.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.cloud.securitycenter.v2', + manifest={ + 'GroupMembership', + }, +) + + +class GroupMembership(proto.Message): + r"""Contains details about groups of which this finding is a + member. A group is a collection of findings that are related in + some way. + + Attributes: + group_type (google.cloud.securitycenter_v2.types.GroupMembership.GroupType): + Type of group. + group_id (str): + ID of the group. + """ + class GroupType(proto.Enum): + r"""Possible types of groups. + + Values: + GROUP_TYPE_UNSPECIFIED (0): + Default value. + GROUP_TYPE_TOXIC_COMBINATION (1): + Group represents a toxic combination. + """ + GROUP_TYPE_UNSPECIFIED = 0 + GROUP_TYPE_TOXIC_COMBINATION = 1 + + group_type: GroupType = proto.Field( + proto.ENUM, + number=1, + enum=GroupType, + ) + group_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py new file mode 100644 index 000000000000..17591c35825f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v2', + manifest={ + 'IamBinding', + }, +) + + +class IamBinding(proto.Message): + r"""Represents a particular IAM binding, which captures a + member's role addition, removal, or state. + + Attributes: + action (google.cloud.securitycenter_v2.types.IamBinding.Action): + The action that was performed on a Binding. + role (str): + Role that is assigned to "members". + For example, "roles/viewer", "roles/editor", or + "roles/owner". + member (str): + A single identity requesting access for a + Cloud Platform resource, for example, + "foo@google.com". + """ + class Action(proto.Enum): + r"""The type of action performed on a Binding in a policy. + + Values: + ACTION_UNSPECIFIED (0): + Unspecified. + ADD (1): + Addition of a Binding. + REMOVE (2): + Removal of a Binding. + """ + ACTION_UNSPECIFIED = 0 + ADD = 1 + REMOVE = 2 + + action: Action = proto.Field( + proto.ENUM, + number=1, + enum=Action, + ) + role: str = proto.Field( + proto.STRING, + number=2, + ) + member: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py new file mode 100644 index 000000000000..01b0184ef591 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v2', + manifest={ + 'Indicator', + }, +) + + +class Indicator(proto.Message): + r"""Represents what's commonly known as an *indicator of compromise* + (IoC) in computer forensics. This is an artifact observed on a + network or in an operating system that, with high confidence, + indicates a computer intrusion. For more information, see `Indicator + of + compromise `__. + + Attributes: + ip_addresses (MutableSequence[str]): + The list of IP addresses that are associated + with the finding. + domains (MutableSequence[str]): + List of domains associated to the Finding. + signatures (MutableSequence[google.cloud.securitycenter_v2.types.Indicator.ProcessSignature]): + The list of matched signatures indicating + that the given process is present in the + environment. + uris (MutableSequence[str]): + The list of URIs associated to the Findings. + """ + + class ProcessSignature(proto.Message): + r"""Indicates what signature matched this process. + + 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: + memory_hash_signature (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.MemoryHashSignature): + Signature indicating that a binary family was + matched. + + This field is a member of `oneof`_ ``signature``. + yara_rule_signature (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.YaraRuleSignature): + Signature indicating that a YARA rule was + matched. + + This field is a member of `oneof`_ ``signature``. + signature_type (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.SignatureType): + Describes the type of resource associated + with the signature. + """ + class SignatureType(proto.Enum): + r"""Possible resource types to be associated with a signature. + + Values: + SIGNATURE_TYPE_UNSPECIFIED (0): + The default signature type. + SIGNATURE_TYPE_PROCESS (1): + Used for signatures concerning processes. + SIGNATURE_TYPE_FILE (2): + Used for signatures concerning disks. + """ + SIGNATURE_TYPE_UNSPECIFIED = 0 + SIGNATURE_TYPE_PROCESS = 1 + SIGNATURE_TYPE_FILE = 2 + + class MemoryHashSignature(proto.Message): + r"""A signature corresponding to memory page hashes. + + Attributes: + binary_family (str): + The binary family. + detections (MutableSequence[google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.MemoryHashSignature.Detection]): + The list of memory hash detections + contributing to the binary family match. + """ + + class Detection(proto.Message): + r"""Memory hash detection contributing to the binary family + match. + + Attributes: + binary (str): + The name of the binary associated with the + memory hash signature detection. + percent_pages_matched (float): + The percentage of memory page hashes in the + signature that were matched. + """ + + binary: str = proto.Field( + proto.STRING, + number=2, + ) + percent_pages_matched: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + binary_family: str = proto.Field( + proto.STRING, + number=1, + ) + detections: MutableSequence['Indicator.ProcessSignature.MemoryHashSignature.Detection'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Indicator.ProcessSignature.MemoryHashSignature.Detection', + ) + + class YaraRuleSignature(proto.Message): + r"""A signature corresponding to a YARA rule. + + Attributes: + yara_rule (str): + The name of the YARA rule. + """ + + yara_rule: str = proto.Field( + proto.STRING, + number=5, + ) + + memory_hash_signature: 'Indicator.ProcessSignature.MemoryHashSignature' = proto.Field( + proto.MESSAGE, + number=6, + oneof='signature', + message='Indicator.ProcessSignature.MemoryHashSignature', + ) + yara_rule_signature: 'Indicator.ProcessSignature.YaraRuleSignature' = proto.Field( + proto.MESSAGE, + number=7, + oneof='signature', + message='Indicator.ProcessSignature.YaraRuleSignature', + ) + signature_type: 'Indicator.ProcessSignature.SignatureType' = proto.Field( + proto.ENUM, + number=8, + enum='Indicator.ProcessSignature.SignatureType', + ) + + ip_addresses: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + domains: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + signatures: MutableSequence[ProcessSignature] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=ProcessSignature, + ) + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.py new file mode 100644 index 000000000000..c57d1db94570 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'KernelRootkit', + }, +) + + +class KernelRootkit(proto.Message): + r"""Kernel mode rootkit signatures. + + Attributes: + name (str): + Rootkit name, when available. + unexpected_code_modification (bool): + True if unexpected modifications of kernel + code memory are present. + unexpected_read_only_data_modification (bool): + True if unexpected modifications of kernel + read-only data memory are present. + unexpected_ftrace_handler (bool): + True if ``ftrace`` points are present with callbacks + pointing to regions that are not in the expected kernel or + module code range. + unexpected_kprobe_handler (bool): + True if ``kprobe`` points are present with callbacks + pointing to regions that are not in the expected kernel or + module code range. + unexpected_kernel_code_pages (bool): + True if kernel code pages that are not in the + expected kernel or module code regions are + present. + unexpected_system_call_handler (bool): + True if system call handlers that are are not + in the expected kernel or module code regions + are present. + unexpected_interrupt_handler (bool): + True if interrupt handlers that are are not + in the expected kernel or module code regions + are present. + unexpected_processes_in_runqueue (bool): + True if unexpected processes in the scheduler + run queue are present. Such processes are in the + run queue, but not in the process task list. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + unexpected_code_modification: bool = proto.Field( + proto.BOOL, + number=2, + ) + unexpected_read_only_data_modification: bool = proto.Field( + proto.BOOL, + number=3, + ) + unexpected_ftrace_handler: bool = proto.Field( + proto.BOOL, + number=4, + ) + unexpected_kprobe_handler: bool = proto.Field( + proto.BOOL, + number=5, + ) + unexpected_kernel_code_pages: bool = proto.Field( + proto.BOOL, + number=6, + ) + unexpected_system_call_handler: bool = proto.Field( + proto.BOOL, + number=7, + ) + unexpected_interrupt_handler: bool = proto.Field( + proto.BOOL, + number=8, + ) + unexpected_processes_in_runqueue: bool = proto.Field( + proto.BOOL, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.py new file mode 100644 index 000000000000..8bc758c1f961 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v2.types import container +from google.cloud.securitycenter_v2.types import label + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Kubernetes', + }, +) + + +class Kubernetes(proto.Message): + r"""Kubernetes-related attributes. + + Attributes: + pods (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Pod]): + Kubernetes + `Pods `__ + associated with the finding. This field contains Pod records + for each container that is owned by a Pod. + nodes (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Node]): + Provides Kubernetes + `node `__ + information. + node_pools (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.NodePool]): + GKE `node + pools `__ + associated with the finding. This field contains node pool + information for each node, when it is available. + roles (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Role]): + Provides Kubernetes role information for findings that + involve `Roles or + ClusterRoles `__. + bindings (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Binding]): + Provides Kubernetes role binding information for findings + that involve `RoleBindings or + ClusterRoleBindings `__. + access_reviews (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.AccessReview]): + Provides information on any Kubernetes access + reviews (privilege checks) relevant to the + finding. + objects (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Object]): + Kubernetes objects related to the finding. + """ + + class Pod(proto.Message): + r"""A Kubernetes Pod. + + Attributes: + ns (str): + Kubernetes Pod namespace. + name (str): + Kubernetes Pod name. + labels (MutableSequence[google.cloud.securitycenter_v2.types.Label]): + Pod labels. For Kubernetes containers, these + are applied to the container. + containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): + Pod containers associated with this finding, + if any. + """ + + ns: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + labels: MutableSequence[label.Label] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=label.Label, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=container.Container, + ) + + class Node(proto.Message): + r"""Kubernetes nodes associated with the finding. + + Attributes: + name (str): + `Full resource + name `__ of + the Compute Engine VM running the cluster node. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + class NodePool(proto.Message): + r"""Provides GKE node pool information. + + Attributes: + name (str): + Kubernetes node pool name. + nodes (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Node]): + Nodes associated with the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + nodes: MutableSequence['Kubernetes.Node'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Kubernetes.Node', + ) + + class Role(proto.Message): + r"""Kubernetes Role or ClusterRole. + + Attributes: + kind (google.cloud.securitycenter_v2.types.Kubernetes.Role.Kind): + Role type. + ns (str): + Role namespace. + name (str): + Role name. + """ + class Kind(proto.Enum): + r"""Types of Kubernetes roles. + + Values: + KIND_UNSPECIFIED (0): + Role type is not specified. + ROLE (1): + Kubernetes Role. + CLUSTER_ROLE (2): + Kubernetes ClusterRole. + """ + KIND_UNSPECIFIED = 0 + ROLE = 1 + CLUSTER_ROLE = 2 + + kind: 'Kubernetes.Role.Kind' = proto.Field( + proto.ENUM, + number=1, + enum='Kubernetes.Role.Kind', + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class Binding(proto.Message): + r"""Represents a Kubernetes RoleBinding or ClusterRoleBinding. + + Attributes: + ns (str): + Namespace for the binding. + name (str): + Name for the binding. + role (google.cloud.securitycenter_v2.types.Kubernetes.Role): + The Role or ClusterRole referenced by the + binding. + subjects (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Subject]): + Represents one or more subjects that are + bound to the role. Not always available for + PATCH requests. + """ + + ns: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + role: 'Kubernetes.Role' = proto.Field( + proto.MESSAGE, + number=3, + message='Kubernetes.Role', + ) + subjects: MutableSequence['Kubernetes.Subject'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Kubernetes.Subject', + ) + + class Subject(proto.Message): + r"""Represents a Kubernetes subject. + + Attributes: + kind (google.cloud.securitycenter_v2.types.Kubernetes.Subject.AuthType): + Authentication type for the subject. + ns (str): + Namespace for the subject. + name (str): + Name for the subject. + """ + class AuthType(proto.Enum): + r"""Auth types that can be used for the subject's kind field. + + Values: + AUTH_TYPE_UNSPECIFIED (0): + Authentication is not specified. + USER (1): + User with valid certificate. + SERVICEACCOUNT (2): + Users managed by Kubernetes API with + credentials stored as secrets. + GROUP (3): + Collection of users. + """ + AUTH_TYPE_UNSPECIFIED = 0 + USER = 1 + SERVICEACCOUNT = 2 + GROUP = 3 + + kind: 'Kubernetes.Subject.AuthType' = proto.Field( + proto.ENUM, + number=1, + enum='Kubernetes.Subject.AuthType', + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class AccessReview(proto.Message): + r"""Conveys information about a Kubernetes access review (such as one + returned by a + ```kubectl auth can-i`` `__ + command) that was involved in a finding. + + Attributes: + group (str): + The API group of the resource. "*" means all. + ns (str): + Namespace of the action being requested. + Currently, there is no distinction between no + namespace and all namespaces. Both are + represented by "" (empty). + name (str): + The name of the resource being requested. + Empty means all. + resource (str): + The optional resource type requested. "*" means all. + subresource (str): + The optional subresource type. + verb (str): + A Kubernetes resource API verb, like get, list, watch, + create, update, delete, proxy. "*" means all. + version (str): + The API version of the resource. "*" means all. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + resource: str = proto.Field( + proto.STRING, + number=4, + ) + subresource: str = proto.Field( + proto.STRING, + number=5, + ) + verb: str = proto.Field( + proto.STRING, + number=6, + ) + version: str = proto.Field( + proto.STRING, + number=7, + ) + + class Object(proto.Message): + r"""Kubernetes object related to the finding, uniquely identified + by GKNN. Used if the object Kind is not one of Pod, Node, + NodePool, Binding, or AccessReview. + + Attributes: + group (str): + Kubernetes object group, such as + "policy.k8s.io/v1". + kind (str): + Kubernetes object kind, such as "Namespace". + ns (str): + Kubernetes object namespace. Must be a valid + DNS label. Named "ns" to avoid collision with + C++ namespace keyword. For details see + https://kubernetes.io/docs/tasks/administer-cluster/namespaces/. + name (str): + Kubernetes object name. For details see + https://kubernetes.io/docs/concepts/overview/working-with-objects/names/. + containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): + Pod containers associated with this finding, + if any. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + kind: str = proto.Field( + proto.STRING, + number=2, + ) + ns: str = proto.Field( + proto.STRING, + number=3, + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=container.Container, + ) + + pods: MutableSequence[Pod] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Pod, + ) + nodes: MutableSequence[Node] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Node, + ) + node_pools: MutableSequence[NodePool] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=NodePool, + ) + roles: MutableSequence[Role] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Role, + ) + bindings: MutableSequence[Binding] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Binding, + ) + access_reviews: MutableSequence[AccessReview] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=AccessReview, + ) + objects: MutableSequence[Object] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Object, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.py new file mode 100644 index 000000000000..d2f158e10cf6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.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.securitycenter.v2', + manifest={ + 'Label', + }, +) + + +class Label(proto.Message): + r"""Represents a generic name-value label. A label has separate name and + value fields to support filtering with the ``contains()`` function. + For more information, see `Filtering on array-type + fields `__. + + Attributes: + name (str): + Name of the label. + value (str): + Value that corresponds to the label's name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.py new file mode 100644 index 000000000000..95c16ba76680 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.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.cloud.securitycenter.v2', + manifest={ + 'LoadBalancer', + }, +) + + +class LoadBalancer(proto.Message): + r"""Contains information related to the load balancer associated + with the finding. + + Attributes: + name (str): + The name of the load balancer associated with + the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py new file mode 100644 index 000000000000..673caf996bad --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'LogEntry', + 'CloudLoggingEntry', + }, +) + + +class LogEntry(proto.Message): + r"""An individual entry in a log. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_logging_entry (google.cloud.securitycenter_v2.types.CloudLoggingEntry): + An individual entry in a log stored in Cloud + Logging. + + This field is a member of `oneof`_ ``log_entry``. + """ + + cloud_logging_entry: 'CloudLoggingEntry' = proto.Field( + proto.MESSAGE, + number=1, + oneof='log_entry', + message='CloudLoggingEntry', + ) + + +class CloudLoggingEntry(proto.Message): + r"""Metadata taken from a `Cloud Logging + LogEntry `__ + + Attributes: + insert_id (str): + A unique identifier for the log entry. + log_id (str): + The type of the log (part of ``log_name``. ``log_name`` is + the resource name of the log to which this log entry + belongs). For example: + ``cloudresourcemanager.googleapis.com/activity`` Note that + this field is not URL-encoded, unlike in ``LogEntry``. + resource_container (str): + The organization, folder, or project of the + monitored resource that produced this log entry. + timestamp (google.protobuf.timestamp_pb2.Timestamp): + The time the event described by the log entry + occurred. + """ + + insert_id: str = proto.Field( + proto.STRING, + number=1, + ) + log_id: str = proto.Field( + proto.STRING, + number=2, + ) + resource_container: str = proto.Field( + proto.STRING, + number=3, + ) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.py new file mode 100644 index 000000000000..d0a5c04b7853 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'MitreAttack', + }, +) + + +class MitreAttack(proto.Message): + r"""MITRE ATT&CK tactics and techniques related to this finding. + See: https://attack.mitre.org + + Attributes: + primary_tactic (google.cloud.securitycenter_v2.types.MitreAttack.Tactic): + The MITRE ATT&CK tactic most closely + represented by this finding, if any. + primary_techniques (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Technique]): + The MITRE ATT&CK technique most closely represented by this + finding, if any. primary_techniques is a repeated field + because there are multiple levels of MITRE ATT&CK + techniques. If the technique most closely represented by + this finding is a sub-technique (e.g. + ``SCANNING_IP_BLOCKS``), both the sub-technique and its + parent technique(s) will be listed (e.g. + ``SCANNING_IP_BLOCKS``, ``ACTIVE_SCANNING``). + additional_tactics (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Tactic]): + Additional MITRE ATT&CK tactics related to + this finding, if any. + additional_techniques (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Technique]): + Additional MITRE ATT&CK techniques related to + this finding, if any, along with any of their + respective parent techniques. + version (str): + The MITRE ATT&CK version referenced by the + above fields. E.g. "8". + """ + class Tactic(proto.Enum): + r"""MITRE ATT&CK tactics that can be referenced by SCC findings. + See: https://attack.mitre.org/tactics/enterprise/ + + Values: + TACTIC_UNSPECIFIED (0): + Unspecified value. + RECONNAISSANCE (1): + TA0043 + RESOURCE_DEVELOPMENT (2): + TA0042 + INITIAL_ACCESS (5): + TA0001 + EXECUTION (3): + TA0002 + PERSISTENCE (6): + TA0003 + PRIVILEGE_ESCALATION (8): + TA0004 + DEFENSE_EVASION (7): + TA0005 + CREDENTIAL_ACCESS (9): + TA0006 + DISCOVERY (10): + TA0007 + LATERAL_MOVEMENT (11): + TA0008 + COLLECTION (12): + TA0009 + COMMAND_AND_CONTROL (4): + TA0011 + EXFILTRATION (13): + TA0010 + IMPACT (14): + TA0040 + """ + TACTIC_UNSPECIFIED = 0 + RECONNAISSANCE = 1 + RESOURCE_DEVELOPMENT = 2 + INITIAL_ACCESS = 5 + EXECUTION = 3 + PERSISTENCE = 6 + PRIVILEGE_ESCALATION = 8 + DEFENSE_EVASION = 7 + CREDENTIAL_ACCESS = 9 + DISCOVERY = 10 + LATERAL_MOVEMENT = 11 + COLLECTION = 12 + COMMAND_AND_CONTROL = 4 + EXFILTRATION = 13 + IMPACT = 14 + + class Technique(proto.Enum): + r"""MITRE ATT&CK techniques that can be referenced by SCC + findings. See: https://attack.mitre.org/techniques/enterprise/ + Next ID: 65 + + Values: + TECHNIQUE_UNSPECIFIED (0): + Unspecified value. + MASQUERADING (49): + T1036 + MATCH_LEGITIMATE_NAME_OR_LOCATION (50): + T1036.005 + BOOT_OR_LOGON_INITIALIZATION_SCRIPTS (37): + T1037 + STARTUP_ITEMS (38): + T1037.005 + NETWORK_SERVICE_DISCOVERY (32): + T1046 + PROCESS_DISCOVERY (56): + T1057 + COMMAND_AND_SCRIPTING_INTERPRETER (6): + T1059 + UNIX_SHELL (7): + T1059.004 + PYTHON (59): + T1059.006 + EXPLOITATION_FOR_PRIVILEGE_ESCALATION (63): + T1068 + PERMISSION_GROUPS_DISCOVERY (18): + T1069 + CLOUD_GROUPS (19): + T1069.003 + INDICATOR_REMOVAL_FILE_DELETION (64): + T1070.004 + APPLICATION_LAYER_PROTOCOL (45): + T1071 + DNS (46): + T1071.004 + SOFTWARE_DEPLOYMENT_TOOLS (47): + T1072 + VALID_ACCOUNTS (14): + T1078 + DEFAULT_ACCOUNTS (35): + T1078.001 + LOCAL_ACCOUNTS (15): + T1078.003 + CLOUD_ACCOUNTS (16): + T1078.004 + PROXY (9): + T1090 + EXTERNAL_PROXY (10): + T1090.002 + MULTI_HOP_PROXY (11): + T1090.003 + ACCOUNT_MANIPULATION (22): + T1098 + ADDITIONAL_CLOUD_CREDENTIALS (40): + T1098.001 + SSH_AUTHORIZED_KEYS (23): + T1098.004 + ADDITIONAL_CONTAINER_CLUSTER_ROLES (58): + T1098.006 + INGRESS_TOOL_TRANSFER (3): + T1105 + NATIVE_API (4): + T1106 + BRUTE_FORCE (44): + T1110 + SHARED_MODULES (5): + T1129 + ACCESS_TOKEN_MANIPULATION (33): + T1134 + TOKEN_IMPERSONATION_OR_THEFT (39): + T1134.001 + EXPLOIT_PUBLIC_FACING_APPLICATION (27): + T1190 + DOMAIN_POLICY_MODIFICATION (30): + T1484 + DATA_DESTRUCTION (29): + T1485 + SERVICE_STOP (52): + T1489 + INHIBIT_SYSTEM_RECOVERY (36): + T1490 + RESOURCE_HIJACKING (8): + T1496 + NETWORK_DENIAL_OF_SERVICE (17): + T1498 + CLOUD_SERVICE_DISCOVERY (48): + T1526 + STEAL_APPLICATION_ACCESS_TOKEN (42): + T1528 + ACCOUNT_ACCESS_REMOVAL (51): + T1531 + STEAL_WEB_SESSION_COOKIE (25): + T1539 + CREATE_OR_MODIFY_SYSTEM_PROCESS (24): + T1543 + ABUSE_ELEVATION_CONTROL_MECHANISM (34): + T1548 + UNSECURED_CREDENTIALS (13): + T1552 + MODIFY_AUTHENTICATION_PROCESS (28): + T1556 + IMPAIR_DEFENSES (31): + T1562 + DISABLE_OR_MODIFY_TOOLS (55): + T1562.001 + EXFILTRATION_OVER_WEB_SERVICE (20): + T1567 + EXFILTRATION_TO_CLOUD_STORAGE (21): + T1567.002 + DYNAMIC_RESOLUTION (12): + T1568 + LATERAL_TOOL_TRANSFER (41): + T1570 + MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE (26): + T1578 + CREATE_SNAPSHOT (54): + T1578.001 + CLOUD_INFRASTRUCTURE_DISCOVERY (53): + T1580 + OBTAIN_CAPABILITIES (43): + T1588 + ACTIVE_SCANNING (1): + T1595 + SCANNING_IP_BLOCKS (2): + T1595.001 + CONTAINER_ADMINISTRATION_COMMAND (60): + T1609 + ESCAPE_TO_HOST (61): + T1611 + CONTAINER_AND_RESOURCE_DISCOVERY (57): + T1613 + STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES (62): + T1649 + """ + TECHNIQUE_UNSPECIFIED = 0 + MASQUERADING = 49 + MATCH_LEGITIMATE_NAME_OR_LOCATION = 50 + BOOT_OR_LOGON_INITIALIZATION_SCRIPTS = 37 + STARTUP_ITEMS = 38 + NETWORK_SERVICE_DISCOVERY = 32 + PROCESS_DISCOVERY = 56 + COMMAND_AND_SCRIPTING_INTERPRETER = 6 + UNIX_SHELL = 7 + PYTHON = 59 + EXPLOITATION_FOR_PRIVILEGE_ESCALATION = 63 + PERMISSION_GROUPS_DISCOVERY = 18 + CLOUD_GROUPS = 19 + INDICATOR_REMOVAL_FILE_DELETION = 64 + APPLICATION_LAYER_PROTOCOL = 45 + DNS = 46 + SOFTWARE_DEPLOYMENT_TOOLS = 47 + VALID_ACCOUNTS = 14 + DEFAULT_ACCOUNTS = 35 + LOCAL_ACCOUNTS = 15 + CLOUD_ACCOUNTS = 16 + PROXY = 9 + EXTERNAL_PROXY = 10 + MULTI_HOP_PROXY = 11 + ACCOUNT_MANIPULATION = 22 + ADDITIONAL_CLOUD_CREDENTIALS = 40 + SSH_AUTHORIZED_KEYS = 23 + ADDITIONAL_CONTAINER_CLUSTER_ROLES = 58 + INGRESS_TOOL_TRANSFER = 3 + NATIVE_API = 4 + BRUTE_FORCE = 44 + SHARED_MODULES = 5 + ACCESS_TOKEN_MANIPULATION = 33 + TOKEN_IMPERSONATION_OR_THEFT = 39 + EXPLOIT_PUBLIC_FACING_APPLICATION = 27 + DOMAIN_POLICY_MODIFICATION = 30 + DATA_DESTRUCTION = 29 + SERVICE_STOP = 52 + INHIBIT_SYSTEM_RECOVERY = 36 + RESOURCE_HIJACKING = 8 + NETWORK_DENIAL_OF_SERVICE = 17 + CLOUD_SERVICE_DISCOVERY = 48 + STEAL_APPLICATION_ACCESS_TOKEN = 42 + ACCOUNT_ACCESS_REMOVAL = 51 + STEAL_WEB_SESSION_COOKIE = 25 + CREATE_OR_MODIFY_SYSTEM_PROCESS = 24 + ABUSE_ELEVATION_CONTROL_MECHANISM = 34 + UNSECURED_CREDENTIALS = 13 + MODIFY_AUTHENTICATION_PROCESS = 28 + IMPAIR_DEFENSES = 31 + DISABLE_OR_MODIFY_TOOLS = 55 + EXFILTRATION_OVER_WEB_SERVICE = 20 + EXFILTRATION_TO_CLOUD_STORAGE = 21 + DYNAMIC_RESOLUTION = 12 + LATERAL_TOOL_TRANSFER = 41 + MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE = 26 + CREATE_SNAPSHOT = 54 + CLOUD_INFRASTRUCTURE_DISCOVERY = 53 + OBTAIN_CAPABILITIES = 43 + ACTIVE_SCANNING = 1 + SCANNING_IP_BLOCKS = 2 + CONTAINER_ADMINISTRATION_COMMAND = 60 + ESCAPE_TO_HOST = 61 + CONTAINER_AND_RESOURCE_DISCOVERY = 57 + STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES = 62 + + primary_tactic: Tactic = proto.Field( + proto.ENUM, + number=1, + enum=Tactic, + ) + primary_techniques: MutableSequence[Technique] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=Technique, + ) + additional_tactics: MutableSequence[Tactic] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=Tactic, + ) + additional_techniques: MutableSequence[Technique] = proto.RepeatedField( + proto.ENUM, + number=4, + enum=Technique, + ) + version: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.py new file mode 100644 index 000000000000..47f95ac38c38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.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.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'MuteConfig', + }, +) + + +class MuteConfig(proto.Message): + r"""A mute config is a Cloud SCC resource that contains the + configuration to mute create/update events of findings. + + Attributes: + name (str): + Identifier. This field will be ignored if provided on config + creation. The following list shows some examples of the + format: + + - ``organizations/{organization}/muteConfigs/{mute_config}`` + - + + ``organizations/{organization}locations/{location}//muteConfigs/{mute_config}`` + + - ``folders/{folder}/muteConfigs/{mute_config}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{mute_config}`` + - ``projects/{project}/muteConfigs/{mute_config}`` + - ``projects/{project}/locations/{location}/muteConfigs/{mute_config}`` + description (str): + A description of the mute config. + filter (str): + Required. An expression that defines the filter to apply + across create/update events of findings. While creating a + filter string, be mindful of the scope in which the mute + configuration is being created. E.g., If a filter contains + project = X but is created under the project = Y scope, it + might not match any findings. + + The following field and operator combinations are supported: + + - severity: ``=``, ``:`` + - category: ``=``, ``:`` + - resource.name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.folders.resource_folder: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + - finding_class: ``=``, ``:`` + - indicator.ip_addresses: ``=``, ``:`` + - indicator.domains: ``=``, ``:`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the mute + config was created. This field is set by the + server and will be ignored if provided on config + creation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time at which + the mute config was updated. This field is set + by the server and will be ignored if provided on + config creation or update. + most_recent_editor (str): + Output only. Email address of the user who + last edited the mute config. This field is set + by the server and will be ignored if provided on + config creation or update. + type_ (google.cloud.securitycenter_v2.types.MuteConfig.MuteConfigType): + Required. The type of the mute config, which + determines what type of mute state the config + affects. Immutable after creation. + expiry_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The expiry of the mute config. Only + applicable for dynamic configs. If the expiry is + set, when the config expires, it is removed from + all findings. + """ + class MuteConfigType(proto.Enum): + r"""The type of MuteConfig. + + Values: + MUTE_CONFIG_TYPE_UNSPECIFIED (0): + Unused. + STATIC (1): + A static mute config, which sets the static + mute state of future matching findings to muted. + Once the static mute state has been set, finding + or config modifications will not affect the + state. + DYNAMIC (2): + A dynamic mute config, which is applied to + existing and future matching findings, setting + their dynamic mute state to "muted". If the + config is updated or deleted, or a matching + finding is updated, such that the finding + doesn't match the config, the config will be + removed from the finding, and the finding's + dynamic mute state may become "unmuted" (unless + other configs still match). + """ + MUTE_CONFIG_TYPE_UNSPECIFIED = 0 + STATIC = 1 + DYNAMIC = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + most_recent_editor: str = proto.Field( + proto.STRING, + number=6, + ) + type_: MuteConfigType = proto.Field( + proto.ENUM, + number=8, + enum=MuteConfigType, + ) + expiry_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py new file mode 100644 index 000000000000..6fe873edc33e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v2', + manifest={ + 'Notebook', + }, +) + + +class Notebook(proto.Message): + r"""Represents a Jupyter notebook IPYNB file, such as a `Colab + Enterprise + notebook `__ file, + that is associated with a finding. + + Attributes: + name (str): + The name of the notebook. + service (str): + The source notebook service, for example, + "Colab Enterprise". + last_author (str): + The user ID of the latest author to modify + the notebook. + notebook_update_time (google.protobuf.timestamp_pb2.Timestamp): + The most recent time the notebook was + updated. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + service: str = proto.Field( + proto.STRING, + number=2, + ) + last_author: str = proto.Field( + proto.STRING, + number=3, + ) + notebook_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py new file mode 100644 index 000000000000..73797dfbbbb8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v2', + manifest={ + 'NotificationConfig', + }, +) + + +class NotificationConfig(proto.Message): + r"""Cloud Security Command Center (Cloud SCC) notification + configs. + A notification config is a Cloud SCC resource that contains the + configuration to send notifications for create/update events of + findings, assets and etc. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The relative resource name of this notification + config. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + The following list shows some examples: + + ``organizations/{organization_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` + + + ``folders/{folder_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` + + + ``projects/{project_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` + description (str): + The description of the notification config + (max of 1024 characters). + pubsub_topic (str): + The Pub/Sub topic to send notifications to. Its format is + "projects/[project_id]/topics/[topic]". + service_account (str): + Output only. The service account that needs + "pubsub.topics.publish" permission to publish to + the Pub/Sub topic. + streaming_config (google.cloud.securitycenter_v2.types.NotificationConfig.StreamingConfig): + The config for triggering streaming-based + notifications. + + This field is a member of `oneof`_ ``notify_config``. + """ + + class StreamingConfig(proto.Message): + r"""The config for streaming-based notifications, which send each + event as soon as it is detected. + + Attributes: + filter (str): + Expression that defines the filter to apply across + create/update events of assets or findings as specified by + the event type. The expression is a list of zero or more + restrictions combined via logical operators ``AND`` and + ``OR``. Parentheses are supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + """ + + filter: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + pubsub_topic: str = proto.Field( + proto.STRING, + number=3, + ) + service_account: str = proto.Field( + proto.STRING, + number=4, + ) + streaming_config: StreamingConfig = proto.Field( + proto.MESSAGE, + number=5, + oneof='notify_config', + message=StreamingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.py new file mode 100644 index 000000000000..cbe17b52c42a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import resource as gcs_resource + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'NotificationMessage', + }, +) + + +class NotificationMessage(proto.Message): + r"""Cloud SCC's Notification + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + notification_config_name (str): + Name of the notification config that + generated current notification. + finding (google.cloud.securitycenter_v2.types.Finding): + If it's a Finding based notification config, + this field will be populated. + + This field is a member of `oneof`_ ``event``. + resource (google.cloud.securitycenter_v2.types.Resource): + The Cloud resource tied to this + notification's Finding. + """ + + notification_config_name: str = proto.Field( + proto.STRING, + number=1, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=2, + oneof='event', + message=gcs_finding.Finding, + ) + resource: gcs_resource.Resource = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_resource.Resource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.py new file mode 100644 index 000000000000..afd2ecb275f7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.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.cloud.securitycenter.v2', + manifest={ + 'OrgPolicy', + }, +) + + +class OrgPolicy(proto.Message): + r"""Contains information about the org policies associated with + the finding. + + Attributes: + name (str): + The resource name of the org policy. Example: + "organizations/{organization_id}/policies/{constraint_name}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py new file mode 100644 index 000000000000..567e7cceaa35 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v2.types import file + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Process', + 'EnvironmentVariable', + }, +) + + +class Process(proto.Message): + r"""Represents an operating system process. + + Attributes: + name (str): + The process name, as displayed in utilities like ``top`` and + ``ps``. This name can be accessed through + ``/proc/[pid]/comm`` and changed with + ``prctl(PR_SET_NAME)``. + binary (google.cloud.securitycenter_v2.types.File): + File information for the process executable. + libraries (MutableSequence[google.cloud.securitycenter_v2.types.File]): + File information for libraries loaded by the + process. + script (google.cloud.securitycenter_v2.types.File): + When the process represents the invocation of a script, + ``binary`` provides information about the interpreter, while + ``script`` provides information about the script file + provided to the interpreter. + args (MutableSequence[str]): + Process arguments as JSON encoded strings. + arguments_truncated (bool): + True if ``args`` is incomplete. + env_variables (MutableSequence[google.cloud.securitycenter_v2.types.EnvironmentVariable]): + Process environment variables. + env_variables_truncated (bool): + True if ``env_variables`` is incomplete. + pid (int): + The process ID. + parent_pid (int): + The parent process ID. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + binary: file.File = proto.Field( + proto.MESSAGE, + number=2, + message=file.File, + ) + libraries: MutableSequence[file.File] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=file.File, + ) + script: file.File = proto.Field( + proto.MESSAGE, + number=4, + message=file.File, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + arguments_truncated: bool = proto.Field( + proto.BOOL, + number=6, + ) + env_variables: MutableSequence['EnvironmentVariable'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='EnvironmentVariable', + ) + env_variables_truncated: bool = proto.Field( + proto.BOOL, + number=8, + ) + pid: int = proto.Field( + proto.INT64, + number=9, + ) + parent_pid: int = proto.Field( + proto.INT64, + number=10, + ) + + +class EnvironmentVariable(proto.Message): + r"""A name-value pair representing an environment variable used + in an operating system process. + + Attributes: + name (str): + Environment variable name as a JSON encoded + string. + val (str): + Environment variable value as a JSON encoded + string. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + val: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.py new file mode 100644 index 000000000000..491062813849 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.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 + +from google.cloud.securitycenter_v2.types import folder + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'CloudProvider', + 'Resource', + 'GcpMetadata', + 'AwsMetadata', + 'AzureMetadata', + 'ResourcePath', + }, +) + + +class CloudProvider(proto.Enum): + r"""The cloud provider the finding pertains to. + + Values: + CLOUD_PROVIDER_UNSPECIFIED (0): + The cloud provider is unspecified. + GOOGLE_CLOUD_PLATFORM (1): + The cloud provider is Google Cloud Platform. + AMAZON_WEB_SERVICES (2): + The cloud provider is Amazon Web Services. + MICROSOFT_AZURE (3): + The cloud provider is Microsoft Azure. + """ + CLOUD_PROVIDER_UNSPECIFIED = 0 + GOOGLE_CLOUD_PLATFORM = 1 + AMAZON_WEB_SERVICES = 2 + MICROSOFT_AZURE = 3 + + +class Resource(proto.Message): + r"""Information related to the Google Cloud 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): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + display_name (str): + The human readable name of the resource. + type_ (str): + The full resource type of the resource. + cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): + Indicates which cloud provider the finding is + from. + service (str): + The service or resource provider associated + with the resource. + location (str): + The region or location of the service (if + applicable). + gcp_metadata (google.cloud.securitycenter_v2.types.GcpMetadata): + The GCP metadata associated with the finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + aws_metadata (google.cloud.securitycenter_v2.types.AwsMetadata): + The AWS metadata associated with the finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + azure_metadata (google.cloud.securitycenter_v2.types.AzureMetadata): + The Azure metadata associated with the + finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + resource_path (google.cloud.securitycenter_v2.types.ResourcePath): + Provides the path to the resource within the + resource hierarchy. + resource_path_string (str): + A string representation of the resource path. For Google + Cloud, it has the format of + ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` + where there can be any number of folders. For AWS, it has + the format of + ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` + where there can be any number of organizational units. For + Azure, it has the format of + ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` + where there can be any number of management groups. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + type_: str = proto.Field( + proto.STRING, + number=3, + ) + cloud_provider: 'CloudProvider' = proto.Field( + proto.ENUM, + number=4, + enum='CloudProvider', + ) + service: str = proto.Field( + proto.STRING, + number=5, + ) + location: str = proto.Field( + proto.STRING, + number=6, + ) + gcp_metadata: 'GcpMetadata' = proto.Field( + proto.MESSAGE, + number=7, + oneof='cloud_provider_metadata', + message='GcpMetadata', + ) + aws_metadata: 'AwsMetadata' = proto.Field( + proto.MESSAGE, + number=8, + oneof='cloud_provider_metadata', + message='AwsMetadata', + ) + azure_metadata: 'AzureMetadata' = proto.Field( + proto.MESSAGE, + number=9, + oneof='cloud_provider_metadata', + message='AzureMetadata', + ) + resource_path: 'ResourcePath' = proto.Field( + proto.MESSAGE, + number=10, + message='ResourcePath', + ) + resource_path_string: str = proto.Field( + proto.STRING, + number=11, + ) + + +class GcpMetadata(proto.Message): + r"""GCP metadata associated with the resource, only applicable if + the finding's cloud provider is Google Cloud Platform. + + Attributes: + project (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The project ID that the resource belongs to. + parent (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (MutableSequence[google.cloud.securitycenter_v2.types.Folder]): + Output only. Contains a Folder message for + each folder in the assets ancestry. The first + folder is the deepest nested folder, and the + last folder is the folder directly under the + Organization. + organization (str): + The name of the organization that the + resource belongs to. + """ + + project: str = proto.Field( + proto.STRING, + number=1, + ) + project_display_name: str = proto.Field( + proto.STRING, + number=2, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=4, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=folder.Folder, + ) + organization: str = proto.Field( + proto.STRING, + number=6, + ) + + +class AwsMetadata(proto.Message): + r"""AWS metadata associated with the resource, only applicable if + the finding's cloud provider is Amazon Web Services. + + Attributes: + organization (google.cloud.securitycenter_v2.types.AwsMetadata.AwsOrganization): + The AWS organization associated with the + resource. + organizational_units (MutableSequence[google.cloud.securitycenter_v2.types.AwsMetadata.AwsOrganizationalUnit]): + A list of AWS organizational units associated + with the resource, ordered from lowest level + (closest to the account) to highest level. + account (google.cloud.securitycenter_v2.types.AwsMetadata.AwsAccount): + The AWS account associated with the resource. + """ + + class AwsOrganization(proto.Message): + r"""An organization is a collection of accounts that are + centrally managed together using consolidated billing, organized + hierarchically with organizational units (OUs), and controlled + with policies. + + Attributes: + id (str): + The unique identifier (ID) for the + organization. The regex pattern for an + organization ID string requires "o-" followed by + from 10 to 32 lowercase letters or digits. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + + class AwsOrganizationalUnit(proto.Message): + r"""An Organizational Unit (OU) is a container of AWS accounts + within a root of an organization. Policies that are attached to + an OU apply to all accounts contained in that OU and in any + child OUs. + + Attributes: + id (str): + The unique identifier (ID) associated with + this OU. The regex pattern for an organizational + unit ID string requires "ou-" followed by from 4 + to 32 lowercase letters or digits (the ID of the + root that contains the OU). This string is + followed by a second "-" dash and from 8 to 32 + additional lowercase letters or digits. For + example, "ou-ab12-cd34ef56". + name (str): + The friendly name of the OU. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + + class AwsAccount(proto.Message): + r"""An AWS account that is a member of an organization. + + Attributes: + id (str): + The unique identifier (ID) of the account, + containing exactly 12 digits. + name (str): + The friendly name of this account. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + + organization: AwsOrganization = proto.Field( + proto.MESSAGE, + number=1, + message=AwsOrganization, + ) + organizational_units: MutableSequence[AwsOrganizationalUnit] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=AwsOrganizationalUnit, + ) + account: AwsAccount = proto.Field( + proto.MESSAGE, + number=3, + message=AwsAccount, + ) + + +class AzureMetadata(proto.Message): + r"""Azure metadata associated with the resource, only applicable + if the finding's cloud provider is Microsoft Azure. + + Attributes: + management_groups (MutableSequence[google.cloud.securitycenter_v2.types.AzureMetadata.AzureManagementGroup]): + A list of Azure management groups associated + with the resource, ordered from lowest level + (closest to the subscription) to highest level. + subscription (google.cloud.securitycenter_v2.types.AzureMetadata.AzureSubscription): + The Azure subscription associated with the + resource. + resource_group (google.cloud.securitycenter_v2.types.AzureMetadata.AzureResourceGroup): + The Azure resource group associated with the + resource. + """ + + class AzureManagementGroup(proto.Message): + r"""Represents an Azure management group. + + Attributes: + id (str): + The UUID of the Azure management group, for example, + ``20000000-0001-0000-0000-000000000000``. + display_name (str): + The display name of the Azure management + group. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + class AzureSubscription(proto.Message): + r"""Represents an Azure subscription. + + Attributes: + id (str): + The UUID of the Azure subscription, for example, + ``291bba3f-e0a5-47bc-a099-3bdcb2a50a05``. + display_name (str): + The display name of the Azure subscription. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + class AzureResourceGroup(proto.Message): + r"""Represents an Azure resource group. + + Attributes: + name (str): + The name of the Azure resource group. This is + not a UUID. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + management_groups: MutableSequence[AzureManagementGroup] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=AzureManagementGroup, + ) + subscription: AzureSubscription = proto.Field( + proto.MESSAGE, + number=2, + message=AzureSubscription, + ) + resource_group: AzureResourceGroup = proto.Field( + proto.MESSAGE, + number=3, + message=AzureResourceGroup, + ) + + +class ResourcePath(proto.Message): + r"""Represents the path of resources leading up to the resource + this finding is about. + + Attributes: + nodes (MutableSequence[google.cloud.securitycenter_v2.types.ResourcePath.ResourcePathNode]): + The list of nodes that make the up resource + path, ordered from lowest level to highest + level. + """ + class ResourcePathNodeType(proto.Enum): + r"""The type of resource the node represents. + + Values: + RESOURCE_PATH_NODE_TYPE_UNSPECIFIED (0): + Node type is unspecified. + GCP_ORGANIZATION (1): + The node represents a Google Cloud + organization. + GCP_FOLDER (2): + The node represents a Google Cloud folder. + GCP_PROJECT (3): + The node represents a Google Cloud project. + AWS_ORGANIZATION (4): + The node represents an AWS organization. + AWS_ORGANIZATIONAL_UNIT (5): + The node represents an AWS organizational + unit. + AWS_ACCOUNT (6): + The node represents an AWS account. + AZURE_MANAGEMENT_GROUP (7): + The node represents an Azure management + group. + AZURE_SUBSCRIPTION (8): + The node represents an Azure subscription. + AZURE_RESOURCE_GROUP (9): + The node represents an Azure resource group. + """ + RESOURCE_PATH_NODE_TYPE_UNSPECIFIED = 0 + GCP_ORGANIZATION = 1 + GCP_FOLDER = 2 + GCP_PROJECT = 3 + AWS_ORGANIZATION = 4 + AWS_ORGANIZATIONAL_UNIT = 5 + AWS_ACCOUNT = 6 + AZURE_MANAGEMENT_GROUP = 7 + AZURE_SUBSCRIPTION = 8 + AZURE_RESOURCE_GROUP = 9 + + class ResourcePathNode(proto.Message): + r"""A node within the resource path. Each node represents a + resource within the resource hierarchy. + + Attributes: + node_type (google.cloud.securitycenter_v2.types.ResourcePath.ResourcePathNodeType): + The type of resource this node represents. + id (str): + The ID of the resource this node represents. + display_name (str): + The display name of the resource this node + represents. + """ + + node_type: 'ResourcePath.ResourcePathNodeType' = proto.Field( + proto.ENUM, + number=1, + enum='ResourcePath.ResourcePathNodeType', + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + + nodes: MutableSequence[ResourcePathNode] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ResourcePathNode, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py new file mode 100644 index 000000000000..49a600dd79e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py @@ -0,0 +1,190 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v2.types import resource +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'ResourceValue', + 'ResourceValueConfig', + }, +) + + +class ResourceValue(proto.Enum): + r"""Value enum to map to a resource + + Values: + RESOURCE_VALUE_UNSPECIFIED (0): + Unspecific value + HIGH (1): + High resource value + MEDIUM (2): + Medium resource value + LOW (3): + Low resource value + NONE (4): + No resource value, e.g. ignore these + resources + """ + RESOURCE_VALUE_UNSPECIFIED = 0 + HIGH = 1 + MEDIUM = 2 + LOW = 3 + NONE = 4 + + +class ResourceValueConfig(proto.Message): + r"""A resource value configuration (RVC) is a mapping + configuration of user's resources to resource values. Used in + Attack path simulations. + + Attributes: + name (str): + Identifier. Name for the resource value + configuration + resource_value (google.cloud.securitycenter_v2.types.ResourceValue): + Resource value level this expression + represents Only required when there is no + Sensitive Data Protection mapping in the request + tag_values (MutableSequence[str]): + Tag values combined with ``AND`` to check against. Values in + the form "tagValues/123" Example: + ``[ "tagValues/123", "tagValues/456", "tagValues/789" ]`` + https://cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing + resource_type (str): + Apply resource_value only to resources that match + resource_type. resource_type will be checked with ``AND`` of + other resources. For example, + "storage.googleapis.com/Bucket" with resource_value "HIGH" + will apply "HIGH" value only to + "storage.googleapis.com/Bucket" resources. + scope (str): + Project or folder to scope this configuration to. For + example, "project/456" would apply this configuration only + to resources in "project/456" scope and will be checked with + ``AND`` of other resources. + resource_labels_selector (MutableMapping[str, str]): + List of resource labels to search for, evaluated with + ``AND``. For example, "resource_labels_selector": {"key": + "value", "env": "prod"} will match resources with labels + "key": "value" ``AND`` "env": "prod" + https://cloud.google.com/resource-manager/docs/creating-managing-labels + description (str): + Description of the resource value + configuration. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp this resource value + configuration was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp this resource value + configuration was last updated. + cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): + Cloud provider this configuration applies to + sensitive_data_protection_mapping (google.cloud.securitycenter_v2.types.ResourceValueConfig.SensitiveDataProtectionMapping): + A mapping of the sensitivity on Sensitive Data Protection + finding to resource values. This mapping can only be used in + combination with a resource_type that is related to + BigQuery, e.g. "bigquery.googleapis.com/Dataset". + """ + + class SensitiveDataProtectionMapping(proto.Message): + r"""Resource value mapping for Sensitive Data Protection findings If any + of these mappings have a resource value that is not unspecified, the + resource_value field will be ignored when reading this + configuration. + + Attributes: + high_sensitivity_mapping (google.cloud.securitycenter_v2.types.ResourceValue): + Resource value mapping for high-sensitivity + Sensitive Data Protection findings + medium_sensitivity_mapping (google.cloud.securitycenter_v2.types.ResourceValue): + Resource value mapping for medium-sensitivity + Sensitive Data Protection findings + """ + + high_sensitivity_mapping: 'ResourceValue' = proto.Field( + proto.ENUM, + number=1, + enum='ResourceValue', + ) + medium_sensitivity_mapping: 'ResourceValue' = proto.Field( + proto.ENUM, + number=2, + enum='ResourceValue', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_value: 'ResourceValue' = proto.Field( + proto.ENUM, + number=2, + enum='ResourceValue', + ) + tag_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + resource_type: str = proto.Field( + proto.STRING, + number=4, + ) + scope: str = proto.Field( + proto.STRING, + number=5, + ) + resource_labels_selector: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + description: str = proto.Field( + proto.STRING, + number=7, + ) + 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, + ) + cloud_provider: resource.CloudProvider = proto.Field( + proto.ENUM, + number=10, + enum=resource.CloudProvider, + ) + sensitive_data_protection_mapping: SensitiveDataProtectionMapping = proto.Field( + proto.MESSAGE, + number=11, + message=SensitiveDataProtectionMapping, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py new file mode 100644 index 000000000000..69a449132422 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v2', + manifest={ + 'SecurityMarks', + }, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + The following list shows some examples: + + - ``organizations/{organization_id}/assets/{asset_id}/securityMarks`` + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` + marks (MutableMapping[str, str]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + canonical_name (str): + The canonical name of the marks. The following list shows + some examples: + + - ``organizations/{organization_id}/assets/{asset_id}/securityMarks`` + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` + + - ``folders/{folder_id}/assets/{asset_id}/securityMarks`` + - + + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks`` + + + ``folders/{folder_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` + + - ``projects/{project_number}/assets/{asset_id}/securityMarks`` + - + + ``projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks`` + + + ``projects/{project_number}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + marks: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.py new file mode 100644 index 000000000000..efa7cfc0b14d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'SecurityPosture', + }, +) + + +class SecurityPosture(proto.Message): + r"""Represents a posture that is deployed on Google Cloud by the + Security Command Center Posture Management service. A posture + contains one or more policy sets. A policy set is a group of + policies that enforce a set of security rules on Google Cloud. + + Attributes: + name (str): + Name of the posture, for example, ``CIS-Posture``. + revision_id (str): + The version of the posture, for example, ``c7cfa2a8``. + posture_deployment_resource (str): + The project, folder, or organization on which the posture is + deployed, for example, ``projects/{project_number}``. + posture_deployment (str): + The name of the posture deployment, for example, + ``organizations/{org_id}/posturedeployments/{posture_deployment_id}``. + changed_policy (str): + The name of the updated policy, for example, + ``projects/{project_id}/policies/{constraint_name}``. + policy_set (str): + The name of the updated policy set, for example, + ``cis-policyset``. + policy (str): + The ID of the updated policy, for example, + ``compute-policy-1``. + policy_drift_details (MutableSequence[google.cloud.securitycenter_v2.types.SecurityPosture.PolicyDriftDetails]): + The details about a change in an updated + policy that violates the deployed posture. + """ + + class PolicyDriftDetails(proto.Message): + r"""The policy field that violates the deployed posture and its + expected and detected values. + + Attributes: + field (str): + The name of the updated field, for example + constraint.implementation.policy_rules[0].enforce + expected_value (str): + The value of this field that was configured in a posture, + for example, ``true`` or + ``allowed_values={"projects/29831892"}``. + detected_value (str): + The detected value that violates the deployed posture, for + example, ``false`` or + ``allowed_values={"projects/22831892"}``. + """ + + field: str = proto.Field( + proto.STRING, + number=1, + ) + expected_value: str = proto.Field( + proto.STRING, + number=2, + ) + detected_value: str = proto.Field( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + ) + posture_deployment_resource: str = proto.Field( + proto.STRING, + number=3, + ) + posture_deployment: str = proto.Field( + proto.STRING, + number=4, + ) + changed_policy: str = proto.Field( + proto.STRING, + number=5, + ) + policy_set: str = proto.Field( + proto.STRING, + number=6, + ) + policy: str = proto.Field( + proto.STRING, + number=7, + ) + policy_drift_details: MutableSequence[PolicyDriftDetails] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=PolicyDriftDetails, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py new file mode 100644 index 000000000000..fdc56c6556a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py @@ -0,0 +1,1932 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v2.types import attack_path +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import resource as gcs_resource +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'BatchCreateResourceValueConfigsRequest', + 'BatchCreateResourceValueConfigsResponse', + 'BulkMuteFindingsRequest', + 'BulkMuteFindingsResponse', + 'CreateBigQueryExportRequest', + 'CreateFindingRequest', + 'CreateMuteConfigRequest', + 'CreateNotificationConfigRequest', + 'CreateResourceValueConfigRequest', + 'CreateSourceRequest', + 'DeleteBigQueryExportRequest', + 'DeleteMuteConfigRequest', + 'DeleteNotificationConfigRequest', + 'DeleteResourceValueConfigRequest', + 'GetBigQueryExportRequest', + 'GetMuteConfigRequest', + 'GetNotificationConfigRequest', + 'GetResourceValueConfigRequest', + 'GetSourceRequest', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAttackPathsRequest', + 'ListAttackPathsResponse', + 'GetSimulationRequest', + 'GetValuedResourceRequest', + 'ListBigQueryExportsRequest', + 'ListBigQueryExportsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListMuteConfigsRequest', + 'ListMuteConfigsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListResourceValueConfigsRequest', + 'ListResourceValueConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListValuedResourcesRequest', + 'ListValuedResourcesResponse', + 'SetFindingStateRequest', + 'SetMuteRequest', + 'UpdateBigQueryExportRequest', + 'UpdateExternalSystemRequest', + 'UpdateFindingRequest', + 'UpdateMuteConfigRequest', + 'UpdateNotificationConfigRequest', + 'UpdateResourceValueConfigRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + }, +) + + +class BatchCreateResourceValueConfigsRequest(proto.Message): + r"""Request message to create multiple resource value configs + + Attributes: + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. The parent field + in the CreateResourceValueConfigRequest messages + must either be empty or match this field. + requests (MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]): + Required. The resource value configs to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence['CreateResourceValueConfigRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='CreateResourceValueConfigRequest', + ) + + +class BatchCreateResourceValueConfigsResponse(proto.Message): + r"""Response message for BatchCreateResourceValueConfigs + + Attributes: + resource_value_configs (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfig]): + The resource value configs created + """ + + resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + + +class BulkMuteFindingsRequest(proto.Message): + r"""Request message for bulk findings update. + + Note: + + 1. If multiple bulk update requests match the same resource, the + order in which they get executed is not defined. + 2. Once a bulk operation is started, there is no way to stop it. + + Attributes: + parent (str): + Required. The parent, at which bulk action needs to be + applied. If no location is specified, findings are updated + in global. The following list shows some examples: + + - ``organizations/[organization_id]`` + - ``organizations/[organization_id]/locations/[location_id]`` + - ``folders/[folder_id]`` + - ``folders/[folder_id]/locations/[location_id]`` + - ``projects/[project_id]`` + - ``projects/[project_id]/locations/[location_id]`` + filter (str): + Expression that identifies findings that should be updated. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + mute_state (google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest.MuteState): + Optional. All findings matching the given filter will have + their mute state set to this value. The default value is + ``MUTED``. Setting this to ``UNDEFINED`` will clear the mute + state on all matching findings. + """ + class MuteState(proto.Enum): + r"""The mute state. + + Values: + MUTE_STATE_UNSPECIFIED (0): + Unused. + MUTED (1): + Matching findings will be muted (default). + UNDEFINED (2): + Matching findings will have their mute state + cleared. + """ + MUTE_STATE_UNSPECIFIED = 0 + MUTED = 1 + UNDEFINED = 2 + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + mute_state: MuteState = proto.Field( + proto.ENUM, + number=3, + enum=MuteState, + ) + + +class BulkMuteFindingsResponse(proto.Message): + r"""The response to a BulkMute request. Contains the LRO + information. + + """ + + +class CreateBigQueryExportRequest(proto.Message): + r"""Request message for creating a BigQuery export. + + Attributes: + parent (str): + Required. The name of the parent resource of the new + BigQuery export. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): + Required. The BigQuery export being created. + big_query_export_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must consist + of only lowercase letters, numbers, and hyphens, + must start with a letter, must end with either a + letter or a number, and must be 63 characters or + less. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + big_query_export: bigquery_export.BigQueryExport = proto.Field( + proto.MESSAGE, + number=2, + message=bigquery_export.BigQueryExport, + ) + big_query_export_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + + Attributes: + parent (str): + Required. Resource name of the new finding's parent. The + following list shows some examples of the format: + + ``organizations/[organization_id]/sources/[source_id]`` + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + alphanumeric and less than or equal to 32 + characters and greater than 0 characters in + length. + finding (google.cloud.securitycenter_v2.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + finding_id: str = proto.Field( + proto.STRING, + number=2, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_finding.Finding, + ) + + +class CreateMuteConfigRequest(proto.Message): + r"""Request message for creating a mute config. + + Attributes: + parent (str): + Required. Resource name of the new mute configs's parent. + Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + mute_config (google.cloud.securitycenter_v2.types.MuteConfig): + Required. The mute config being created. + mute_config_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must consist + of only lowercase letters, numbers, and hyphens, + must start with a letter, must end with either a + letter or a number, and must be 63 characters or + less. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + mute_config: gcs_mute_config.MuteConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_mute_config.MuteConfig, + ) + mute_config_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateNotificationConfigRequest(proto.Message): + r"""Request message for creating a notification config. + + Attributes: + parent (str): + Required. Resource name of the new notification config's + parent. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + config_id (str): + Required. + Unique identifier provided by the client within + the parent scope. It must be between 1 and 128 + characters and contain alphanumeric characters, + underscores, or hyphens only. + notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): + Required. The notification config being + created. The name and the service account will + be ignored as they are both output only fields + on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + config_id: str = proto.Field( + proto.STRING, + number=2, + ) + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_notification_config.NotificationConfig, + ) + + +class CreateResourceValueConfigRequest(proto.Message): + r"""Request message to create single resource value config + + Attributes: + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. + resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): + Required. The resource value config being + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_resource_value_config.ResourceValueConfig, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be ``organizations/[organization_id]``. + source (google.cloud.securitycenter_v2.types.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_source.Source, + ) + + +class DeleteBigQueryExportRequest(proto.Message): + r"""Request message for deleting a BigQuery export. + + Attributes: + name (str): + Required. The name of the BigQuery export to delete. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}/locations/{location}/bigQueryExports/{export_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteMuteConfigRequest(proto.Message): + r"""Request message for deleting a mute config. If no location is + specified, default is global. + + Attributes: + name (str): + Required. Name of the mute config to delete. The following + list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteNotificationConfigRequest(proto.Message): + r"""Request message for deleting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to delete. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_id]`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteResourceValueConfigRequest(proto.Message): + r"""Request message to delete resource value config + + Attributes: + name (str): + Required. Name of the ResourceValueConfig to + delete + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetBigQueryExportRequest(proto.Message): + r"""Request message for retrieving a BigQuery export. + + Attributes: + name (str): + Required. Name of the BigQuery export to retrieve. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}locations/{location}//bigQueryExports/{export_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetMuteConfigRequest(proto.Message): + r"""Request message for retrieving a mute config. If no location + is specified, default is global. + + Attributes: + name (str): + Required. Name of the mute config to retrieve. The following + list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetNotificationConfigRequest(proto.Message): + r"""Request message for getting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to get. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_id]`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetResourceValueConfigRequest(proto.Message): + r"""Request message to get resource value config + + Attributes: + name (str): + Required. Name of the resource value config to retrieve. Its + format is + organizations/{organization}/resourceValueConfigs/{config_id}. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is ``organizations/[organization_id]/source/[source_id]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + + Attributes: + parent (str): + Required. Name of the source to groupBy. If no location is + specified, finding is assumed to be in global. The following + list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To groupBy across all sources provide a source_id of ``-``. + The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/[location_id]`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-/locations/[location_id]`` + - ``projects/{project_id}/sources/-`` + - ``projects/{project_id}/sources/-/locations/[location_id]`` + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - severity: ``=``, ``:`` + + - security_marks.marks: ``=``, ``:`` + + - resource: + + - resource.name: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "parent,resource_name". + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v2.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=struct_pb2.Value, + ) + count: int = proto.Field( + proto.INT64, + number=2, + ) + + +class ListAttackPathsRequest(proto.Message): + r"""Request message for listing the attack paths for a given + simulation or valued resource. + + Attributes: + parent (str): + Required. Name of parent to list attack paths. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + filter (str): + The filter expression that filters the attack path in the + response. Supported fields: + + - ``valued_resources`` supports = + page_token (str): + The value returned by the last ``ListAttackPathsResponse``; + indicates that this is a continuation of a prior + ``ListAttackPaths`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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 ListAttackPathsResponse(proto.Message): + r"""Response message for listing the attack paths for a given + simulation or valued resource. + + Attributes: + attack_paths (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath]): + The attack paths that the attack path + simulation identified. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + attack_paths: MutableSequence[attack_path.AttackPath] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=attack_path.AttackPath, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetSimulationRequest(proto.Message): + r"""Request message for getting simulation. + Simulation name can include "latest" to retrieve the latest + simulation For example, "organizations/123/simulations/latest" + + Attributes: + name (str): + Required. The organization name or simulation name of this + simulation + + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetValuedResourceRequest(proto.Message): + r"""Request message for getting a valued resource. + + Attributes: + name (str): + Required. The name of this valued resource + + Valid format: + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListBigQueryExportsRequest(proto.Message): + r"""Request message for listing BigQuery exports at a given scope + e.g. organization, folder or project. + + Attributes: + parent (str): + Required. The parent, which owns the collection of BigQuery + exports. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + page_size (int): + The maximum number of configs to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous + ``ListBigQueryExports`` call. Provide this to retrieve the + subsequent page. When paginating, all other parameters + provided to ``ListBigQueryExports`` 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 ListBigQueryExportsResponse(proto.Message): + r"""Response message for listing BigQuery exports. + + Attributes: + big_query_exports (MutableSequence[google.cloud.securitycenter_v2.types.BigQueryExport]): + The BigQuery exports from the specified + parent. + 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 + + big_query_exports: MutableSequence[bigquery_export.BigQueryExport] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=bigquery_export.BigQueryExport, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + + Attributes: + parent (str): + Required. Name of the source the findings belong to. If no + location is specified, the default is global. The following + list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To list across all sources provide a source_id of ``-``. The + following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/{location_id}`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-locations/{location_id}`` + - ``projects/{projects_id}/sources/-`` + - ``projects/{projects_id}/sources/-/locations/{location_id}`` + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - severity: ``=``, ``:`` + + - security_marks.marks: ``=``, ``:`` + + - resource: + + - resource.name: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + - resource.folders.resource_folder: ``=``, ``:`` + - resource.display_name: ``=``, ``:`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: "name,parent". The + default sorting order is ascending. To specify descending + order for a field, a suffix " desc" should be appended to + the field name. For example: "name desc,parent". Redundant + space characters in the syntax are insignificant. "name + desc,parent" and " name desc , parent " are equivalent. + + The following fields are supported: name parent state + category resource_name event_time security_marks.marks + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the Finding fields to + be listed in the response. An empty field mask + will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=9, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + + Attributes: + list_findings_results (MutableSequence[google.cloud.securitycenter_v2.types.ListFindingsResponse.ListFindingsResult]): + Findings matching the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + class ListFindingsResult(proto.Message): + r"""Result containing the Finding. + + Attributes: + finding (google.cloud.securitycenter_v2.types.Finding): + Finding matching the search request. + resource (google.cloud.securitycenter_v2.types.ListFindingsResponse.ListFindingsResult.Resource): + Output only. Resource that is associated with + this finding. + """ + + class Resource(proto.Message): + r"""Information related to the Google Cloud resource that is + associated with this finding. + + 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): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + display_name (str): + The human readable name of the resource. + type_ (str): + The full resource type of the resource. + cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): + Indicates which cloud provider the finding is + from. + service (str): + The service or resource provider associated + with the resource. + location (str): + The region or location of the service (if + applicable). + gcp_metadata (google.cloud.securitycenter_v2.types.GcpMetadata): + The GCP metadata associated with the finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + aws_metadata (google.cloud.securitycenter_v2.types.AwsMetadata): + The AWS metadata associated with the finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + azure_metadata (google.cloud.securitycenter_v2.types.AzureMetadata): + The Azure metadata associated with the + finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + resource_path (google.cloud.securitycenter_v2.types.ResourcePath): + Provides the path to the resource within the + resource hierarchy. + resource_path_string (str): + A string representation of the resource path. For Google + Cloud, it has the format of + ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` + where there can be any number of folders. For AWS, it has + the format of + ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` + where there can be any number of organizational units. For + Azure, it has the format of + ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` + where there can be any number of management groups. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + type_: str = proto.Field( + proto.STRING, + number=3, + ) + cloud_provider: gcs_resource.CloudProvider = proto.Field( + proto.ENUM, + number=4, + enum=gcs_resource.CloudProvider, + ) + service: str = proto.Field( + proto.STRING, + number=5, + ) + location: str = proto.Field( + proto.STRING, + number=6, + ) + gcp_metadata: gcs_resource.GcpMetadata = proto.Field( + proto.MESSAGE, + number=7, + oneof='cloud_provider_metadata', + message=gcs_resource.GcpMetadata, + ) + aws_metadata: gcs_resource.AwsMetadata = proto.Field( + proto.MESSAGE, + number=8, + oneof='cloud_provider_metadata', + message=gcs_resource.AwsMetadata, + ) + azure_metadata: gcs_resource.AzureMetadata = proto.Field( + proto.MESSAGE, + number=9, + oneof='cloud_provider_metadata', + message=gcs_resource.AzureMetadata, + ) + resource_path: gcs_resource.ResourcePath = proto.Field( + proto.MESSAGE, + number=10, + message=gcs_resource.ResourcePath, + ) + resource_path_string: str = proto.Field( + proto.STRING, + number=11, + ) + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + resource: 'ListFindingsResponse.ListFindingsResult.Resource' = proto.Field( + proto.MESSAGE, + number=3, + message='ListFindingsResponse.ListFindingsResult.Resource', + ) + + @property + def raw_page(self): + return self + + list_findings_results: MutableSequence[ListFindingsResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListFindingsResult, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListMuteConfigsRequest(proto.Message): + r"""Request message for listing mute configs at a given scope + e.g. organization, folder or project. If no location is + specified, default is global. + + Attributes: + parent (str): + Required. The parent, which owns the collection of mute + configs. Its format is + ``organizations/[organization_id]", "folders/[folder_id]``, + ``projects/[project_id]``, + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, + ``projects/[project_id]/locations/[location_id]``. + page_size (int): + The maximum number of configs to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListMuteConfigs`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListMuteConfigs`` 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 ListMuteConfigsResponse(proto.Message): + r"""Response message for listing mute configs. + + Attributes: + mute_configs (MutableSequence[google.cloud.securitycenter_v2.types.MuteConfig]): + The mute configs from the specified parent. + 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 + + mute_configs: MutableSequence[gcs_mute_config.MuteConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_mute_config.MuteConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListNotificationConfigsRequest(proto.Message): + r"""Request message for listing notification configs. + + Attributes: + parent (str): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + page_token (str): + The value returned by the last + ``ListNotificationConfigsResponse``; indicates that this is + a continuation of a prior ``ListNotificationConfigs`` call, + and that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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 ListNotificationConfigsResponse(proto.Message): + r"""Response message for listing notification configs. + + Attributes: + notification_configs (MutableSequence[google.cloud.securitycenter_v2.types.NotificationConfig]): + Notification configs belonging to the + requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + notification_configs: MutableSequence[gcs_notification_config.NotificationConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListResourceValueConfigsRequest(proto.Message): + r"""Request message to list resource value configs of a parent + + Attributes: + parent (str): + Required. The parent, which owns the collection of resource + value configs. Its format is + ``organizations/[organization_id]`` + page_size (int): + The maximum number of configs to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous + ``ListResourceValueConfigs`` call. Provide this to retrieve + the subsequent page. + + When paginating, all other parameters provided to + ``ListResourceValueConfigs`` must match the call that + provided the page token. + + page_size can be specified, and the new page_size 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, + ) + + +class ListResourceValueConfigsResponse(proto.Message): + r"""Response message to list resource value configs + + Attributes: + resource_value_configs (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfig]): + The resource value configs from the specified + parent. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is empty, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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=7, + ) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v2.types.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListValuedResourcesRequest(proto.Message): + r"""Request message for listing the valued resources for a given + simulation. + + Attributes: + parent (str): + Required. Name of parent to list exposed resources. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + filter (str): + The filter expression that filters the valued resources in + the response. Supported fields: + + - ``resource_value`` supports = + - ``resource_type`` supports = + page_token (str): + The value returned by the last + ``ListValuedResourcesResponse``; indicates that this is a + continuation of a prior ``ListValuedResources`` call, and + that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + order_by (str): + Optional. The fields by which to order the valued resources + response. + + Supported fields: + + - ``exposed_score`` + + - ``resource_value`` + + - ``resource_type`` + + Values should be a comma separated list of fields. For + example: ``exposed_score,resource_value``. + + The default sorting order is descending. To specify + ascending or descending order for a field, append a " ASC" + or a " DESC" suffix, respectively; for example: + ``exposed_score DESC``. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListValuedResourcesResponse(proto.Message): + r"""Response message for listing the valued resources for a given + simulation. + + Attributes: + valued_resources (MutableSequence[google.cloud.securitycenter_v2.types.ValuedResource]): + The valued resources that the attack path + simulation identified. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The estimated total number of results + matching the query. + """ + + @property + def raw_page(self): + return self + + valued_resources: MutableSequence[valued_resource.ValuedResource] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=valued_resource.ValuedResource, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + + Attributes: + name (str): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + state (google.cloud.securitycenter_v2.types.Finding.State): + Required. The desired State of the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: gcs_finding.Finding.State = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.State, + ) + + +class SetMuteRequest(proto.Message): + r"""Request message for updating a finding's mute status. + + Attributes: + name (str): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + mute (google.cloud.securitycenter_v2.types.Finding.Mute): + Required. The desired state of the Mute. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + mute: gcs_finding.Finding.Mute = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.Mute, + ) + + +class UpdateBigQueryExportRequest(proto.Message): + r"""Request message for updating a BigQuery export. + + Attributes: + big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): + Required. The BigQuery export being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + big_query_export: bigquery_export.BigQueryExport = proto.Field( + proto.MESSAGE, + number=1, + message=bigquery_export.BigQueryExport, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateExternalSystemRequest(proto.Message): + r"""Request message for updating a ExternalSystem resource. + + Attributes: + external_system (google.cloud.securitycenter_v2.types.ExternalSystem): + Required. The external system resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + external system resource. + If empty all mutable fields will be updated. + """ + + external_system: gcs_external_system.ExternalSystem = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_external_system.ExternalSystem, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + + Attributes: + finding (google.cloud.securitycenter_v2.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must be alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing source_properties. + Individual source_properties can be added/updated by using + "source_properties." in the field mask. + """ + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateMuteConfigRequest(proto.Message): + r"""Request message for updating a mute config. + + Attributes: + mute_config (google.cloud.securitycenter_v2.types.MuteConfig): + Required. The mute config being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + mute_config: gcs_mute_config.MuteConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_mute_config.MuteConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateNotificationConfigRequest(proto.Message): + r"""Request message for updating a notification config. + + Attributes: + notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): + Required. The notification config to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + notification config. + If empty all mutable fields will be updated. + """ + + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateResourceValueConfigRequest(proto.Message): + r"""Request message to update resource value config + + Attributes: + resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): + Required. The resource value config being + updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If empty all mutable + fields will be updated. + + To update nested fields, include the top level field in the + mask For example, to update gcp_metadata.resource_type, + include the "gcp_metadata" field mask + """ + + resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): + Required. The security marks resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If empty + or set to "marks", all marks will be replaced. Individual + marks can be updated using "marks.". + """ + + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_marks.SecurityMarks, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (google.cloud.securitycenter_v2.types.Source): + Required. The source resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the source + resource. + If empty all mutable fields will be updated. + """ + + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + 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-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py new file mode 100644 index 000000000000..5c64646490da --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v2.types import resource +from google.cloud.securitycenter_v2.types import valued_resource +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Simulation', + }, +) + + +class Simulation(proto.Message): + r"""Attack path simulation + + Attributes: + name (str): + Full resource name of the Simulation: + ``organizations/123/simulations/456`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time simulation was created + resource_value_configs_metadata (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfigMetadata]): + Resource value configurations' metadata used + in this simulation. Maximum of 100. + cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): + Indicates which cloud provider was used in + this simulation. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + resource_value_configs_metadata: MutableSequence[valued_resource.ResourceValueConfigMetadata] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=valued_resource.ResourceValueConfigMetadata, + ) + cloud_provider: resource.CloudProvider = proto.Field( + proto.ENUM, + number=4, + enum=resource.CloudProvider, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.py new file mode 100644 index 000000000000..006e16a02f4a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Source', + }, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, and other tools. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and outdated or + insecure libraries.". + canonical_name (str): + The canonical name of the finding source. It's either + "organizations/{organization_id}/sources/{source_id}", + "folders/{folder_id}/sources/{source_id}", or + "projects/{project_number}/sources/{source_id}", depending + on the closest CRM ancestor of the resource associated with + the finding. + """ + + 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, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.py new file mode 100644 index 000000000000..e70d9aa2e281 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'ToxicCombination', + }, +) + + +class ToxicCombination(proto.Message): + r"""Contains details about a group of security issues that, when + the issues occur together, represent a greater risk than when + the issues occur independently. A group of such issues is + referred to as a toxic combination. + + Attributes: + attack_exposure_score (float): + The `Attack exposure + score `__ + of this toxic combination. The score is a measure of how + much this toxic combination exposes one or more high-value + resources to potential attack. + related_findings (MutableSequence[str]): + List of resource names of findings associated with this + toxic combination. For example, + ``organizations/123/sources/456/findings/789``. + """ + + attack_exposure_score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + related_findings: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.py new file mode 100644 index 000000000000..ed481ba587b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'ValuedResource', + 'ResourceValueConfigMetadata', + }, +) + + +class ValuedResource(proto.Message): + r"""A resource that is determined to have value to a user's + system + + Attributes: + name (str): + Valued resource name, for example, e.g.: + ``organizations/123/simulations/456/valuedResources/789`` + resource (str): + The `full resource + name `__ + of the valued resource. + resource_type (str): + The `resource + type `__ + of the valued resource. + display_name (str): + Human-readable name of the valued resource. + resource_value (google.cloud.securitycenter_v2.types.ValuedResource.ResourceValue): + How valuable this resource is. + exposed_score (float): + Exposed score for this valued resource. A + value of 0 means no exposure was detected + exposure. + resource_value_configs_used (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfigMetadata]): + List of resource value configurations' + metadata used to determine the value of this + resource. Maximum of 100. + """ + class ResourceValue(proto.Enum): + r"""How valuable the resource is. + + Values: + RESOURCE_VALUE_UNSPECIFIED (0): + The resource value isn't specified. + RESOURCE_VALUE_LOW (1): + This is a low-value resource. + RESOURCE_VALUE_MEDIUM (2): + This is a medium-value resource. + RESOURCE_VALUE_HIGH (3): + This is a high-value resource. + """ + RESOURCE_VALUE_UNSPECIFIED = 0 + RESOURCE_VALUE_LOW = 1 + RESOURCE_VALUE_MEDIUM = 2 + RESOURCE_VALUE_HIGH = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource: str = proto.Field( + proto.STRING, + number=2, + ) + resource_type: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + resource_value: ResourceValue = proto.Field( + proto.ENUM, + number=5, + enum=ResourceValue, + ) + exposed_score: float = proto.Field( + proto.DOUBLE, + number=6, + ) + resource_value_configs_used: MutableSequence['ResourceValueConfigMetadata'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='ResourceValueConfigMetadata', + ) + + +class ResourceValueConfigMetadata(proto.Message): + r"""Metadata about a ResourceValueConfig. For example, id and + name. + + Attributes: + name (str): + Resource value config name + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.py new file mode 100644 index 000000000000..79c7e06db637 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.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. +# +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.securitycenter.v2', + manifest={ + 'Vulnerability', + 'Cve', + 'Reference', + 'Cvssv3', + 'Package', + 'SecurityBulletin', + }, +) + + +class Vulnerability(proto.Message): + r"""Refers to common vulnerability fields e.g. cve, cvss, cwe + etc. + + Attributes: + cve (google.cloud.securitycenter_v2.types.Cve): + CVE stands for Common Vulnerabilities and + Exposures (https://cve.mitre.org/about/) + offending_package (google.cloud.securitycenter_v2.types.Package): + The offending package is relevant to the + finding. + fixed_package (google.cloud.securitycenter_v2.types.Package): + The fixed package is relevant to the finding. + security_bulletin (google.cloud.securitycenter_v2.types.SecurityBulletin): + The security bulletin is relevant to this + finding. + """ + + cve: 'Cve' = proto.Field( + proto.MESSAGE, + number=1, + message='Cve', + ) + offending_package: 'Package' = proto.Field( + proto.MESSAGE, + number=2, + message='Package', + ) + fixed_package: 'Package' = proto.Field( + proto.MESSAGE, + number=3, + message='Package', + ) + security_bulletin: 'SecurityBulletin' = proto.Field( + proto.MESSAGE, + number=4, + message='SecurityBulletin', + ) + + +class Cve(proto.Message): + r"""CVE stands for Common Vulnerabilities and Exposures. Information + from the `CVE + record `__ that + describes this vulnerability. + + Attributes: + id (str): + The unique identifier for the vulnerability. + e.g. CVE-2021-34527 + references (MutableSequence[google.cloud.securitycenter_v2.types.Reference]): + Additional information about the CVE. + e.g. + https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527 + cvssv3 (google.cloud.securitycenter_v2.types.Cvssv3): + Describe Common Vulnerability Scoring System + specified at + https://www.first.org/cvss/v3.1/specification-document + upstream_fix_available (bool): + Whether upstream fix is available for the + CVE. + impact (google.cloud.securitycenter_v2.types.Cve.RiskRating): + The potential impact of the vulnerability if + it was to be exploited. + exploitation_activity (google.cloud.securitycenter_v2.types.Cve.ExploitationActivity): + The exploitation activity of the + vulnerability in the wild. + observed_in_the_wild (bool): + Whether or not the vulnerability has been + observed in the wild. + zero_day (bool): + Whether or not the vulnerability was zero day + when the finding was published. + exploit_release_date (google.protobuf.timestamp_pb2.Timestamp): + Date the first publicly available exploit or + PoC was released. + """ + class RiskRating(proto.Enum): + r"""The possible values of impact of the vulnerability if it was + to be exploited. + + Values: + RISK_RATING_UNSPECIFIED (0): + Invalid or empty value. + LOW (1): + Exploitation would have little to no security + impact. + MEDIUM (2): + Exploitation would enable attackers to + perform activities, or could allow attackers to + have a direct impact, but would require + additional steps. + HIGH (3): + Exploitation would enable attackers to have a + notable direct impact without needing to + overcome any major mitigating factors. + CRITICAL (4): + Exploitation would fundamentally undermine + the security of affected systems, enable actors + to perform significant attacks with minimal + effort, with little to no mitigating factors to + overcome. + """ + RISK_RATING_UNSPECIFIED = 0 + LOW = 1 + MEDIUM = 2 + HIGH = 3 + CRITICAL = 4 + + class ExploitationActivity(proto.Enum): + r"""The possible values of exploitation activity of the + vulnerability in the wild. + + Values: + EXPLOITATION_ACTIVITY_UNSPECIFIED (0): + Invalid or empty value. + WIDE (1): + Exploitation has been reported or confirmed + to widely occur. + CONFIRMED (2): + Limited reported or confirmed exploitation + activities. + AVAILABLE (3): + Exploit is publicly available. + ANTICIPATED (4): + No known exploitation activity, but has a + high potential for exploitation. + NO_KNOWN (5): + No known exploitation activity. + """ + EXPLOITATION_ACTIVITY_UNSPECIFIED = 0 + WIDE = 1 + CONFIRMED = 2 + AVAILABLE = 3 + ANTICIPATED = 4 + NO_KNOWN = 5 + + id: str = proto.Field( + proto.STRING, + number=1, + ) + references: MutableSequence['Reference'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Reference', + ) + cvssv3: 'Cvssv3' = proto.Field( + proto.MESSAGE, + number=3, + message='Cvssv3', + ) + upstream_fix_available: bool = proto.Field( + proto.BOOL, + number=4, + ) + impact: RiskRating = proto.Field( + proto.ENUM, + number=5, + enum=RiskRating, + ) + exploitation_activity: ExploitationActivity = proto.Field( + proto.ENUM, + number=6, + enum=ExploitationActivity, + ) + observed_in_the_wild: bool = proto.Field( + proto.BOOL, + number=7, + ) + zero_day: bool = proto.Field( + proto.BOOL, + number=8, + ) + exploit_release_date: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + + +class Reference(proto.Message): + r"""Additional Links + + Attributes: + source (str): + Source of the reference e.g. NVD + uri (str): + Uri for the mentioned source e.g. + https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527. + """ + + source: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Cvssv3(proto.Message): + r"""Common Vulnerability Scoring System version 3. + + Attributes: + base_score (float): + The base score is a function of the base + metric scores. + attack_vector (google.cloud.securitycenter_v2.types.Cvssv3.AttackVector): + Base Metrics + Represents the intrinsic characteristics of a + vulnerability that are constant over time and + across user environments. This metric reflects + the context by which vulnerability exploitation + is possible. + attack_complexity (google.cloud.securitycenter_v2.types.Cvssv3.AttackComplexity): + This metric describes the conditions beyond + the attacker's control that must exist in order + to exploit the vulnerability. + privileges_required (google.cloud.securitycenter_v2.types.Cvssv3.PrivilegesRequired): + This metric describes the level of privileges + an attacker must possess before successfully + exploiting the vulnerability. + user_interaction (google.cloud.securitycenter_v2.types.Cvssv3.UserInteraction): + This metric captures the requirement for a + human user, other than the attacker, to + participate in the successful compromise of the + vulnerable component. + scope (google.cloud.securitycenter_v2.types.Cvssv3.Scope): + The Scope metric captures whether a + vulnerability in one vulnerable component + impacts resources in components beyond its + security scope. + confidentiality_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): + This metric measures the impact to the + confidentiality of the information resources + managed by a software component due to a + successfully exploited vulnerability. + integrity_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): + This metric measures the impact to integrity + of a successfully exploited vulnerability. + availability_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): + This metric measures the impact to the + availability of the impacted component resulting + from a successfully exploited vulnerability. + """ + class AttackVector(proto.Enum): + r"""This metric reflects the context by which vulnerability + exploitation is possible. + + Values: + ATTACK_VECTOR_UNSPECIFIED (0): + Invalid value. + ATTACK_VECTOR_NETWORK (1): + The vulnerable component is bound to the + network stack and the set of possible attackers + extends beyond the other options listed below, + up to and including the entire Internet. + ATTACK_VECTOR_ADJACENT (2): + The vulnerable component is bound to the + network stack, but the attack is limited at the + protocol level to a logically adjacent topology. + ATTACK_VECTOR_LOCAL (3): + The vulnerable component is not bound to the + network stack and the attacker's path is via + read/write/execute capabilities. + ATTACK_VECTOR_PHYSICAL (4): + The attack requires the attacker to + physically touch or manipulate the vulnerable + component. + """ + ATTACK_VECTOR_UNSPECIFIED = 0 + ATTACK_VECTOR_NETWORK = 1 + ATTACK_VECTOR_ADJACENT = 2 + ATTACK_VECTOR_LOCAL = 3 + ATTACK_VECTOR_PHYSICAL = 4 + + class AttackComplexity(proto.Enum): + r"""This metric describes the conditions beyond the attacker's + control that must exist in order to exploit the vulnerability. + + Values: + ATTACK_COMPLEXITY_UNSPECIFIED (0): + Invalid value. + ATTACK_COMPLEXITY_LOW (1): + Specialized access conditions or extenuating + circumstances do not exist. An attacker can + expect repeatable success when attacking the + vulnerable component. + ATTACK_COMPLEXITY_HIGH (2): + A successful attack depends on conditions + beyond the attacker's control. That is, a + successful attack cannot be accomplished at + will, but requires the attacker to invest in + some measurable amount of effort in preparation + or execution against the vulnerable component + before a successful attack can be expected. + """ + ATTACK_COMPLEXITY_UNSPECIFIED = 0 + ATTACK_COMPLEXITY_LOW = 1 + ATTACK_COMPLEXITY_HIGH = 2 + + class PrivilegesRequired(proto.Enum): + r"""This metric describes the level of privileges an attacker + must possess before successfully exploiting the vulnerability. + + Values: + PRIVILEGES_REQUIRED_UNSPECIFIED (0): + Invalid value. + PRIVILEGES_REQUIRED_NONE (1): + The attacker is unauthorized prior to attack, + and therefore does not require any access to + settings or files of the vulnerable system to + carry out an attack. + PRIVILEGES_REQUIRED_LOW (2): + The attacker requires privileges that provide + basic user capabilities that could normally + affect only settings and files owned by a user. + Alternatively, an attacker with Low privileges + has the ability to access only non-sensitive + resources. + PRIVILEGES_REQUIRED_HIGH (3): + The attacker requires privileges that provide + significant (e.g., administrative) control over + the vulnerable component allowing access to + component-wide settings and files. + """ + PRIVILEGES_REQUIRED_UNSPECIFIED = 0 + PRIVILEGES_REQUIRED_NONE = 1 + PRIVILEGES_REQUIRED_LOW = 2 + PRIVILEGES_REQUIRED_HIGH = 3 + + class UserInteraction(proto.Enum): + r"""This metric captures the requirement for a human user, other + than the attacker, to participate in the successful compromise + of the vulnerable component. + + Values: + USER_INTERACTION_UNSPECIFIED (0): + Invalid value. + USER_INTERACTION_NONE (1): + The vulnerable system can be exploited + without interaction from any user. + USER_INTERACTION_REQUIRED (2): + Successful exploitation of this vulnerability + requires a user to take some action before the + vulnerability can be exploited. + """ + USER_INTERACTION_UNSPECIFIED = 0 + USER_INTERACTION_NONE = 1 + USER_INTERACTION_REQUIRED = 2 + + class Scope(proto.Enum): + r"""The Scope metric captures whether a vulnerability in one + vulnerable component impacts resources in components beyond its + security scope. + + Values: + SCOPE_UNSPECIFIED (0): + Invalid value. + SCOPE_UNCHANGED (1): + An exploited vulnerability can only affect + resources managed by the same security + authority. + SCOPE_CHANGED (2): + An exploited vulnerability can affect + resources beyond the security scope managed by + the security authority of the vulnerable + component. + """ + SCOPE_UNSPECIFIED = 0 + SCOPE_UNCHANGED = 1 + SCOPE_CHANGED = 2 + + class Impact(proto.Enum): + r"""The Impact metrics capture the effects of a successfully + exploited vulnerability on the component that suffers the worst + outcome that is most directly and predictably associated with + the attack. + + Values: + IMPACT_UNSPECIFIED (0): + Invalid value. + IMPACT_HIGH (1): + High impact. + IMPACT_LOW (2): + Low impact. + IMPACT_NONE (3): + No impact. + """ + IMPACT_UNSPECIFIED = 0 + IMPACT_HIGH = 1 + IMPACT_LOW = 2 + IMPACT_NONE = 3 + + base_score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + attack_vector: AttackVector = proto.Field( + proto.ENUM, + number=2, + enum=AttackVector, + ) + attack_complexity: AttackComplexity = proto.Field( + proto.ENUM, + number=3, + enum=AttackComplexity, + ) + privileges_required: PrivilegesRequired = proto.Field( + proto.ENUM, + number=4, + enum=PrivilegesRequired, + ) + user_interaction: UserInteraction = proto.Field( + proto.ENUM, + number=5, + enum=UserInteraction, + ) + scope: Scope = proto.Field( + proto.ENUM, + number=6, + enum=Scope, + ) + confidentiality_impact: Impact = proto.Field( + proto.ENUM, + number=7, + enum=Impact, + ) + integrity_impact: Impact = proto.Field( + proto.ENUM, + number=8, + enum=Impact, + ) + availability_impact: Impact = proto.Field( + proto.ENUM, + number=9, + enum=Impact, + ) + + +class Package(proto.Message): + r"""Package is a generic definition of a package. + + Attributes: + package_name (str): + The name of the package where the + vulnerability was detected. + cpe_uri (str): + The CPE URI where the vulnerability was + detected. + package_type (str): + Type of package, for example, os, maven, or + go. + package_version (str): + The version of the package. + """ + + package_name: str = proto.Field( + proto.STRING, + number=1, + ) + cpe_uri: str = proto.Field( + proto.STRING, + number=2, + ) + package_type: str = proto.Field( + proto.STRING, + number=3, + ) + package_version: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SecurityBulletin(proto.Message): + r"""SecurityBulletin are notifications of vulnerabilities of + Google products. + + Attributes: + bulletin_id (str): + ID of the bulletin corresponding to the + vulnerability. + submission_time (google.protobuf.timestamp_pb2.Timestamp): + Submission time of this Security Bulletin. + suggested_upgrade_version (str): + This represents a version that the cluster + receiving this notification should be upgraded + to, based on its current version. For example, + 1.15.0 + """ + + bulletin_id: str = proto.Field( + proto.STRING, + number=1, + ) + submission_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + suggested_upgrade_version: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v2/noxfile.py new file mode 100644 index 000000000000..cd78e7c39a06 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-securitycenter' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +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"): + 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/securitycenter_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"): + 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", + "grpcio", + "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/securitycenter_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( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): + # Ignore release of mypy 1.11.0 which may have a regression + 'mypy!=1.11.0', + '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-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py new file mode 100644 index 000000000000..e74e57a22631 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + requests = securitycenter_v2.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + + request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py new file mode 100644 index 000000000000..d6c2ad8428ff --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + requests = securitycenter_v2.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + + request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py new file mode 100644 index 000000000000..4b2fd03c3f02 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_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 BulkMuteFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py new file mode 100644 index 000000000000..743d1302b400 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_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 BulkMuteFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py new file mode 100644 index 000000000000..1698ad6adc92 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_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 CreateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_create_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = await client.create_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py new file mode 100644 index 000000000000..becab1857b3c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_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 CreateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_create_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = client.create_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py new file mode 100644 index 000000000000..3a2c089e9019 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_create_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py new file mode 100644 index 000000000000..4294f4ffd397 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_create_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py new file mode 100644 index 000000000000..c858b59a6586 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_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 CreateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_create_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = await client.create_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py new file mode 100644 index 000000000000..a0de28b38bbd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_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 CreateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_create_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = client.create_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py new file mode 100644 index 000000000000..ae681f4e8f3e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_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 CreateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_create_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py new file mode 100644 index 000000000000..0bf75d6458fd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_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 CreateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_create_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py new file mode 100644 index 000000000000..9afb50b6e83e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_create_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py new file mode 100644 index 000000000000..af9c2b763cc6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_create_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py new file mode 100644 index 000000000000..4aac72fa5605 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + await client.delete_big_query_export(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py new file mode 100644 index 000000000000..b278bde5e5ae --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + client.delete_big_query_export(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py new file mode 100644 index 000000000000..10ceee02e146 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_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 DeleteMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_delete_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_mute_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py new file mode 100644 index 000000000000..a051c7c17741 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_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 DeleteMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_delete_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_mute_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py new file mode 100644 index 000000000000..fceb0255c2bd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_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 DeleteNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py new file mode 100644 index 000000000000..906f2a39092c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_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 DeleteNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_delete_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py new file mode 100644 index 000000000000..191842b98c8f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_resource_value_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py new file mode 100644 index 000000000000..e8aac97d4f8d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_resource_value_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py new file mode 100644 index 000000000000..14de594a963c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_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 GetBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py new file mode 100644 index 000000000000..a8d4416456ab --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_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 GetBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = client.get_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py new file mode 100644 index 000000000000..04061abcf9a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py new file mode 100644 index 000000000000..4d9d6d45b825 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py new file mode 100644 index 000000000000..348376a0b9b4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_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 GetMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py new file mode 100644 index 000000000000..84adb2a92f59 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_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 GetMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py new file mode 100644 index 000000000000..73885369a61e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_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 GetNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py new file mode 100644 index 000000000000..84d892dabf5f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_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 GetNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py new file mode 100644 index 000000000000..4076aa39fbc6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_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 GetResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py new file mode 100644 index 000000000000..814ba5a717d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_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 GetResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py new file mode 100644 index 000000000000..4cf61313cb96 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_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 GetSimulation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetSimulation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_simulation(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_simulation(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetSimulation_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py new file mode 100644 index 000000000000..572655cf48c9 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_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 GetSimulation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetSimulation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_simulation(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = client.get_simulation(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetSimulation_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py new file mode 100644 index 000000000000..685b7f0cc423 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py new file mode 100644 index 000000000000..a33bef8b910d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py new file mode 100644 index 000000000000..b0601f503c25 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_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 GetValuedResource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetValuedResource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_valued_resource(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_valued_resource(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetValuedResource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py new file mode 100644 index 000000000000..ed7d7630288d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_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 GetValuedResource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetValuedResource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_valued_resource(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_valued_resource(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetValuedResource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py new file mode 100644 index 000000000000..d829f16c868e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GroupFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_group_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py new file mode 100644 index 000000000000..d7e8c0a21523 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GroupFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_group_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py new file mode 100644 index 000000000000..ed648fdea30d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_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 ListAttackPaths +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListAttackPaths_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_attack_paths(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListAttackPaths_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py new file mode 100644 index 000000000000..bdecd1972ff1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_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 ListAttackPaths +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListAttackPaths_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_attack_paths(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListAttackPaths_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py new file mode 100644 index 000000000000..405bc21b0f37 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_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 ListBigQueryExports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py new file mode 100644 index 000000000000..ccb98f95fa3c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_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 ListBigQueryExports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py new file mode 100644 index 000000000000..bb6c9e3c9bc9 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_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 securitycenter_v2 + + +async def sample_list_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py new file mode 100644 index 000000000000..190548636c6f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_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 securitycenter_v2 + + +def sample_list_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py new file mode 100644 index 000000000000..50ec2b1fd631 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_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 ListMuteConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_mute_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py new file mode 100644 index 000000000000..d28a0e6adb61 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_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 ListMuteConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_mute_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py new file mode 100644 index 000000000000..7b12a639c763 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_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 ListNotificationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py new file mode 100644 index 000000000000..d1cffc2d7793 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_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 ListNotificationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_notification_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py new file mode 100644 index 000000000000..9f8a6124f4d6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_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 ListResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py new file mode 100644 index 000000000000..cfc3651b5540 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_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 ListResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py new file mode 100644 index 000000000000..447f27ccaa16 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListSources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_sources(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py new file mode 100644 index 000000000000..9447d7eb91ee --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListSources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_sources(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py new file mode 100644 index 000000000000..1c17d84f91cb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_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 ListValuedResources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListValuedResources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_valued_resources(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListValuedResources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py new file mode 100644 index 000000000000..616675828d82 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_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 ListValuedResources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListValuedResources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_valued_resources(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListValuedResources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py new file mode 100644 index 000000000000..905eb5d7db22 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetFindingState_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_set_finding_state(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py new file mode 100644 index 000000000000..339e22bde563 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetFindingState_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_set_finding_state(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py new file mode 100644 index 000000000000..2c74d459d83f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py new file mode 100644 index 000000000000..4e5ef3b13cbf --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py new file mode 100644 index 000000000000..fa80c37c66ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_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 SetMute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetMute_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_set_mute(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = await client.set_mute(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetMute_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py new file mode 100644 index 000000000000..9355527a6bac --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_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 SetMute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetMute_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_set_mute(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = client.set_mute(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetMute_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py new file mode 100644 index 000000000000..3ccd4f4848bb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py new file mode 100644 index 000000000000..6df1fda9cf90 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py new file mode 100644 index 000000000000..365c17bd2756 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_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 UpdateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateBigQueryExportRequest( + ) + + # Make the request + response = await client.update_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py new file mode 100644 index 000000000000..18b99ec2462e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_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 UpdateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateBigQueryExportRequest( + ) + + # Make the request + response = client.update_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py new file mode 100644 index 000000000000..179da29467bb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_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 UpdateExternalSystem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_external_system(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateExternalSystemRequest( + ) + + # Make the request + response = await client.update_external_system(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py new file mode 100644 index 000000000000..6a68970514cc --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_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 UpdateExternalSystem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_external_system(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateExternalSystemRequest( + ) + + # Make the request + response = client.update_external_system(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py new file mode 100644 index 000000000000..245e358b0eea --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py new file mode 100644 index 000000000000..512e315aa049 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py new file mode 100644 index 000000000000..7796c39566e2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_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 UpdateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = await client.update_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py new file mode 100644 index 000000000000..920f6986fb3b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_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 UpdateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = client.update_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py new file mode 100644 index 000000000000..bed9621bb2ea --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_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 UpdateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py new file mode 100644 index 000000000000..ed5516437b4d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_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 UpdateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py new file mode 100644 index 000000000000..0ecd6b7d2fd5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_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 UpdateResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateResourceValueConfigRequest( + ) + + # Make the request + response = await client.update_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py new file mode 100644 index 000000000000..2508104c843d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_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 UpdateResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateResourceValueConfigRequest( + ) + + # Make the request + response = client.update_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py new file mode 100644 index 000000000000..faf2900ce05c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_security_marks(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py new file mode 100644 index 000000000000..9843735d4ad6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_security_marks(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py new file mode 100644 index 000000000000..39f5bd6e19c2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py new file mode 100644 index 000000000000..f138fd97e1ec --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json new file mode 100644 index 000000000000..3ebbbfe28b50 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json @@ -0,0 +1,6607 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.securitycenter.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-cloud-securitycenter", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.batch_create_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BatchCreateResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BatchCreateResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse", + "shortName": "batch_create_resource_value_configs" + }, + "description": "Sample for BatchCreateResourceValueConfigs", + "file": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.batch_create_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BatchCreateResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BatchCreateResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse", + "shortName": "batch_create_resource_value_configs" + }, + "description": "Sample for BatchCreateResourceValueConfigs", + "file": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.bulk_mute_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BulkMuteFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BulkMuteFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "bulk_mute_findings" + }, + "description": "Sample for BulkMuteFindings", + "file": "securitycenter_v2_generated_security_center_bulk_mute_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v2_generated_security_center_bulk_mute_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.bulk_mute_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BulkMuteFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BulkMuteFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "bulk_mute_findings" + }, + "description": "Sample for BulkMuteFindings", + "file": "securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v2.types.BigQueryExport" + }, + { + "name": "big_query_export_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.BigQueryExport", + "shortName": "create_big_query_export" + }, + "description": "Sample for CreateBigQueryExport", + "file": "securitycenter_v2_generated_security_center_create_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v2_generated_security_center_create_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v2.types.BigQueryExport" + }, + { + "name": "big_query_export_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.BigQueryExport", + "shortName": "create_big_query_export" + }, + "description": "Sample for CreateBigQueryExport", + "file": "securitycenter_v2_generated_security_center_create_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v2_generated_security_center_create_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v2.types.Finding" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v2_generated_security_center_create_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateFinding_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": "securitycenter_v2_generated_security_center_create_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v2.types.Finding" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v2_generated_security_center_create_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateFinding_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": "securitycenter_v2_generated_security_center_create_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateMuteConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v2.types.MuteConfig" + }, + { + "name": "mute_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.cloud.securitycenter_v2.types.MuteConfig", + "shortName": "create_mute_config" + }, + "description": "Sample for CreateMuteConfig", + "file": "securitycenter_v2_generated_security_center_create_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v2_generated_security_center_create_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateMuteConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v2.types.MuteConfig" + }, + { + "name": "mute_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.cloud.securitycenter_v2.types.MuteConfig", + "shortName": "create_mute_config" + }, + "description": "Sample for CreateMuteConfig", + "file": "securitycenter_v2_generated_security_center_create_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v2_generated_security_center_create_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v2.types.NotificationConfig" + }, + { + "name": "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.cloud.securitycenter_v2.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v2_generated_security_center_create_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v2_generated_security_center_create_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v2.types.NotificationConfig" + }, + { + "name": "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.cloud.securitycenter_v2.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v2_generated_security_center_create_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v2_generated_security_center_create_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v2.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v2_generated_security_center_create_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_create_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v2.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v2_generated_security_center_create_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_create_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest" + }, + { + "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_big_query_export" + }, + "description": "Sample for DeleteBigQueryExport", + "file": "securitycenter_v2_generated_security_center_delete_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v2_generated_security_center_delete_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest" + }, + { + "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_big_query_export" + }, + "description": "Sample for DeleteBigQueryExport", + "file": "securitycenter_v2_generated_security_center_delete_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v2_generated_security_center_delete_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest" + }, + { + "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_mute_config" + }, + "description": "Sample for DeleteMuteConfig", + "file": "securitycenter_v2_generated_security_center_delete_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v2_generated_security_center_delete_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest" + }, + { + "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_mute_config" + }, + "description": "Sample for DeleteMuteConfig", + "file": "securitycenter_v2_generated_security_center_delete_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v2_generated_security_center_delete_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest" + }, + { + "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_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v2_generated_security_center_delete_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v2_generated_security_center_delete_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest" + }, + { + "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_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v2_generated_security_center_delete_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v2_generated_security_center_delete_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest" + }, + { + "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_resource_value_config" + }, + "description": "Sample for DeleteResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_delete_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v2_generated_security_center_delete_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest" + }, + { + "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_resource_value_config" + }, + "description": "Sample for DeleteResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetBigQueryExportRequest" + }, + { + "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.securitycenter_v2.types.BigQueryExport", + "shortName": "get_big_query_export" + }, + "description": "Sample for GetBigQueryExport", + "file": "securitycenter_v2_generated_security_center_get_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetBigQueryExportRequest" + }, + { + "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.securitycenter_v2.types.BigQueryExport", + "shortName": "get_big_query_export" + }, + "description": "Sample for GetBigQueryExport", + "file": "securitycenter_v2_generated_security_center_get_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v2_generated_security_center_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v2_generated_security_center_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetMuteConfigRequest" + }, + { + "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.securitycenter_v2.types.MuteConfig", + "shortName": "get_mute_config" + }, + "description": "Sample for GetMuteConfig", + "file": "securitycenter_v2_generated_security_center_get_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetMuteConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetMuteConfigRequest" + }, + { + "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.securitycenter_v2.types.MuteConfig", + "shortName": "get_mute_config" + }, + "description": "Sample for GetMuteConfig", + "file": "securitycenter_v2_generated_security_center_get_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetMuteConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v2.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v2_generated_security_center_get_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v2.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v2_generated_security_center_get_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest" + }, + { + "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.securitycenter_v2.types.ResourceValueConfig", + "shortName": "get_resource_value_config" + }, + "description": "Sample for GetResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_get_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest" + }, + { + "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.securitycenter_v2.types.ResourceValueConfig", + "shortName": "get_resource_value_config" + }, + "description": "Sample for GetResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_get_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_simulation", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSimulation", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSimulation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetSimulationRequest" + }, + { + "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.securitycenter_v2.types.Simulation", + "shortName": "get_simulation" + }, + "description": "Sample for GetSimulation", + "file": "securitycenter_v2_generated_security_center_get_simulation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSimulation_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_simulation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_simulation", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSimulation", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSimulation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetSimulationRequest" + }, + { + "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.securitycenter_v2.types.Simulation", + "shortName": "get_simulation" + }, + "description": "Sample for GetSimulation", + "file": "securitycenter_v2_generated_security_center_get_simulation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSimulation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_simulation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetSourceRequest" + }, + { + "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.securitycenter_v2.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v2_generated_security_center_get_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetSourceRequest" + }, + { + "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.securitycenter_v2.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v2_generated_security_center_get_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_valued_resource", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetValuedResource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetValuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetValuedResourceRequest" + }, + { + "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.securitycenter_v2.types.ValuedResource", + "shortName": "get_valued_resource" + }, + "description": "Sample for GetValuedResource", + "file": "securitycenter_v2_generated_security_center_get_valued_resource_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetValuedResource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_valued_resource_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_valued_resource", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetValuedResource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetValuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetValuedResourceRequest" + }, + { + "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.securitycenter_v2.types.ValuedResource", + "shortName": "get_valued_resource" + }, + "description": "Sample for GetValuedResource", + "file": "securitycenter_v2_generated_security_center_get_valued_resource_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetValuedResource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_valued_resource_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsAsyncPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v2_generated_security_center_group_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GroupFindings_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": "securitycenter_v2_generated_security_center_group_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v2_generated_security_center_group_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GroupFindings_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": "securitycenter_v2_generated_security_center_group_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_attack_paths", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListAttackPaths", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAttackPaths" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListAttackPathsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListAttackPathsAsyncPager", + "shortName": "list_attack_paths" + }, + "description": "Sample for ListAttackPaths", + "file": "securitycenter_v2_generated_security_center_list_attack_paths_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v2_generated_security_center_list_attack_paths_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_attack_paths", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListAttackPaths", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAttackPaths" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListAttackPathsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListAttackPathsPager", + "shortName": "list_attack_paths" + }, + "description": "Sample for ListAttackPaths", + "file": "securitycenter_v2_generated_security_center_list_attack_paths_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v2_generated_security_center_list_attack_paths_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_big_query_exports", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListBigQueryExports", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListBigQueryExports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsAsyncPager", + "shortName": "list_big_query_exports" + }, + "description": "Sample for ListBigQueryExports", + "file": "securitycenter_v2_generated_security_center_list_big_query_exports_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v2_generated_security_center_list_big_query_exports_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_big_query_exports", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListBigQueryExports", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListBigQueryExports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsPager", + "shortName": "list_big_query_exports" + }, + "description": "Sample for ListBigQueryExports", + "file": "securitycenter_v2_generated_security_center_list_big_query_exports_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v2_generated_security_center_list_big_query_exports_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListFindingsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListFindingsAsyncPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v2_generated_security_center_list_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListFindings_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": "securitycenter_v2_generated_security_center_list_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListFindingsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListFindingsPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v2_generated_security_center_list_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListFindings_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": "securitycenter_v2_generated_security_center_list_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_mute_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListMuteConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListMuteConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListMuteConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsAsyncPager", + "shortName": "list_mute_configs" + }, + "description": "Sample for ListMuteConfigs", + "file": "securitycenter_v2_generated_security_center_list_mute_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v2_generated_security_center_list_mute_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_mute_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListMuteConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListMuteConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListMuteConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsPager", + "shortName": "list_mute_configs" + }, + "description": "Sample for ListMuteConfigs", + "file": "securitycenter_v2_generated_security_center_list_mute_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v2_generated_security_center_list_mute_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsAsyncPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v2_generated_security_center_list_notification_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v2_generated_security_center_list_notification_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v2_generated_security_center_list_notification_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v2_generated_security_center_list_notification_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsAsyncPager", + "shortName": "list_resource_value_configs" + }, + "description": "Sample for ListResourceValueConfigs", + "file": "securitycenter_v2_generated_security_center_list_resource_value_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v2_generated_security_center_list_resource_value_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsPager", + "shortName": "list_resource_value_configs" + }, + "description": "Sample for ListResourceValueConfigs", + "file": "securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListSourcesRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListSourcesAsyncPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v2_generated_security_center_list_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListSources_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": "securitycenter_v2_generated_security_center_list_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListSourcesRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListSourcesPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v2_generated_security_center_list_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListSources_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": "securitycenter_v2_generated_security_center_list_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_valued_resources", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListValuedResources", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListValuedResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListValuedResourcesRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesAsyncPager", + "shortName": "list_valued_resources" + }, + "description": "Sample for ListValuedResources", + "file": "securitycenter_v2_generated_security_center_list_valued_resources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v2_generated_security_center_list_valued_resources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_valued_resources", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListValuedResources", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListValuedResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListValuedResourcesRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesPager", + "shortName": "list_valued_resources" + }, + "description": "Sample for ListValuedResources", + "file": "securitycenter_v2_generated_security_center_list_valued_resources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v2_generated_security_center_list_valued_resources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v2.types.Finding.State" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v2_generated_security_center_set_finding_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetFindingState_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": "securitycenter_v2_generated_security_center_set_finding_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v2.types.Finding.State" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v2_generated_security_center_set_finding_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetFindingState_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": "securitycenter_v2_generated_security_center_set_finding_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v2_generated_security_center_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v2_generated_security_center_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_mute", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetMute", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetMute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.SetMuteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "mute", + "type": "google.cloud.securitycenter_v2.types.Finding.Mute" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "set_mute" + }, + "description": "Sample for SetMute", + "file": "securitycenter_v2_generated_security_center_set_mute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetMute_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": "securitycenter_v2_generated_security_center_set_mute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_mute", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetMute", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetMute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.SetMuteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "mute", + "type": "google.cloud.securitycenter_v2.types.Finding.Mute" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "set_mute" + }, + "description": "Sample for SetMute", + "file": "securitycenter_v2_generated_security_center_set_mute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetMute_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": "securitycenter_v2_generated_security_center_set_mute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v2_generated_security_center_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v2_generated_security_center_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v2.types.BigQueryExport" + }, + { + "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.securitycenter_v2.types.BigQueryExport", + "shortName": "update_big_query_export" + }, + "description": "Sample for UpdateBigQueryExport", + "file": "securitycenter_v2_generated_security_center_update_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v2_generated_security_center_update_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v2.types.BigQueryExport" + }, + { + "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.securitycenter_v2.types.BigQueryExport", + "shortName": "update_big_query_export" + }, + "description": "Sample for UpdateBigQueryExport", + "file": "securitycenter_v2_generated_security_center_update_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v2_generated_security_center_update_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_external_system", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateExternalSystem", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateExternalSystem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest" + }, + { + "name": "external_system", + "type": "google.cloud.securitycenter_v2.types.ExternalSystem" + }, + { + "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.securitycenter_v2.types.ExternalSystem", + "shortName": "update_external_system" + }, + "description": "Sample for UpdateExternalSystem", + "file": "securitycenter_v2_generated_security_center_update_external_system_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v2_generated_security_center_update_external_system_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_external_system", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateExternalSystem", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateExternalSystem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest" + }, + { + "name": "external_system", + "type": "google.cloud.securitycenter_v2.types.ExternalSystem" + }, + { + "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.securitycenter_v2.types.ExternalSystem", + "shortName": "update_external_system" + }, + "description": "Sample for UpdateExternalSystem", + "file": "securitycenter_v2_generated_security_center_update_external_system_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v2_generated_security_center_update_external_system_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v2.types.Finding" + }, + { + "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.securitycenter_v2.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v2_generated_security_center_update_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v2_generated_security_center_update_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v2.types.Finding" + }, + { + "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.securitycenter_v2.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v2_generated_security_center_update_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v2_generated_security_center_update_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v2.types.MuteConfig" + }, + { + "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.securitycenter_v2.types.MuteConfig", + "shortName": "update_mute_config" + }, + "description": "Sample for UpdateMuteConfig", + "file": "securitycenter_v2_generated_security_center_update_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v2_generated_security_center_update_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v2.types.MuteConfig" + }, + { + "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.securitycenter_v2.types.MuteConfig", + "shortName": "update_mute_config" + }, + "description": "Sample for UpdateMuteConfig", + "file": "securitycenter_v2_generated_security_center_update_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v2_generated_security_center_update_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v2.types.NotificationConfig" + }, + { + "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.securitycenter_v2.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v2_generated_security_center_update_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v2_generated_security_center_update_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v2.types.NotificationConfig" + }, + { + "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.securitycenter_v2.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v2_generated_security_center_update_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v2_generated_security_center_update_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest" + }, + { + "name": "resource_value_config", + "type": "google.cloud.securitycenter_v2.types.ResourceValueConfig" + }, + { + "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.securitycenter_v2.types.ResourceValueConfig", + "shortName": "update_resource_value_config" + }, + "description": "Sample for UpdateResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_update_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v2_generated_security_center_update_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest" + }, + { + "name": "resource_value_config", + "type": "google.cloud.securitycenter_v2.types.ResourceValueConfig" + }, + { + "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.securitycenter_v2.types.ResourceValueConfig", + "shortName": "update_resource_value_config" + }, + "description": "Sample for UpdateResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_update_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v2_generated_security_center_update_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v2.types.SecurityMarks" + }, + { + "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.securitycenter_v2.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v2_generated_security_center_update_security_marks_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v2_generated_security_center_update_security_marks_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v2.types.SecurityMarks" + }, + { + "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.securitycenter_v2.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v2_generated_security_center_update_security_marks_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v2_generated_security_center_update_security_marks_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v2.types.Source" + }, + { + "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.securitycenter_v2.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v2_generated_security_center_update_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSource_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": "securitycenter_v2_generated_security_center_update_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v2.types.Source" + }, + { + "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.securitycenter_v2.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v2_generated_security_center_update_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSource_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": "securitycenter_v2_generated_security_center_update_source_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py new file mode 100644 index 000000000000..f95da838422b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py @@ -0,0 +1,215 @@ +#! /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 securitycenterCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_create_resource_value_configs': ('parent', 'requests', ), + 'bulk_mute_findings': ('parent', 'filter', 'mute_state', ), + 'create_big_query_export': ('parent', 'big_query_export', 'big_query_export_id', ), + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_mute_config': ('parent', 'mute_config', 'mute_config_id', ), + 'create_notification_config': ('parent', 'config_id', 'notification_config', ), + 'create_source': ('parent', 'source', ), + 'delete_big_query_export': ('name', ), + 'delete_mute_config': ('name', ), + 'delete_notification_config': ('name', ), + 'delete_resource_value_config': ('name', ), + 'get_big_query_export': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_mute_config': ('name', ), + 'get_notification_config': ('name', ), + 'get_resource_value_config': ('name', ), + 'get_simulation': ('name', ), + 'get_source': ('name', ), + 'get_valued_resource': ('name', ), + 'group_findings': ('parent', 'group_by', 'filter', 'page_token', 'page_size', ), + 'list_attack_paths': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_big_query_exports': ('parent', 'page_size', 'page_token', ), + 'list_findings': ('parent', 'filter', 'order_by', 'field_mask', 'page_token', 'page_size', ), + 'list_mute_configs': ('parent', 'page_size', 'page_token', ), + 'list_notification_configs': ('parent', 'page_token', 'page_size', ), + 'list_resource_value_configs': ('parent', 'page_size', 'page_token', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'list_valued_resources': ('parent', 'filter', 'page_token', 'page_size', 'order_by', ), + 'set_finding_state': ('name', 'state', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'set_mute': ('name', 'mute', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_big_query_export': ('big_query_export', 'update_mask', ), + 'update_external_system': ('external_system', 'update_mask', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_mute_config': ('mute_config', 'update_mask', ), + 'update_notification_config': ('notification_config', 'update_mask', ), + 'update_resource_value_config': ('resource_value_config', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', ), + 'update_source': ('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=securitycenterCallTransformer(), +): + """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 securitycenter 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-securitycenter/v2/setup.py b/owl-bot-staging/google-cloud-securitycenter/v2/setup.py new file mode 100644 index 000000000000..c4538ec101f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/setup.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. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-securitycenter' + + +description = "Google Cloud Securitycenter API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/securitycenter/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", + "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", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_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-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py new file mode 100644 index 000000000000..6104ead93daa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py @@ -0,0 +1,31716 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +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 + +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.securitycenter_v2.services.security_center import SecurityCenterAsyncClient +from google.cloud.securitycenter_v2.services.security_center import SecurityCenterClient +from google.cloud.securitycenter_v2.services.security_center import pagers +from google.cloud.securitycenter_v2.services.security_center import transports +from google.cloud.securitycenter_v2.types import access +from google.cloud.securitycenter_v2.types import application +from google.cloud.securitycenter_v2.types import attack_exposure +from google.cloud.securitycenter_v2.types import attack_path +from google.cloud.securitycenter_v2.types import backup_disaster_recovery +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import cloud_armor +from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile +from google.cloud.securitycenter_v2.types import cloud_dlp_inspection +from google.cloud.securitycenter_v2.types import compliance +from google.cloud.securitycenter_v2.types import connection +from google.cloud.securitycenter_v2.types import contact_details +from google.cloud.securitycenter_v2.types import container +from google.cloud.securitycenter_v2.types import database +from google.cloud.securitycenter_v2.types import exfiltration +from google.cloud.securitycenter_v2.types import external_system +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import file +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import group_membership +from google.cloud.securitycenter_v2.types import iam_binding +from google.cloud.securitycenter_v2.types import indicator +from google.cloud.securitycenter_v2.types import kernel_rootkit +from google.cloud.securitycenter_v2.types import kubernetes +from google.cloud.securitycenter_v2.types import label +from google.cloud.securitycenter_v2.types import load_balancer +from google.cloud.securitycenter_v2.types import log_entry +from google.cloud.securitycenter_v2.types import mitre_attack +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notebook +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import org_policy +from google.cloud.securitycenter_v2.types import process +from google.cloud.securitycenter_v2.types import resource +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import security_posture +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import toxic_combination +from google.cloud.securitycenter_v2.types import valued_resource +from google.cloud.securitycenter_v2.types import vulnerability +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 duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None + assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SecurityCenterClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SecurityCenterGrpcTransport, "grpc"), + (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + 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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + available_transports = [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterRestTransport, + ] + assert transport in available_transports + + transport = SecurityCenterClient.get_transport_class("grpc") + assert transport == transports.SecurityCenterGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, 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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), +]) +def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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_security_center_client_client_options_from_dict(): + with mock.patch('google.cloud.securitycenter_v2.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.BatchCreateResourceValueConfigsRequest, + dict, +]) +def test_batch_create_resource_value_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse( + ) + response = client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) + + +def test_batch_create_resource_value_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_create_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() + + +def test_batch_create_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.BatchCreateResourceValueConfigsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_create_resource_value_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest( + parent='parent_value', + ) + +def test_batch_create_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc + request = {} + client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_resource_value_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_batch_create_resource_value_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( + )) + response = await client.batch_create_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() + +@pytest.mark.asyncio +async def test_batch_create_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.batch_create_resource_value_configs] = mock_object + + request = {} + await client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.batch_create_resource_value_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( + )) + response = await client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) + + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_async_from_dict(): + await test_batch_create_resource_value_configs_async(request_type=dict) + + +def test_batch_create_resource_value_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + client.batch_create_resource_value_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_batch_create_resource_value_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) + await client.batch_create_resource_value_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_batch_create_resource_value_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_resource_value_configs( + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(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 + arg = args[0].requests + mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] + assert arg == mock_val + + +def test_batch_create_resource_value_configs_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], + ) + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_resource_value_configs( + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(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 + arg = args[0].requests + mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.BulkMuteFindingsRequest, + dict, +]) +def test_bulk_mute_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BulkMuteFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_bulk_mute_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.bulk_mute_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest() + + +def test_bulk_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.BulkMuteFindingsRequest( + parent='parent_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.bulk_mute_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest( + parent='parent_value', + filter='filter_value', + ) + +def test_bulk_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc + request = {} + client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest() + +@pytest.mark.asyncio +async def test_bulk_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.bulk_mute_findings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.bulk_mute_findings] = mock_object + + request = {} + await client.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.bulk_mute_findings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_bulk_mute_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BulkMuteFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BulkMuteFindingsRequest() + 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_bulk_mute_findings_async_from_dict(): + await test_bulk_mute_findings_async(request_type=dict) + + +def test_bulk_mute_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BulkMuteFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.bulk_mute_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_bulk_mute_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BulkMuteFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.bulk_mute_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_bulk_mute_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings( + 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_bulk_mute_findings_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_bulk_mute_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings( + 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_bulk_mute_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateBigQueryExportRequest, + dict, +]) +def test_create_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + response = client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +def test_create_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest() + + +def test_create_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateBigQueryExportRequest( + parent='parent_value', + big_query_export_id='big_query_export_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest( + parent='parent_value', + big_query_export_id='big_query_export_id_value', + ) + +def test_create_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + request = {} + client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_big_query_export(request) + + # Establish that a new wrapper 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_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.create_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_create_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_big_query_export] = mock_object + + request = {} + await client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +@pytest.mark.asyncio +async def test_create_big_query_export_async_from_dict(): + await test_create_big_query_export_async(request_type=dict) + + +def test_create_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateBigQueryExportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value = bigquery_export.BigQueryExport() + client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateBigQueryExportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + await client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_big_query_export( + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_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].big_query_export + mock_val = bigquery_export.BigQueryExport(name='name_value') + assert arg == mock_val + arg = args[0].big_query_export_id + mock_val = 'big_query_export_id_value' + assert arg == mock_val + + +def test_create_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_id_value', + ) + +@pytest.mark.asyncio +async def test_create_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_big_query_export( + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_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].big_query_export + mock_val = bigquery_export.BigQueryExport(name='name_value') + assert arg == mock_val + arg = args[0].big_query_export_id + mock_val = 'big_query_export_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_create_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.create_finding] = mock_rpc + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object + + request = {} + await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_create_finding_async_from_dict(): + await test_create_finding_async(request_type=dict) + + +def test_create_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_finding( + parent='parent_value', + finding=gcs_finding.Finding(name='name_value'), + finding_id='finding_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].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + + +def test_create_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding=gcs_finding.Finding(name='name_value'), + finding_id='finding_id_value', + ) + +@pytest.mark.asyncio +async def test_create_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_finding( + parent='parent_value', + finding=gcs_finding.Finding(name='name_value'), + finding_id='finding_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].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding=gcs_finding.Finding(name='name_value'), + finding_id='finding_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateMuteConfigRequest, + dict, +]) +def test_create_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + response = client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_create_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest() + + +def test_create_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateMuteConfigRequest( + parent='parent_value', + mute_config_id='mute_config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest( + parent='parent_value', + mute_config_id='mute_config_id_value', + ) + +def test_create_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + request = {} + client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.create_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest() + +@pytest.mark.asyncio +async def test_create_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_mute_config] = mock_object + + request = {} + await client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +@pytest.mark.asyncio +async def test_create_mute_config_async_from_dict(): + await test_create_mute_config_async(request_type=dict) + +def test_create_mute_config_routing_parameters(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateMuteConfigRequest(**{"parent": "projects/sample1/locations/sample2"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.create_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateMuteConfigRequest(**{"parent": "organizations/sample1/locations/sample2"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.create_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateMuteConfigRequest(**{"parent": "folders/sample1/locations/sample2"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.create_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + + +def test_create_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_mute_config( + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_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].mute_config + mock_val = gcs_mute_config.MuteConfig(name='name_value') + assert arg == mock_val + arg = args[0].mute_config_id + mock_val = 'mute_config_id_value' + assert arg == mock_val + + +def test_create_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_mute_config( + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_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].mute_config + mock_val = gcs_mute_config.MuteConfig(name='name_value') + assert arg == mock_val + arg = args[0].mute_config_id + mock_val = 'mute_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateNotificationConfigRequest, + dict, +]) +def test_create_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_create_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateNotificationConfigRequest( + parent='parent_value', + config_id='config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest( + parent='parent_value', + config_id='config_id_value', + ) + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_create_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_notification_config] = mock_object + + request = {} + await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_create_notification_config_async_from_dict(): + await test_create_notification_config_async(request_type=dict) + + +def test_create_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.create_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.create_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_notification_config( + parent='parent_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + config_id='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].notification_config + mock_val = gcs_notification_config.NotificationConfig(name='name_value') + assert arg == mock_val + arg = args[0].config_id + mock_val = 'config_id_value' + assert arg == mock_val + + +def test_create_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + config_id='config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_notification_config( + parent='parent_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + config_id='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].notification_config + mock_val = gcs_notification_config.NotificationConfig(name='name_value') + assert arg == mock_val + arg = args[0].config_id + mock_val = 'config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_notification_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + config_id='config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_create_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object + + request = {} + await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_create_source_async_from_dict(): + await test_create_source_async(request_type=dict) + + +def test_create_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.create_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.create_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + + +def test_create_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteBigQueryExportRequest, + dict, +]) +def test_delete_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() + + +def test_delete_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteBigQueryExportRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest( + name='name_value', + ) + +def test_delete_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + request = {} + client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_big_query_export(request) + + # Establish that a new wrapper 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_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_delete_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_big_query_export] = mock_object + + request = {} + await client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteBigQueryExportRequest() + 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_big_query_export_async_from_dict(): + await test_delete_big_query_export_async(request_type=dict) + + +def test_delete_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value = None + client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__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_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__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_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteMuteConfigRequest, + dict, +]) +def test_delete_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest() + + +def test_delete_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteMuteConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest( + name='name_value', + ) + +def test_delete_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + request = {} + client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest() + +@pytest.mark.asyncio +async def test_delete_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_mute_config] = mock_object + + request = {} + await client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteMuteConfigRequest() + 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_mute_config_async_from_dict(): + await test_delete_mute_config_async(request_type=dict) + +def test_delete_mute_config_routing_parameters(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteMuteConfigRequest(**{"name": "projects/sample1/locations/sample2/muteConfigs/sample3"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value = None + client.delete_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteMuteConfigRequest(**{"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value = None + client.delete_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteMuteConfigRequest(**{"name": "folders/sample1/locations/sample2/muteConfigs/sample3"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value = None + client.delete_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + + +def test_delete_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, +]) +def test_delete_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteNotificationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest( + name='name_value', + ) + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_delete_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_notification_config] = mock_object + + request = {} + await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteNotificationConfigRequest() + 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_config_async_from_dict(): + await test_delete_notification_config_async(request_type=dict) + + +def test_delete_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = None + client.delete_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_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_notification_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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_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_notification_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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_notification_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteResourceValueConfigRequest, + dict, +]) +def test_delete_resource_value_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() + + +def test_delete_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteResourceValueConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_resource_value_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest( + name='name_value', + ) + +def test_delete_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + request = {} + client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_resource_value_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_resource_value_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() + +@pytest.mark.asyncio +async def test_delete_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_resource_value_config] = mock_object + + request = {} + await client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_resource_value_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteResourceValueConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteResourceValueConfigRequest() + 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_resource_value_config_async_from_dict(): + await test_delete_resource_value_config_async(request_type=dict) + + +def test_delete_resource_value_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value = None + client.delete_resource_value_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_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_resource_value_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_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetBigQueryExportRequest, + dict, +]) +def test_get_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + response = client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +def test_get_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest() + + +def test_get_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetBigQueryExportRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest( + name='name_value', + ) + +def test_get_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc + request = {} + client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.get_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_get_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_big_query_export] = mock_object + + request = {} + await client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +@pytest.mark.asyncio +async def test_get_big_query_export_async_from_dict(): + await test_get_big_query_export_async(request_type=dict) + + +def test_get_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value = bigquery_export.BigQueryExport() + client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + await client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSimulationRequest, + dict, +]) +def test_get_simulation(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + response = client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSimulationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == 'name_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +def test_get_simulation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_simulation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest() + + +def test_get_simulation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSimulationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_simulation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest( + name='name_value', + ) + +def test_get_simulation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_simulation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc + request = {} + client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_simulation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_simulation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_simulation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest() + +@pytest.mark.asyncio +async def test_get_simulation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_simulation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_simulation] = mock_object + + request = {} + await client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_simulation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_simulation_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSimulationRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSimulationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == 'name_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +@pytest.mark.asyncio +async def test_get_simulation_async_from_dict(): + await test_get_simulation_async(request_type=dict) + + +def test_get_simulation_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSimulationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value = simulation.Simulation() + client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_simulation_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSimulationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) + await client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_simulation_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_simulation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_simulation_flattened_error(): + client = SecurityCenterClient( + credentials=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_simulation( + securitycenter_service.GetSimulationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_simulation_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_simulation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_simulation_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_simulation( + securitycenter_service.GetSimulationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetValuedResourceRequest, + dict, +]) +def test_get_valued_resource(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + ) + response = client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetValuedResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == 'name_value' + assert response.resource == 'resource_value' + assert response.resource_type == 'resource_type_value' + assert response.display_name == 'display_name_value' + assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + + +def test_get_valued_resource_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_valued_resource() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest() + + +def test_get_valued_resource_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetValuedResourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_valued_resource(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest( + name='name_value', + ) + +def test_get_valued_resource_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_valued_resource in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc + request = {} + client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_valued_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_valued_resource_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + )) + response = await client.get_valued_resource() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest() + +@pytest.mark.asyncio +async def test_get_valued_resource_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_valued_resource in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_valued_resource] = mock_object + + request = {} + await client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_valued_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_valued_resource_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetValuedResourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + )) + response = await client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetValuedResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == 'name_value' + assert response.resource == 'resource_value' + assert response.resource_type == 'resource_type_value' + assert response.display_name == 'display_name_value' + assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + + +@pytest.mark.asyncio +async def test_get_valued_resource_async_from_dict(): + await test_get_valued_resource_async(request_type=dict) + + +def test_get_valued_resource_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetValuedResourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value = valued_resource.ValuedResource() + client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_valued_resource_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetValuedResourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) + await client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_valued_resource_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_valued_resource( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_valued_resource_flattened_error(): + client = SecurityCenterClient( + credentials=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_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_valued_resource_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_valued_resource( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_valued_resource_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.GetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest( + resource='resource_value', + ) + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object + + request = {} + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetMuteConfigRequest, + dict, +]) +def test_get_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + ) + response = client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_get_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest() + + +def test_get_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetMuteConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest( + name='name_value', + ) + +def test_get_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_mute_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_mute_config] = mock_rpc + request = {} + client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.get_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest() + +@pytest.mark.asyncio +async def test_get_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_mute_config] = mock_object + + request = {} + await client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC + + +@pytest.mark.asyncio +async def test_get_mute_config_async_from_dict(): + await test_get_mute_config_async(request_type=dict) + +def test_get_mute_config_routing_parameters(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetMuteConfigRequest(**{"name": "projects/sample1/locations/sample2/muteConfigs/sample3"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value = mute_config.MuteConfig() + client.get_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetMuteConfigRequest(**{"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value = mute_config.MuteConfig() + client.get_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetMuteConfigRequest(**{"name": "folders/sample1/locations/sample2/muteConfigs/sample3"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value = mute_config.MuteConfig() + client.get_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + + +def test_get_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_mute_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_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_mute_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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetNotificationConfigRequest, + dict, +]) +def test_get_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_get_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetNotificationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest( + name='name_value', + ) + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_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_notification_config] = mock_rpc + request = {} + client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_get_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_notification_config] = mock_object + + request = {} + await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_get_notification_config_async_from_dict(): + await test_get_notification_config_async(request_type=dict) + + +def test_get_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = notification_config.NotificationConfig() + client.get_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + await client.get_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_notification_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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_notification_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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_notification_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetResourceValueConfigRequest, + dict, +]) +def test_get_resource_value_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + response = client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +def test_get_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest() + + +def test_get_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetResourceValueConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_resource_value_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest( + name='name_value', + ) + +def test_get_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc + request = {} + client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_resource_value_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_resource_value_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest() + +@pytest.mark.asyncio +async def test_get_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_resource_value_config] = mock_object + + request = {} + await client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_resource_value_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetResourceValueConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +@pytest.mark.asyncio +async def test_get_resource_value_config_async_from_dict(): + await test_get_resource_value_config_async(request_type=dict) + + +def test_get_resource_value_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value = resource_value_config.ResourceValueConfig() + client.get_resource_value_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_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) + await client.get_resource_value_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_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_resource_value_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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_resource_value_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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_get_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest( + name='name_value', + ) + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + +@pytest.mark.asyncio +async def test_get_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object + + request = {} + await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_get_source_async_from_dict(): + await test_get_source_async(request_type=dict) + + +def test_get_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = source.Source() + client.get_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + await client.get_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_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_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + +@pytest.mark.asyncio +async def test_group_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_findings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object + + request = {} + await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_findings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_findings_async_from_dict(): + await test_group_findings_async(request_type=dict) + + +def test_group_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = securitycenter_service.GroupFindingsResponse() + client.group_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_group_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + await client.group_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_group_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that the 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + + +def test_group_findings_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + +@pytest.mark.asyncio +async def test_group_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_group_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_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, securitycenter_service.GroupResult) + for i in results) +def test_group_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_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_group_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_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", [ + securitycenter_service.ListAttackPathsRequest, + dict, +]) +def test_list_attack_paths(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAttackPathsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_attack_paths_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_attack_paths() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest() + + +def test_list_attack_paths_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListAttackPathsRequest( + 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_attack_paths), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_attack_paths(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_attack_paths_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_attack_paths in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc + request = {} + client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_attack_paths(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_attack_paths_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_attack_paths() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest() + +@pytest.mark.asyncio +async def test_list_attack_paths_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_attack_paths in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_attack_paths] = mock_object + + request = {} + await client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_attack_paths(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_attack_paths_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAttackPathsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAttackPathsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_attack_paths_async_from_dict(): + await test_list_attack_paths_async(request_type=dict) + + +def test_list_attack_paths_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAttackPathsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + call.return_value = securitycenter_service.ListAttackPathsResponse() + client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_attack_paths_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAttackPathsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) + await client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_attack_paths_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_attack_paths( + 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_attack_paths_flattened_error(): + client = SecurityCenterClient( + credentials=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_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_attack_paths_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_attack_paths( + 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_attack_paths_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent='parent_value', + ) + + +def test_list_attack_paths_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_attack_paths(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, attack_path.AttackPath) + for i in results) +def test_list_attack_paths_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + pages = list(client.list_attack_paths(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_attack_paths_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_attack_paths(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, attack_path.AttackPath) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_attack_paths_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + 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_attack_paths(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", [ + securitycenter_service.ListBigQueryExportsRequest, + dict, +]) +def test_list_big_query_exports(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListBigQueryExportsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_big_query_exports_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_big_query_exports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest() + + +def test_list_big_query_exports_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListBigQueryExportsRequest( + 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_big_query_exports), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_big_query_exports(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_big_query_exports_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_big_query_exports in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc + request = {} + client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_big_query_exports(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_big_query_exports_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_big_query_exports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest() + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_exports in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_big_query_exports] = mock_object + + request = {} + await client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_big_query_exports(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_big_query_exports_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListBigQueryExportsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListBigQueryExportsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_from_dict(): + await test_list_big_query_exports_async(request_type=dict) + + +def test_list_big_query_exports_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListBigQueryExportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_exports_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListBigQueryExportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) + await client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_exports_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_big_query_exports( + 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_big_query_exports_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_big_query_exports_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_big_query_exports( + 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_big_query_exports_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent='parent_value', + ) + + +def test_list_big_query_exports_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_big_query_exports(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, bigquery_export.BigQueryExport) + for i in results) +def test_list_big_query_exports_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + pages = list(client.list_big_query_exports(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_big_query_exports_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_big_query_exports(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, bigquery_export.BigQueryExport) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + 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_big_query_exports(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", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +def test_list_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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] == securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + +@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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object + + request = {} + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +@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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( + 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 = securitycenter_service.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', + ) + + # Establish that the 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_findings_flattened_error(): + client = SecurityCenterClient( + credentials=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( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_findings_flattened_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.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', + ) + + # Establish that 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_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_findings( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + + +def test_list_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in results) +def test_list_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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 = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_findings_async_pages(): + client = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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", [ + securitycenter_service.ListMuteConfigsRequest, + dict, +]) +def test_list_mute_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListMuteConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_mute_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_mute_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest() + + +def test_list_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListMuteConfigsRequest( + 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_mute_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_mute_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_mute_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_mute_configs] = mock_rpc + request = {} + client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_mute_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_mute_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_mute_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest() + +@pytest.mark.asyncio +async def test_list_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_mute_configs] = mock_object + + request = {} + await client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_mute_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_mute_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListMuteConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListMuteConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_mute_configs_async_from_dict(): + await test_list_mute_configs_async(request_type=dict) + +def test_list_mute_configs_routing_parameters(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListMuteConfigsRequest(**{"parent": "projects/sample1/locations/sample2/muteConfigs"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListMuteConfigsResponse() + client.list_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListMuteConfigsRequest(**{"parent": "organizations/sample1/locations/sample2/muteConfigs"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListMuteConfigsResponse() + client.list_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListMuteConfigsRequest(**{"parent": "folders/sample1/locations/sample2/muteConfigs"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListMuteConfigsResponse() + client.list_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + + +def test_list_mute_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_mute_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_mute_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_mute_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_mute_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_mute_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent='parent_value', + ) + + +def test_list_mute_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_mute_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, mute_config.MuteConfig) + for i in results) +def test_list_mute_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_mute_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_mute_configs_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_mute_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, mute_config.MuteConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_mute_configs_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + 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_mute_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", [ + securitycenter_service.ListNotificationConfigsRequest, + dict, +]) +def test_list_notification_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListNotificationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_notification_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListNotificationConfigsRequest( + 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_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notification_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_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_notification_configs] = mock_rpc + request = {} + client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_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_notification_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + +@pytest.mark.asyncio +async def test_list_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_notification_configs] = mock_object + + request = {} + await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_notification_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListNotificationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_from_dict(): + await test_list_notification_configs_async(request_type=dict) + + +def test_list_notification_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + 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_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + client.list_notification_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_notification_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + 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_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + await client.list_notification_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_notification_configs_flattened(): + client = SecurityCenterClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_notification_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_notification_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_notification_configs_flattened_async(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_notification_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_notification_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_notification_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + 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_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, notification_config.NotificationConfig) + for i in results) +def test_list_notification_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_notification_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_notification_configs_async_pager(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_notification_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, notification_config.NotificationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_pages(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + 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_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", [ + securitycenter_service.ListResourceValueConfigsRequest, + dict, +]) +def test_list_resource_value_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_resource_value_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() + + +def test_list_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListResourceValueConfigsRequest( + 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_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_resource_value_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc + request = {} + client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_value_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_resource_value_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() + +@pytest.mark.asyncio +async def test_list_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_resource_value_configs] = mock_object + + request = {} + await client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_resource_value_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListResourceValueConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async_from_dict(): + await test_list_resource_value_configs_async(request_type=dict) + + +def test_list_resource_value_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + client.list_resource_value_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_resource_value_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) + await client.list_resource_value_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_resource_value_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_resource_value_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_resource_value_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_resource_value_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_resource_value_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_resource_value_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent='parent_value', + ) + + +def test_list_resource_value_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_resource_value_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, resource_value_config.ResourceValueConfig) + for i in results) +def test_list_resource_value_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_resource_value_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_resource_value_configs_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_resource_value_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, resource_value_config.ResourceValueConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + 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_resource_value_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", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListSourcesRequest( + 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_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + +@pytest.mark.asyncio +async def test_list_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_sources in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object + + request = {} + await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_sources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sources_async_from_dict(): + await test_list_sources_async(request_type=dict) + + +def test_list_sources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = securitycenter_service.ListSourcesResponse() + client.list_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_sources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + await client.list_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_sources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_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_sources_flattened_error(): + client = SecurityCenterClient( + credentials=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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_sources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_sources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_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, source.Source) + for i in results) +def test_list_sources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = list(client.list_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_sources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_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, source.Source) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_sources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + 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_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", [ + securitycenter_service.ListValuedResourcesRequest, + dict, +]) +def test_list_valued_resources(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListValuedResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_valued_resources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_valued_resources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest() + + +def test_list_valued_resources_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListValuedResourcesRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_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_valued_resources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_valued_resources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_value', + order_by='order_by_value', + ) + +def test_list_valued_resources_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_valued_resources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc + request = {} + client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_valued_resources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_valued_resources_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_valued_resources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest() + +@pytest.mark.asyncio +async def test_list_valued_resources_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_valued_resources in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_valued_resources] = mock_object + + request = {} + await client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_valued_resources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_valued_resources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListValuedResourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListValuedResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_valued_resources_async_from_dict(): + await test_list_valued_resources_async(request_type=dict) + + +def test_list_valued_resources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListValuedResourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + call.return_value = securitycenter_service.ListValuedResourcesResponse() + client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_valued_resources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListValuedResourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) + await client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_valued_resources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_valued_resources( + 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_valued_resources_flattened_error(): + client = SecurityCenterClient( + credentials=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_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_valued_resources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_valued_resources( + 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_valued_resources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent='parent_value', + ) + + +def test_list_valued_resources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_valued_resources(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, valued_resource.ValuedResource) + for i in results) +def test_list_valued_resources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_valued_resources(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_valued_resources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_valued_resources(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, valued_resource.ValuedResource) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_valued_resources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + 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_valued_resources(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", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_set_finding_state_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + +@pytest.mark.asyncio +async def test_set_finding_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object + + request = {} + await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_finding_state(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_set_finding_state_async_from_dict(): + await test_set_finding_state_async(request_type=dict) + + +def test_set_finding_state_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = finding.Finding() + client.set_finding_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_set_finding_state_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_finding_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_set_finding_state_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + ) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.SetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest( + resource='resource_value', + ) + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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( + version=774, + etag=b'etag_blob', + )) + response = await client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object + + request = {} + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = SecurityCenterClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetMuteRequest, + dict, +]) +def test_set_mute(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetMuteRequest() + 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.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_set_mute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_mute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest() + + +def test_set_mute_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SetMuteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_mute(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest( + name='name_value', + ) + +def test_set_mute_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_mute in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc + request = {} + client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_mute(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_set_mute_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_mute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest() + +@pytest.mark.asyncio +async def test_set_mute_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_mute in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_mute] = mock_object + + request = {} + await client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_mute(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_mute_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetMuteRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetMuteRequest() + 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.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_set_mute_async_from_dict(): + await test_set_mute_async(request_type=dict) + + +def test_set_mute_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetMuteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value = finding.Finding() + client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_mute_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetMuteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_set_mute_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__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.set_mute( + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].mute + mock_val = finding.Finding.Mute.MUTED + assert arg == mock_val + + +def test_set_mute_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_mute( + securitycenter_service.SetMuteRequest(), + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + +@pytest.mark.asyncio +async def test_set_mute_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__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.set_mute( + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].mute + mock_val = finding.Finding.Mute.MUTED + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_mute_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_mute( + securitycenter_service.SetMuteRequest(), + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.TestIamPermissionsRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( + resource='resource_value', + ) + +def test_test_iam_permissions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object + + request = {} + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateBigQueryExportRequest, + dict, +]) +def test_update_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + response = client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +def test_update_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() + + +def test_update_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateBigQueryExportRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest( + ) + +def test_update_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc + request = {} + client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_big_query_export(request) + + # Establish that a new wrapper 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_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.update_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_update_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_big_query_export] = mock_object + + request = {} + await client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +@pytest.mark.asyncio +async def test_update_big_query_export_async_from_dict(): + await test_update_big_query_export_async(request_type=dict) + + +def test_update_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateBigQueryExportRequest() + + request.big_query_export.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value = bigquery_export.BigQueryExport() + client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'big_query_export.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateBigQueryExportRequest() + + request.big_query_export.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + await client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'big_query_export.name=name_value', + ) in kw['metadata'] + + +def test_update_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_big_query_export( + big_query_export=bigquery_export.BigQueryExport(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].big_query_export + mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_big_query_export( + big_query_export=bigquery_export.BigQueryExport(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].big_query_export + mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateExternalSystemRequest, + dict, +]) +def test_update_external_system(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + ) + response = client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateExternalSystemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == 'name_value' + assert response.assignees == ['assignees_value'] + assert response.external_uid == 'external_uid_value' + assert response.status == 'status_value' + assert response.case_uri == 'case_uri_value' + assert response.case_priority == 'case_priority_value' + + +def test_update_external_system_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_external_system() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest() + + +def test_update_external_system_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateExternalSystemRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_external_system(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest( + ) + +def test_update_external_system_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_external_system in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc + request = {} + client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_external_system(request) + + # Establish that a new wrapper 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_external_system_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + )) + response = await client.update_external_system() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest() + +@pytest.mark.asyncio +async def test_update_external_system_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_external_system in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_external_system] = mock_object + + request = {} + await client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_external_system(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_external_system_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateExternalSystemRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + )) + response = await client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateExternalSystemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == 'name_value' + assert response.assignees == ['assignees_value'] + assert response.external_uid == 'external_uid_value' + assert response.status == 'status_value' + assert response.case_uri == 'case_uri_value' + assert response.case_priority == 'case_priority_value' + + +@pytest.mark.asyncio +async def test_update_external_system_async_from_dict(): + await test_update_external_system_async(request_type=dict) + + +def test_update_external_system_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateExternalSystemRequest() + + request.external_system.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value = gcs_external_system.ExternalSystem() + client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'external_system.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_external_system_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateExternalSystemRequest() + + request.external_system.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) + await client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'external_system.name=name_value', + ) in kw['metadata'] + + +def test_update_external_system_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_external_system( + external_system=gcs_external_system.ExternalSystem(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].external_system + mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error(): + client = SecurityCenterClient( + credentials=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_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_external_system_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_external_system( + external_system=gcs_external_system.ExternalSystem(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].external_system + mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_update_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateFindingRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.update_finding] = mock_rpc + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object + + request = {} + await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_update_finding_async_from_dict(): + await test_update_finding_async(request_type=dict) + + +def test_update_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +def test_update_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_finding( + finding=gcs_finding.Finding(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].finding + mock_val = gcs_finding.Finding(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_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_finding( + finding=gcs_finding.Finding(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].finding + mock_val = gcs_finding.Finding(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_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateMuteConfigRequest, + dict, +]) +def test_update_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + response = client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_update_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest() + + +def test_update_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateMuteConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest( + ) + +def test_update_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + request = {} + client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.update_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest() + +@pytest.mark.asyncio +async def test_update_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_mute_config] = mock_object + + request = {} + await client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +@pytest.mark.asyncio +async def test_update_mute_config_async_from_dict(): + await test_update_mute_config_async(request_type=dict) + +def test_update_mute_config_routing_parameters(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateMuteConfigRequest(**{"mute_config": {"name": "projects/sample1/locations/sample2/muteConfigs/sample3"}}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.update_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateMuteConfigRequest(**{"mute_config": {"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"}}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.update_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateMuteConfigRequest(**{"mute_config": {"name": "folders/sample1/locations/sample2/muteConfigs/sample3"}}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.update_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + + +def test_update_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_mute_config( + mute_config=gcs_mute_config.MuteConfig(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].mute_config + mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_mute_config( + mute_config=gcs_mute_config.MuteConfig(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].mute_config + mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, +]) +def test_update_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_update_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateNotificationConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest( + ) + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_update_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_notification_config] = mock_object + + request = {} + await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_update_notification_config_async_from_dict(): + await test_update_notification_config_async(request_type=dict) + + +def test_update_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.update_notification_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', + 'notification_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.update_notification_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', + 'notification_config.name=name_value', + ) in kw['metadata'] + + +def test_update_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_notification_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateResourceValueConfigRequest, + dict, +]) +def test_update_resource_value_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + response = client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +def test_update_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() + + +def test_update_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateResourceValueConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_resource_value_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest( + ) + +def test_update_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + request = {} + client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_resource_value_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_resource_value_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.update_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() + +@pytest.mark.asyncio +async def test_update_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_resource_value_config] = mock_object + + request = {} + await client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_resource_value_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateResourceValueConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +@pytest.mark.asyncio +async def test_update_resource_value_config_async_from_dict(): + await test_update_resource_value_config_async(request_type=dict) + + +def test_update_resource_value_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateResourceValueConfigRequest() + + request.resource_value_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value = gcs_resource_value_config.ResourceValueConfig() + client.update_resource_value_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', + 'resource_value_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateResourceValueConfigRequest() + + request.resource_value_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) + await client.update_resource_value_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', + 'resource_value_config.name=name_value', + ) in kw['metadata'] + + +def test_update_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_resource_value_config( + resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config + mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_resource_value_config( + resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config + mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + response = client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_security_marks_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + +def test_update_security_marks_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSecurityMarksRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( + ) + +def test_update_security_marks_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish that a new wrapper 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_security_marks_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + +@pytest.mark.asyncio +async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_marks in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object + + request = {} + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_security_marks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_security_marks_async_from_dict(): + await test_update_security_marks_async(request_type=dict) + + +def test_update_security_marks_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = gcs_security_marks.SecurityMarks() + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_marks_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +def test_update_security_marks_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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].security_marks + mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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].security_marks + mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSourceRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object + + request = {} + await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_source_async_from_dict(): + await test_update_source_async(request_type=dict) + + +def test_update_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +def test_update_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_source( + source=gcs_source.Source(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].source + mock_val = gcs_source.Source(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_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_source( + source=gcs_source.Source(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].source + mock_val = gcs_source.Source(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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.BatchCreateResourceValueConfigsRequest, + dict, +]) +def test_batch_create_resource_value_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.BatchCreateResourceValueConfigsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) + +def test_batch_create_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc + + request = {} + client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_resource_value_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_batch_create_resource_value_configs_rest_required_fields(request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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()).batch_create_resource_value_configs._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_create_resource_value_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_create_resource_value_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_resource_value_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_batch_create_resource_value_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_batch_create_resource_value_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(securitycenter_service.BatchCreateResourceValueConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.BatchCreateResourceValueConfigsResponse.to_json(securitycenter_service.BatchCreateResourceValueConfigsResponse()) + + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + client.batch_create_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_create_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_create_resource_value_configs(request) + + +def test_batch_create_resource_value_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(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.batch_create_resource_value_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/v2/{parent=organizations/*}/resourceValueConfigs:batchCreate" % client.transport._host, args[1]) + + +def test_batch_create_resource_value_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], + ) + + +def test_batch_create_resource_value_configs_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.BulkMuteFindingsRequest, + dict, +]) +def test_bulk_mute_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') + + # 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 + response = client.bulk_mute_findings(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_bulk_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc + + request = {} + client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_rest_required_fields(request_type=securitycenter_service.BulkMuteFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).bulk_mute_findings._get_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()).bulk_mute_findings._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 = SecurityCenterClient( + 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.bulk_mute_findings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_bulk_mute_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.bulk_mute_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_bulk_mute_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_bulk_mute_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_bulk_mute_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.BulkMuteFindingsRequest.pb(securitycenter_service.BulkMuteFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = securitycenter_service.BulkMuteFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.bulk_mute_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_bulk_mute_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BulkMuteFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.bulk_mute_findings(request) + + +def test_bulk_mute_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.bulk_mute_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/v2/{parent=organizations/*}/findings:bulkMute" % client.transport._host, args[1]) + + +def test_bulk_mute_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent='parent_value', + ) + + +def test_bulk_mute_findings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateBigQueryExportRequest, + dict, +]) +def test_create_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/locations/sample2'} + request_init["big_query_export"] = {'name': 'name_value', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.CreateBigQueryExportRequest.meta.fields["big_query_export"] + + 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["big_query_export"].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["big_query_export"][field])): + del request_init["big_query_export"][field][i][subfield] + else: + del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + +def test_create_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + + request = {} + client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.CreateBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["big_query_export_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 "bigQueryExportId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "bigQueryExportId" in jsonified_request + assert jsonified_request["bigQueryExportId"] == request_init["big_query_export_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["bigQueryExportId"] = 'big_query_export_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("big_query_export_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 "bigQueryExportId" in jsonified_request + assert jsonified_request["bigQueryExportId"] == 'big_query_export_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + expected_params = [ + ( + "bigQueryExportId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(("bigQueryExportId", )) & set(("parent", "bigQueryExport", "bigQueryExportId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_big_query_export") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_big_query_export") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateBigQueryExportRequest.pb(securitycenter_service.CreateBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) + + request = securitycenter_service.CreateBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.create_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_big_query_export(request) + + +def test_create_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{parent=organizations/*/locations/*}/bigQueryExports" % client.transport._host, args[1]) + + +def test_create_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_id_value', + ) + + +def test_create_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2/locations/sample3'} + request_init["finding"] = {'name': 'name_value', 'canonical_name': 'canonical_name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'mute': 1, 'mute_info': {'static_mute': {'state': 1, 'apply_time': {}}, 'dynamic_mute_records': [{'mute_config': 'mute_config_value', 'match_time': {}}]}, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True, 'exploit_release_date': {}}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.create_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.create_finding] = mock_rpc + + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["finding_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 "findingId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "findingId" in jsonified_request + assert jsonified_request["findingId"] == request_init["finding_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["findingId"] = 'finding_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request + assert jsonified_request["findingId"] == 'finding_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.create_finding(request) + + expected_params = [ + ( + "findingId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.CreateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2/locations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_finding(request) + + +def test_create_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2/locations/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + finding=gcs_finding.Finding(name='name_value'), + finding_id='finding_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 = gcs_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.create_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/v2/{parent=organizations/*/sources/*/locations/*}/findings" % client.transport._host, args[1]) + + +def test_create_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding=gcs_finding.Finding(name='name_value'), + finding_id='finding_id_value', + ) + + +def test_create_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateMuteConfigRequest, + dict, +]) +def test_create_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/locations/sample2'} + request_init["mute_config"] = {'name': 'name_value', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'type_': 1, 'expiry_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 = securitycenter_service.CreateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): + del request_init["mute_config"][field][i][subfield] + else: + del request_init["mute_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 = gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + +def test_create_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + + request = {} + client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.CreateMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["mute_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 "muteConfigId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "muteConfigId" in jsonified_request + assert jsonified_request["muteConfigId"] == request_init["mute_config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["muteConfigId"] = 'mute_config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("mute_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 "muteConfigId" in jsonified_request + assert jsonified_request["muteConfigId"] == 'mute_config_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + expected_params = [ + ( + "muteConfigId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("muteConfigId", )) & set(("parent", "muteConfig", "muteConfigId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_mute_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_mute_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateMuteConfigRequest.pb(securitycenter_service.CreateMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) + + request = securitycenter_service.CreateMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_mute_config.MuteConfig() + + client.create_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_mute_config(request) + + +def test_create_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_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 = gcs_mute_config.MuteConfig.pb(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_mute_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/v2/{parent=organizations/*/locations/*}/muteConfigs" % client.transport._host, args[1]) + + +def test_create_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_id_value', + ) + + +def test_create_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateNotificationConfigRequest, + dict, +]) +def test_create_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/locations/sample2'} + request_init["notification_config"] = {'name': 'name_value', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.CreateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.CreateNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["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 "configId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "configId" in jsonified_request + assert jsonified_request["configId"] == request_init["config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["configId"] = 'config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("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 "configId" in jsonified_request + assert jsonified_request["configId"] == 'config_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ( + "configId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("configId", )) & set(("parent", "configId", "notificationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateNotificationConfigRequest.pb(securitycenter_service.CreateNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) + + request = securitycenter_service.CreateNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.create_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_notification_config(request) + + +def test_create_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + config_id='config_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 = gcs_notification_config.NotificationConfig.pb(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_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/v2/{parent=organizations/*/locations/*}/notificationConfigs" % client.transport._host, args[1]) + + +def test_create_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + config_id='config_id_value', + ) + + +def test_create_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.CreateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_source(request) + + +def test_create_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v2/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_create_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +def test_create_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteBigQueryExportRequest, + dict, +]) +def test_delete_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + + request = {} + client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.DeleteBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + 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_big_query_export(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_big_query_export") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteBigQueryExportRequest.pb(securitycenter_service.DeleteBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_big_query_export(request) + + +def test_delete_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/locations/sample2/bigQueryExports/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_big_query_export(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{name=organizations/*/locations/*/bigQueryExports/*}" % client.transport._host, args[1]) + + +def test_delete_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name='name_value', + ) + + +def test_delete_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteMuteConfigRequest, + dict, +]) +def test_delete_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/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 = 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + + request = {} + client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.DeleteMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( + 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_mute_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_mute_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteMuteConfigRequest.pb(securitycenter_service.DeleteMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_mute_config(request) + + +def test_delete_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/muteConfigs/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_mute_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/v2/{name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name='name_value', + ) + + +def test_delete_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, +]) +def test_delete_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = 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_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.DeleteNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_notification_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteNotificationConfigRequest.pb(securitycenter_service.DeleteNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_notification_config(request) + + +def test_delete_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/locations/sample2/notificationConfigs/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_notification_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/v2/{name=organizations/*/locations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +def test_delete_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteResourceValueConfigRequest, + dict, +]) +def test_delete_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = 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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + + request = {} + client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.DeleteResourceValueConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( + 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_resource_value_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_resource_value_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteResourceValueConfigRequest.pb(securitycenter_service.DeleteResourceValueConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteResourceValueConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteResourceValueConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_resource_value_config(request) + + +def test_delete_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/resourceValueConfigs/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_resource_value_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/v2/{name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_resource_value_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name='name_value', + ) + + +def test_delete_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetBigQueryExportRequest, + dict, +]) +def test_get_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + +def test_get_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc + + request = {} + client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.GetBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_big_query_export") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_big_query_export") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetBigQueryExportRequest.pb(securitycenter_service.GetBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) + + request = securitycenter_service.GetBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.get_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_big_query_export(request) + + +def test_get_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{name=organizations/*/locations/*/bigQueryExports/*}" % client.transport._host, args[1]) + + +def test_get_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name='name_value', + ) + + +def test_get_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSimulationRequest, + dict, +]) +def test_get_simulation_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = simulation.Simulation.pb(return_value) + 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_simulation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == 'name_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + +def test_get_simulation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_simulation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc + + request = {} + client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_simulation(request) + + # Establish 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_simulation_rest_required_fields(request_type=securitycenter_service.GetSimulationRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_simulation._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_simulation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = simulation.Simulation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = simulation.Simulation.pb(return_value) + 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_simulation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_simulation_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_simulation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_simulation_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_simulation") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_simulation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSimulationRequest.pb(securitycenter_service.GetSimulationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = simulation.Simulation.to_json(simulation.Simulation()) + + request = securitycenter_service.GetSimulationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = simulation.Simulation() + + client.get_simulation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_simulation_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSimulationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_simulation(request) + + +def test_get_simulation_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = simulation.Simulation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation.pb(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_simulation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{name=organizations/*/simulations/*}" % client.transport._host, args[1]) + + +def test_get_simulation_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_simulation( + securitycenter_service.GetSimulationRequest(), + name='name_value', + ) + + +def test_get_simulation_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetValuedResourceRequest, + dict, +]) +def test_get_valued_resource_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = valued_resource.ValuedResource.pb(return_value) + 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_valued_resource(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == 'name_value' + assert response.resource == 'resource_value' + assert response.resource_type == 'resource_type_value' + assert response.display_name == 'display_name_value' + assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + +def test_get_valued_resource_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_valued_resource in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc + + request = {} + client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_valued_resource(request) + + # Establish 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_valued_resource_rest_required_fields(request_type=securitycenter_service.GetValuedResourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_valued_resource._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_valued_resource._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = valued_resource.ValuedResource() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = valued_resource.ValuedResource.pb(return_value) + 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_valued_resource(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_valued_resource_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_valued_resource._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_valued_resource_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_valued_resource") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_valued_resource") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetValuedResourceRequest.pb(securitycenter_service.GetValuedResourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = valued_resource.ValuedResource.to_json(valued_resource.ValuedResource()) + + request = securitycenter_service.GetValuedResourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = valued_resource.ValuedResource() + + client.get_valued_resource(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_valued_resource_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetValuedResourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_valued_resource(request) + + +def test_get_valued_resource_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = valued_resource.ValuedResource() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource.pb(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_valued_resource(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{name=organizations/*/simulations/*/valuedResources/*}" % client.transport._host, args[1]) + + +def test_get_valued_resource_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name='name_value', + ) + + +def test_get_valued_resource_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.get_iam_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/v2/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetMuteConfigRequest, + dict, +]) +def test_get_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC + +def test_get_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_mute_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_mute_config] = mock_rpc + + request = {} + client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.GetMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = mute_config.MuteConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_mute_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_mute_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetMuteConfigRequest.pb(securitycenter_service.GetMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = mute_config.MuteConfig.to_json(mute_config.MuteConfig()) + + request = securitycenter_service.GetMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = mute_config.MuteConfig() + + client.get_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_mute_config(request) + + +def test_get_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig.pb(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_mute_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/v2/{name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) + + +def test_get_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name='name_value', + ) + + +def test_get_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetNotificationConfigRequest, + dict, +]) +def test_get_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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_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_notification_config] = mock_rpc + + request = {} + client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.GetNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetNotificationConfigRequest.pb(securitycenter_service.GetNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = notification_config.NotificationConfig.to_json(notification_config.NotificationConfig()) + + request = securitycenter_service.GetNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = notification_config.NotificationConfig() + + client.get_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_notification_config(request) + + +def test_get_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = notification_config.NotificationConfig.pb(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_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/v2/{name=organizations/*/locations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_get_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +def test_get_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetResourceValueConfigRequest, + dict, +]) +def test_get_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + +def test_get_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc + + request = {} + client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.GetResourceValueConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource_value_config.ResourceValueConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_resource_value_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_resource_value_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetResourceValueConfigRequest.pb(securitycenter_service.GetResourceValueConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource_value_config.ResourceValueConfig.to_json(resource_value_config.ResourceValueConfig()) + + request = securitycenter_service.GetResourceValueConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource_value_config.ResourceValueConfig() + + client.get_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetResourceValueConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_resource_value_config(request) + + +def test_get_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resource_value_config.ResourceValueConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig.pb(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_resource_value_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/v2/{name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) + + +def test_get_resource_value_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name='name_value', + ) + + +def test_get_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/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 = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = source.Source.to_json(source.Source()) + + request = securitycenter_service.GetSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = source.Source() + + client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_source(request) + + +def test_get_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v2/{name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_get_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +def test_get_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_findings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) + + request = securitycenter_service.GroupFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupFindingsResponse() + + client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_findings(request) + + +def test_group_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + group_by='group_by_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v2/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) + + +def test_group_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} + + pager = client.group_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_findings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListAttackPathsRequest, + dict, +]) +def test_list_attack_paths_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) + 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_attack_paths(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_attack_paths_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_attack_paths in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc + + request = {} + client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_attack_paths(request) + + # Establish 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_attack_paths_rest_required_fields(request_type=securitycenter_service.ListAttackPathsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_attack_paths._get_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_attack_paths._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAttackPathsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) + 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_attack_paths(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_attack_paths_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_attack_paths._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_attack_paths_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_attack_paths") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_attack_paths") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListAttackPathsRequest.pb(securitycenter_service.ListAttackPathsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListAttackPathsResponse.to_json(securitycenter_service.ListAttackPathsResponse()) + + request = securitycenter_service.ListAttackPathsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListAttackPathsResponse() + + client.list_attack_paths(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_attack_paths_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAttackPathsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_attack_paths(request) + + +def test_list_attack_paths_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAttackPathsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse.pb(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_attack_paths(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{parent=organizations/*/simulations/*}/attackPaths" % client.transport._host, args[1]) + + +def test_list_attack_paths_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent='parent_value', + ) + + +def test_list_attack_paths_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListAttackPathsResponse.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': 'organizations/sample1/simulations/sample2'} + + pager = client.list_attack_paths(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, attack_path.AttackPath) + for i in results) + + pages = list(client.list_attack_paths(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListBigQueryExportsRequest, + dict, +]) +def test_list_big_query_exports_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) + 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_big_query_exports(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_big_query_exports_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_big_query_exports in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc + + request = {} + client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_big_query_exports(request) + + # Establish 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_big_query_exports_rest_required_fields(request_type=securitycenter_service.ListBigQueryExportsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_big_query_exports._get_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_big_query_exports._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListBigQueryExportsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) + 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_big_query_exports(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_big_query_exports_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_big_query_exports._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_big_query_exports_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_big_query_exports") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_big_query_exports") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListBigQueryExportsRequest.pb(securitycenter_service.ListBigQueryExportsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListBigQueryExportsResponse.to_json(securitycenter_service.ListBigQueryExportsResponse()) + + request = securitycenter_service.ListBigQueryExportsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListBigQueryExportsResponse() + + client.list_big_query_exports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_big_query_exports_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListBigQueryExportsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_big_query_exports(request) + + +def test_list_big_query_exports_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListBigQueryExportsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse.pb(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_big_query_exports(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{parent=organizations/*/locations/*}/bigQueryExports" % client.transport._host, args[1]) + + +def test_list_big_query_exports_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent='parent_value', + ) + + +def test_list_big_query_exports_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListBigQueryExportsResponse.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': 'organizations/sample1/locations/sample2'} + + pager = client.list_big_query_exports(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, bigquery_export.BigQueryExport) + for i in results) + + pages = list(client.list_big_query_exports(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.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' + assert response.total_size == 1086 + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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=securitycenter_service.ListFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("field_mask", "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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.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 = securitycenter_service.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 = [ + ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("fieldMask", "filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) + + request = securitycenter_service.ListFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListFindingsResponse() + + client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_findings(request) + + +def test_list_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.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/v2/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) + + +def test_list_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + + +def test_list_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} + + pager = client.list_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) + 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 + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListMuteConfigsRequest, + dict, +]) +def test_list_mute_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) + 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_mute_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_mute_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_mute_configs] = mock_rpc + + request = {} + client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_mute_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_mute_configs_rest_required_fields(request_type=securitycenter_service.ListMuteConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListMuteConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) + 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_mute_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_mute_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_mute_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_mute_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_mute_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_mute_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListMuteConfigsRequest.pb(securitycenter_service.ListMuteConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListMuteConfigsResponse.to_json(securitycenter_service.ListMuteConfigsResponse()) + + request = securitycenter_service.ListMuteConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListMuteConfigsResponse() + + client.list_mute_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_mute_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListMuteConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_mute_configs(request) + + +def test_list_mute_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListMuteConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse.pb(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_mute_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/v2/{parent=organizations/*}/muteConfigs" % client.transport._host, args[1]) + + +def test_list_mute_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent='parent_value', + ) + + +def test_list_mute_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListMuteConfigsResponse.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': 'organizations/sample1'} + + pager = client.list_mute_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, mute_config.MuteConfig) + for i in results) + + pages = list(client.list_mute_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListNotificationConfigsRequest, + dict, +]) +def test_list_notification_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) + 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_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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_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_notification_configs] = mock_rpc + + request = {} + client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_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_notification_configs_rest_required_fields(request_type=securitycenter_service.ListNotificationConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListNotificationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) + 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_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_notification_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_notification_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_notification_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_notification_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_notification_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListNotificationConfigsRequest.pb(securitycenter_service.ListNotificationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListNotificationConfigsResponse.to_json(securitycenter_service.ListNotificationConfigsResponse()) + + request = securitycenter_service.ListNotificationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListNotificationConfigsResponse() + + client.list_notification_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_notification_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_notification_configs(request) + + +def test_list_notification_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListNotificationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse.pb(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_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/v2/{parent=organizations/*/locations/*}/notificationConfigs" % client.transport._host, args[1]) + + +def test_list_notification_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListNotificationConfigsResponse.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': 'organizations/sample1/locations/sample2'} + + pager = client.list_notification_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, notification_config.NotificationConfig) + for i in results) + + pages = list(client.list_notification_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListResourceValueConfigsRequest, + dict, +]) +def test_list_resource_value_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc + + request = {} + client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_value_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_resource_value_configs_rest_required_fields(request_type=securitycenter_service.ListResourceValueConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListResourceValueConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_resource_value_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_resource_value_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_resource_value_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_resource_value_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_resource_value_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListResourceValueConfigsRequest.pb(securitycenter_service.ListResourceValueConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListResourceValueConfigsResponse.to_json(securitycenter_service.ListResourceValueConfigsResponse()) + + request = securitycenter_service.ListResourceValueConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListResourceValueConfigsResponse() + + client.list_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListResourceValueConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_resource_value_configs(request) + + +def test_list_resource_value_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListResourceValueConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse.pb(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_resource_value_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/v2/{parent=organizations/*}/resourceValueConfigs" % client.transport._host, args[1]) + + +def test_list_resource_value_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent='parent_value', + ) + + +def test_list_resource_value_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListResourceValueConfigsResponse.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': 'organizations/sample1'} + + pager = client.list_resource_value_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource_value_config.ResourceValueConfig) + for i in results) + + pages = list(client.list_resource_value_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_sources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_sources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) + + request = securitycenter_service.ListSourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListSourcesResponse() + + client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_sources(request) + + +def test_list_sources_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v2/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_list_sources_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} + + pager = client.list_sources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, source.Source) + for i in results) + + pages = list(client.list_sources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListValuedResourcesRequest, + dict, +]) +def test_list_valued_resources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) + 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_valued_resources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_list_valued_resources_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_valued_resources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc + + request = {} + client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_valued_resources(request) + + # Establish 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_valued_resources_rest_required_fields(request_type=securitycenter_service.ListValuedResourcesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_valued_resources._get_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_valued_resources._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListValuedResourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) + 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_valued_resources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_valued_resources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_valued_resources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_valued_resources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_valued_resources") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_valued_resources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListValuedResourcesRequest.pb(securitycenter_service.ListValuedResourcesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListValuedResourcesResponse.to_json(securitycenter_service.ListValuedResourcesResponse()) + + request = securitycenter_service.ListValuedResourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListValuedResourcesResponse() + + client.list_valued_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_valued_resources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListValuedResourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_valued_resources(request) + + +def test_list_valued_resources_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListValuedResourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse.pb(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_valued_resources(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{parent=organizations/*/simulations/*}/valuedResources" % client.transport._host, args[1]) + + +def test_list_valued_resources_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent='parent_value', + ) + + +def test_list_valued_resources_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListValuedResourcesResponse.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': 'organizations/sample1/simulations/sample2'} + + pager = client.list_valued_resources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, valued_resource.ValuedResource) + for i in results) + + pages = list(client.list_valued_resources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # 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 + response = client.set_finding_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( + 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': "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 = 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.set_finding_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_finding_state_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_finding_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "state", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_finding_state_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetFindingStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_finding_state(request) + + +def test_set_finding_state_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + state=finding.Finding.State.ACTIVE, + ) + mock_args.update(sample_request) + + # 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.set_finding_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/v2/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) + + +def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + ) + + +def test_set_finding_state_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.set_iam_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/v2/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetMuteRequest, + dict, +]) +def test_set_mute_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # 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 + response = client.set_mute(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_set_mute_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_mute in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc + + request = {} + client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_mute(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_set_mute_rest_required_fields(request_type=securitycenter_service.SetMuteRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + 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': "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 = 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.set_mute(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_mute_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_mute._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "mute", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_mute_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_mute") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_mute") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetMuteRequest.pb(securitycenter_service.SetMuteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetMuteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_mute(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_mute_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetMuteRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_mute(request) + + +def test_set_mute_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + mock_args.update(sample_request) + + # 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.set_mute(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{name=organizations/*/sources/*/findings/*}:setMute" % client.transport._host, args[1]) + + +def test_set_mute_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_mute( + securitycenter_service.SetMuteRequest(), + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + +def test_set_mute_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # 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 + response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_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.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateBigQueryExportRequest, + dict, +]) +def test_update_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'big_query_export': {'name': 'organizations/sample1/locations/sample2/bigQueryExports/sample3'}} + request_init["big_query_export"] = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/sample3', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.UpdateBigQueryExportRequest.meta.fields["big_query_export"] + + 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["big_query_export"].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["big_query_export"][field])): + del request_init["big_query_export"][field][i][subfield] + else: + del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + +def test_update_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc + + request = {} + client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.UpdateBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_big_query_export._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_big_query_export._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("bigQueryExport", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_big_query_export") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_big_query_export") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateBigQueryExportRequest.pb(securitycenter_service.UpdateBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) + + request = securitycenter_service.UpdateBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.update_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'big_query_export': {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_big_query_export(request) + + +def test_update_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = {'big_query_export': {'name': 'organizations/sample1/locations/sample2/bigQueryExports/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + big_query_export=bigquery_export.BigQueryExport(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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{big_query_export.name=organizations/*/locations/*/bigQueryExports/*}" % client.transport._host, args[1]) + + +def test_update_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateExternalSystemRequest, + dict, +]) +def test_update_external_system_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} + request_init["external_system"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4', 'assignees': ['assignees_value1', 'assignees_value2'], 'external_uid': 'external_uid_value', 'status': 'status_value', 'external_system_update_time': {'seconds': 751, 'nanos': 543}, 'case_uri': 'case_uri_value', 'case_priority': 'case_priority_value', 'case_sla': {}, 'case_create_time': {}, 'case_close_time': {}, 'ticket_info': {'id': 'id_value', 'assignee': 'assignee_value', 'description': 'description_value', 'uri': 'uri_value', 'status': 'status_value', 'update_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 = securitycenter_service.UpdateExternalSystemRequest.meta.fields["external_system"] + + 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["external_system"].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["external_system"][field])): + del request_init["external_system"][field][i][subfield] + else: + del request_init["external_system"][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 = gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_external_system.ExternalSystem.pb(return_value) + 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_external_system(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == 'name_value' + assert response.assignees == ['assignees_value'] + assert response.external_uid == 'external_uid_value' + assert response.status == 'status_value' + assert response.case_uri == 'case_uri_value' + assert response.case_priority == 'case_priority_value' + +def test_update_external_system_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_external_system in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc + + request = {} + client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_external_system(request) + + # Establish 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_external_system_rest_required_fields(request_type=securitycenter_service.UpdateExternalSystemRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_external_system._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_external_system._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_external_system.ExternalSystem() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_external_system.ExternalSystem.pb(return_value) + 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_external_system(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_external_system_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_external_system._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("externalSystem", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_external_system_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_external_system") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_external_system") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateExternalSystemRequest.pb(securitycenter_service.UpdateExternalSystemRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_external_system.ExternalSystem.to_json(gcs_external_system.ExternalSystem()) + + request = securitycenter_service.UpdateExternalSystemRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_external_system.ExternalSystem() + + client.update_external_system(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_external_system_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateExternalSystemRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_external_system(request) + + +def test_update_external_system_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_external_system.ExternalSystem() + + # get arguments that satisfy an http rule for this method + sample_request = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + external_system=gcs_external_system.ExternalSystem(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 = gcs_external_system.ExternalSystem.pb(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_external_system(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}" % client.transport._host, args[1]) + + +def test_update_external_system_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_external_system_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'canonical_name': 'canonical_name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'mute': 1, 'mute_info': {'static_mute': {'state': 1, 'apply_time': {}}, 'dynamic_mute_records': [{'mute_config': 'mute_config_value', 'match_time': {}}]}, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True, 'exploit_release_date': {}}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.update_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.update_finding] = mock_rpc + + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_finding._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_finding._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.update_finding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.UpdateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_finding(request) + + +def test_update_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + finding=gcs_finding.Finding(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 = gcs_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.update_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/v2/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) + + +def test_update_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateMuteConfigRequest, + dict, +]) +def test_update_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} + request_init["mute_config"] = {'name': 'organizations/sample1/muteConfigs/sample2', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'type_': 1, 'expiry_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 = securitycenter_service.UpdateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): + del request_init["mute_config"][field][i][subfield] + else: + del request_init["mute_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 = gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + +def test_update_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + + request = {} + client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.UpdateMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("muteConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_mute_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_mute_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateMuteConfigRequest.pb(securitycenter_service.UpdateMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) + + request = securitycenter_service.UpdateMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_mute_config.MuteConfig() + + client.update_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_mute_config(request) + + +def test_update_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + mute_config=gcs_mute_config.MuteConfig(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 = gcs_mute_config.MuteConfig.pb(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_mute_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/v2/{mute_config.name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) + + +def test_update_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, +]) +def test_update_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'notification_config': {'name': 'organizations/sample1/locations/sample2/notificationConfigs/sample3'}} + request_init["notification_config"] = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/sample3', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.UpdateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.UpdateNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("notificationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateNotificationConfigRequest.pb(securitycenter_service.UpdateNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) + + request = securitycenter_service.UpdateNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.update_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'notification_config': {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_notification_config(request) + + +def test_update_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'notification_config': {'name': 'organizations/sample1/locations/sample2/notificationConfigs/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/v2/{notification_config.name=organizations/*/locations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_update_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateResourceValueConfigRequest, + dict, +]) +def test_update_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} + request_init["resource_value_config"] = {'name': 'organizations/sample1/resourceValueConfigs/sample2', 'resource_value': 1, 'tag_values': ['tag_values_value1', 'tag_values_value2'], 'resource_type': 'resource_type_value', 'scope': 'scope_value', 'resource_labels_selector': {}, 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'cloud_provider': 1, 'sensitive_data_protection_mapping': {'high_sensitivity_mapping': 1, 'medium_sensitivity_mapping': 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 = securitycenter_service.UpdateResourceValueConfigRequest.meta.fields["resource_value_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["resource_value_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["resource_value_config"][field])): + del request_init["resource_value_config"][field][i][subfield] + else: + del request_init["resource_value_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 = gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + +def test_update_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + + request = {} + client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.UpdateResourceValueConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_resource_value_config.ResourceValueConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("resourceValueConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_resource_value_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_resource_value_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateResourceValueConfigRequest.pb(securitycenter_service.UpdateResourceValueConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_resource_value_config.ResourceValueConfig.to_json(gcs_resource_value_config.ResourceValueConfig()) + + request = securitycenter_service.UpdateResourceValueConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_resource_value_config.ResourceValueConfig() + + client.update_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateResourceValueConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_resource_value_config(request) + + +def test_update_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_resource_value_config.ResourceValueConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + resource_value_config=gcs_resource_value_config.ResourceValueConfig(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 = gcs_resource_value_config.ResourceValueConfig.pb(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_resource_value_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/v2/{resource_value_config.name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) + + +def test_update_resource_value_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks'}} + request_init["security_marks"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks', 'marks': {}, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] + + 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["security_marks"].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["security_marks"][field])): + del request_init["security_marks"][field][i][subfield] + else: + del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + +def test_update_security_marks_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_security_marks._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_security_marks._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_security_marks_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_security_marks._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("securityMarks", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_security_marks_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) + + request = securitycenter_service.UpdateSecurityMarksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_security_marks.SecurityMarks() + + client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_security_marks(request) + + +def test_update_security_marks_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + + # get arguments that satisfy an http rule for this method + sample_request = {'security_marks': {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks'}} + + # get truthy value for each flattened field + mock_args = dict( + security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}" % client.transport._host, args[1]) + + +def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_security_marks_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.UpdateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_source(request) + + +def test_update_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v2/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_update_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SecurityCenterClient( + 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 = SecurityCenterClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecurityCenterClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, +]) +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() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SecurityCenterClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecurityCenterGrpcTransport, + ) + +def test_security_center_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_security_center_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.securitycenter_v2.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'batch_create_resource_value_configs', + 'bulk_mute_findings', + 'create_big_query_export', + 'create_finding', + 'create_mute_config', + 'create_notification_config', + 'create_source', + 'delete_big_query_export', + 'delete_mute_config', + 'delete_notification_config', + 'delete_resource_value_config', + 'get_big_query_export', + 'get_simulation', + 'get_valued_resource', + 'get_iam_policy', + 'get_mute_config', + 'get_notification_config', + 'get_resource_value_config', + 'get_source', + 'group_findings', + 'list_attack_paths', + 'list_big_query_exports', + 'list_findings', + 'list_mute_configs', + 'list_notification_configs', + 'list_resource_value_configs', + 'list_sources', + 'list_valued_resources', + 'set_finding_state', + 'set_iam_policy', + 'set_mute', + 'test_iam_permissions', + 'update_big_query_export', + 'update_external_system', + 'update_finding', + 'update_mute_config', + 'update_notification_config', + 'update_resource_value_config', + 'update_security_marks', + 'update_source', + '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_security_center_base_transport_with_credentials_file(): + # Instantiate the 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.securitycenter_v2.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + 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_security_center_base_transport_with_adc(): + # Test the default 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.securitycenter_v2.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +def test_security_center_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) + SecurityCenterClient() + 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_transport_auth_adc(transport_class): + # If 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, + ], +) +def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_security_center_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host 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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_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.SecurityCenterRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_security_center_rest_lro_client(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a 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 + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_no_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_with_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_security_center_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SecurityCenterClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SecurityCenterClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.batch_create_resource_value_configs._session + session2 = client2.transport.batch_create_resource_value_configs._session + assert session1 != session2 + session1 = client1.transport.bulk_mute_findings._session + session2 = client2.transport.bulk_mute_findings._session + assert session1 != session2 + session1 = client1.transport.create_big_query_export._session + session2 = client2.transport.create_big_query_export._session + assert session1 != session2 + session1 = client1.transport.create_finding._session + session2 = client2.transport.create_finding._session + assert session1 != session2 + session1 = client1.transport.create_mute_config._session + session2 = client2.transport.create_mute_config._session + assert session1 != session2 + session1 = client1.transport.create_notification_config._session + session2 = client2.transport.create_notification_config._session + assert session1 != session2 + session1 = client1.transport.create_source._session + session2 = client2.transport.create_source._session + assert session1 != session2 + session1 = client1.transport.delete_big_query_export._session + session2 = client2.transport.delete_big_query_export._session + assert session1 != session2 + session1 = client1.transport.delete_mute_config._session + session2 = client2.transport.delete_mute_config._session + assert session1 != session2 + session1 = client1.transport.delete_notification_config._session + session2 = client2.transport.delete_notification_config._session + assert session1 != session2 + session1 = client1.transport.delete_resource_value_config._session + session2 = client2.transport.delete_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.get_big_query_export._session + session2 = client2.transport.get_big_query_export._session + assert session1 != session2 + session1 = client1.transport.get_simulation._session + session2 = client2.transport.get_simulation._session + assert session1 != session2 + session1 = client1.transport.get_valued_resource._session + session2 = client2.transport.get_valued_resource._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.get_mute_config._session + session2 = client2.transport.get_mute_config._session + assert session1 != session2 + session1 = client1.transport.get_notification_config._session + session2 = client2.transport.get_notification_config._session + assert session1 != session2 + session1 = client1.transport.get_resource_value_config._session + session2 = client2.transport.get_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.get_source._session + session2 = client2.transport.get_source._session + assert session1 != session2 + session1 = client1.transport.group_findings._session + session2 = client2.transport.group_findings._session + assert session1 != session2 + session1 = client1.transport.list_attack_paths._session + session2 = client2.transport.list_attack_paths._session + assert session1 != session2 + session1 = client1.transport.list_big_query_exports._session + session2 = client2.transport.list_big_query_exports._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_mute_configs._session + session2 = client2.transport.list_mute_configs._session + assert session1 != session2 + session1 = client1.transport.list_notification_configs._session + session2 = client2.transport.list_notification_configs._session + assert session1 != session2 + session1 = client1.transport.list_resource_value_configs._session + session2 = client2.transport.list_resource_value_configs._session + assert session1 != session2 + session1 = client1.transport.list_sources._session + session2 = client2.transport.list_sources._session + assert session1 != session2 + session1 = client1.transport.list_valued_resources._session + session2 = client2.transport.list_valued_resources._session + assert session1 != session2 + session1 = client1.transport.set_finding_state._session + session2 = client2.transport.set_finding_state._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.set_mute._session + session2 = client2.transport.set_mute._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 + session1 = client1.transport.update_big_query_export._session + session2 = client2.transport.update_big_query_export._session + assert session1 != session2 + session1 = client1.transport.update_external_system._session + session2 = client2.transport.update_external_system._session + assert session1 != session2 + session1 = client1.transport.update_finding._session + session2 = client2.transport.update_finding._session + assert session1 != session2 + session1 = client1.transport.update_mute_config._session + session2 = client2.transport.update_mute_config._session + assert session1 != session2 + session1 = client1.transport.update_notification_config._session + session2 = client2.transport.update_notification_config._session + assert session1 != session2 + session1 = client1.transport.update_resource_value_config._session + session2 = client2.transport.update_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.update_security_marks._session + session2 = client2.transport.update_security_marks._session + assert session1 != session2 + session1 = client1.transport.update_source._session + session2 = client2.transport.update_source._session + assert session1 != session2 +def test_security_center_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcTransport( + 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_security_center_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcAsyncIOTransport( + 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(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_security_center_grpc_lro_client(): + client = SecurityCenterClient( + 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_security_center_grpc_lro_async_client(): + client = SecurityCenterAsyncClient( + 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_attack_path_path(): + organization = "squid" + simulation = "clam" + valued_resource = "whelk" + attack_path = "octopus" + expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) + actual = SecurityCenterClient.attack_path_path(organization, simulation, valued_resource, attack_path) + assert expected == actual + + +def test_parse_attack_path_path(): + expected = { + "organization": "oyster", + "simulation": "nudibranch", + "valued_resource": "cuttlefish", + "attack_path": "mussel", + } + path = SecurityCenterClient.attack_path_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_attack_path_path(path) + assert expected == actual + +def test_big_query_export_path(): + organization = "winkle" + location = "nautilus" + export = "scallop" + expected = "organizations/{organization}/locations/{location}/bigQueryExports/{export}".format(organization=organization, location=location, export=export, ) + actual = SecurityCenterClient.big_query_export_path(organization, location, export) + assert expected == actual + + +def test_parse_big_query_export_path(): + expected = { + "organization": "abalone", + "location": "squid", + "export": "clam", + } + path = SecurityCenterClient.big_query_export_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_big_query_export_path(path) + assert expected == actual + +def test_dlp_job_path(): + project = "whelk" + dlp_job = "octopus" + expected = "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) + actual = SecurityCenterClient.dlp_job_path(project, dlp_job) + assert expected == actual + + +def test_parse_dlp_job_path(): + expected = { + "project": "oyster", + "dlp_job": "nudibranch", + } + path = SecurityCenterClient.dlp_job_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_dlp_job_path(path) + assert expected == actual + +def test_external_system_path(): + organization = "cuttlefish" + source = "mussel" + finding = "winkle" + externalsystem = "nautilus" + expected = "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) + actual = SecurityCenterClient.external_system_path(organization, source, finding, externalsystem) + assert expected == actual + + +def test_parse_external_system_path(): + expected = { + "organization": "scallop", + "source": "abalone", + "finding": "squid", + "externalsystem": "clam", + } + path = SecurityCenterClient.external_system_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_external_system_path(path) + assert expected == actual + +def test_finding_path(): + organization = "whelk" + source = "octopus" + finding = "oyster" + expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + actual = SecurityCenterClient.finding_path(organization, source, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "organization": "nudibranch", + "source": "cuttlefish", + "finding": "mussel", + } + path = SecurityCenterClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_finding_path(path) + assert expected == actual + +def test_mute_config_path(): + organization = "winkle" + mute_config = "nautilus" + expected = "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) + actual = SecurityCenterClient.mute_config_path(organization, mute_config) + assert expected == actual + + +def test_parse_mute_config_path(): + expected = { + "organization": "scallop", + "mute_config": "abalone", + } + path = SecurityCenterClient.mute_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_mute_config_path(path) + assert expected == actual + +def test_notification_config_path(): + organization = "squid" + location = "clam" + notification_config = "whelk" + expected = "organizations/{organization}/locations/{location}/notificationConfigs/{notification_config}".format(organization=organization, location=location, notification_config=notification_config, ) + actual = SecurityCenterClient.notification_config_path(organization, location, notification_config) + assert expected == actual + + +def test_parse_notification_config_path(): + expected = { + "organization": "octopus", + "location": "oyster", + "notification_config": "nudibranch", + } + path = SecurityCenterClient.notification_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_notification_config_path(path) + assert expected == actual + +def test_policy_path(): + organization = "cuttlefish" + constraint_name = "mussel" + expected = "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) + actual = SecurityCenterClient.policy_path(organization, constraint_name) + assert expected == actual + + +def test_parse_policy_path(): + expected = { + "organization": "winkle", + "constraint_name": "nautilus", + } + path = SecurityCenterClient.policy_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_policy_path(path) + assert expected == actual + +def test_resource_value_config_path(): + organization = "scallop" + resource_value_config = "abalone" + expected = "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) + actual = SecurityCenterClient.resource_value_config_path(organization, resource_value_config) + assert expected == actual + + +def test_parse_resource_value_config_path(): + expected = { + "organization": "squid", + "resource_value_config": "clam", + } + path = SecurityCenterClient.resource_value_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_resource_value_config_path(path) + assert expected == actual + +def test_security_marks_path(): + organization = "whelk" + asset = "octopus" + expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.security_marks_path(organization, asset) + assert expected == actual + + +def test_parse_security_marks_path(): + expected = { + "organization": "oyster", + "asset": "nudibranch", + } + path = SecurityCenterClient.security_marks_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_marks_path(path) + assert expected == actual + +def test_simulation_path(): + organization = "cuttlefish" + simulation = "mussel" + expected = "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) + actual = SecurityCenterClient.simulation_path(organization, simulation) + assert expected == actual + + +def test_parse_simulation_path(): + expected = { + "organization": "winkle", + "simulation": "nautilus", + } + path = SecurityCenterClient.simulation_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_simulation_path(path) + assert expected == actual + +def test_source_path(): + organization = "scallop" + source = "abalone" + expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + actual = SecurityCenterClient.source_path(organization, source) + assert expected == actual + + +def test_parse_source_path(): + expected = { + "organization": "squid", + "source": "clam", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_path(path) + assert expected == actual + +def test_table_data_profile_path(): + project = "whelk" + table_profile = "octopus" + expected = "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) + actual = SecurityCenterClient.table_data_profile_path(project, table_profile) + assert expected == actual + + +def test_parse_table_data_profile_path(): + expected = { + "project": "oyster", + "table_profile": "nudibranch", + } + path = SecurityCenterClient.table_data_profile_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_table_data_profile_path(path) + assert expected == actual + +def test_topic_path(): + project = "cuttlefish" + topic = "mussel" + expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + actual = SecurityCenterClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "winkle", + "topic": "nautilus", + } + path = SecurityCenterClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_topic_path(path) + assert expected == actual + +def test_valued_resource_path(): + organization = "scallop" + simulation = "abalone" + valued_resource = "squid" + expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) + actual = SecurityCenterClient.valued_resource_path(organization, simulation, valued_resource) + assert expected == actual + + +def test_parse_valued_resource_path(): + expected = { + "organization": "clam", + "simulation": "whelk", + "valued_resource": "octopus", + } + path = SecurityCenterClient.valued_resource_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_valued_resource_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SecurityCenterClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = SecurityCenterClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = SecurityCenterClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = SecurityCenterClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SecurityCenterClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = SecurityCenterClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = SecurityCenterClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = SecurityCenterClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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 = SecurityCenterClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = SecurityCenterClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + transport_class = SecurityCenterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations/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 = 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.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations/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 = 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_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations/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() + + # 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 + + 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(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations'}, 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() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations'} + request = request_type(**request_init) + # Mock the http request call within the method and 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.ListOperationsResponse() + + # 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), +]) +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 a89c2aad826a8c86e51bdfcba6f186570c76ef66 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 2 Aug 2024 02:00:53 +0000 Subject: [PATCH 2/4] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../v1/.coveragerc | 13 - .../google-cloud-securitycenter/v1/.flake8 | 33 - .../v1/MANIFEST.in | 2 - .../google-cloud-securitycenter/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../v1/docs/conf.py | 376 - .../v1/docs/index.rst | 7 - .../securitycenter_v1/security_center.rst | 10 - .../v1/docs/securitycenter_v1/services_.rst | 6 - .../v1/docs/securitycenter_v1/types_.rst | 6 - .../google/cloud/securitycenter/__init__.py | 343 - .../cloud/securitycenter/gapic_version.py | 16 - .../v1/google/cloud/securitycenter/py.typed | 2 - .../cloud/securitycenter_v1/__init__.py | 344 - .../securitycenter_v1/gapic_metadata.json | 973 - .../cloud/securitycenter_v1/gapic_version.py | 16 - .../google/cloud/securitycenter_v1/py.typed | 2 - .../securitycenter_v1/services/__init__.py | 15 - .../services/security_center/__init__.py | 22 - .../services/security_center/async_client.py | 7965 --- .../services/security_center/client.py | 8455 --- .../services/security_center/pagers.py | 2333 - .../security_center/transports/__init__.py | 38 - .../security_center/transports/base.py | 1251 - .../security_center/transports/grpc.py | 2103 - .../transports/grpc_asyncio.py | 2583 - .../security_center/transports/rest.py | 8529 --- .../cloud/securitycenter_v1/types/__init__.py | 440 - .../cloud/securitycenter_v1/types/access.py | 193 - .../securitycenter_v1/types/application.py | 55 - .../cloud/securitycenter_v1/types/asset.py | 227 - .../types/attack_exposure.py | 113 - .../securitycenter_v1/types/attack_path.py | 223 - .../types/backup_disaster_recovery.py | 137 - .../types/bigquery_export.py | 135 - .../securitycenter_v1/types/cloud_armor.py | 217 - .../types/cloud_dlp_data_profile.py | 71 - .../types/cloud_dlp_inspection.py | 70 - .../securitycenter_v1/types/compliance.py | 61 - .../securitycenter_v1/types/connection.py | 97 - .../types/contact_details.py | 61 - .../securitycenter_v1/types/container.py | 80 - .../cloud/securitycenter_v1/types/database.py | 98 - ...ve_event_threat_detection_custom_module.py | 113 - ...security_health_analytics_custom_module.py | 104 - .../event_threat_detection_custom_module.py | 138 - ...tection_custom_module_validation_errors.py | 123 - .../securitycenter_v1/types/exfiltration.py | 96 - .../types/external_system.py | 180 - .../cloud/securitycenter_v1/types/file.py | 113 - .../cloud/securitycenter_v1/types/finding.py | 691 - .../cloud/securitycenter_v1/types/folder.py | 54 - .../types/group_membership.py | 65 - .../securitycenter_v1/types/iam_binding.py | 77 - .../securitycenter_v1/types/indicator.py | 186 - .../securitycenter_v1/types/kernel_rootkit.py | 107 - .../securitycenter_v1/types/kubernetes.py | 398 - .../cloud/securitycenter_v1/types/label.py | 54 - .../securitycenter_v1/types/load_balancer.py | 47 - .../securitycenter_v1/types/log_entry.py | 96 - .../securitycenter_v1/types/mitre_attack.py | 334 - .../securitycenter_v1/types/mute_config.py | 123 - .../cloud/securitycenter_v1/types/notebook.py | 72 - .../types/notification_config.py | 127 - .../types/notification_message.py | 70 - .../securitycenter_v1/types/org_policy.py | 47 - .../types/organization_settings.py | 123 - .../cloud/securitycenter_v1/types/process.py | 136 - .../cloud/securitycenter_v1/types/resource.py | 474 - .../types/resource_value_config.py | 189 - .../types/run_asset_discovery_response.py | 76 - ...security_health_analytics_custom_config.py | 173 - ...security_health_analytics_custom_module.py | 138 - .../securitycenter_v1/types/security_marks.py | 80 - .../types/security_posture.py | 128 - .../types/securitycenter_service.py | 3494 -- .../securitycenter_v1/types/simulation.py | 73 - .../cloud/securitycenter_v1/types/source.py | 88 - .../types/toxic_combination.py | 60 - .../types/valued_resource.py | 126 - .../securitycenter_v1/types/vulnerability.py | 538 - .../google-cloud-securitycenter/v1/mypy.ini | 3 - .../google-cloud-securitycenter/v1/noxfile.py | 280 - ...tch_create_resource_value_configs_async.py | 58 - ...atch_create_resource_value_configs_sync.py | 58 - ...ecurity_center_bulk_mute_findings_async.py | 56 - ...security_center_bulk_mute_findings_sync.py | 56 - ...ty_center_create_big_query_export_async.py | 53 - ...ity_center_create_big_query_export_sync.py | 53 - ...nt_threat_detection_custom_module_async.py | 52 - ...ent_threat_detection_custom_module_sync.py | 52 - ...ed_security_center_create_finding_async.py | 53 - ...ted_security_center_create_finding_sync.py | 53 - ...ecurity_center_create_mute_config_async.py | 57 - ...security_center_create_mute_config_sync.py | 57 - ...center_create_notification_config_async.py | 53 - ..._center_create_notification_config_sync.py | 53 - ...ty_health_analytics_custom_module_async.py | 52 - ...ity_health_analytics_custom_module_sync.py | 52 - ...ted_security_center_create_source_async.py | 52 - ...ated_security_center_create_source_sync.py | 52 - ...ty_center_delete_big_query_export_async.py | 50 - ...ity_center_delete_big_query_export_sync.py | 50 - ...nt_threat_detection_custom_module_async.py | 50 - ...ent_threat_detection_custom_module_sync.py | 50 - ...ecurity_center_delete_mute_config_async.py | 50 - ...security_center_delete_mute_config_sync.py | 50 - ...center_delete_notification_config_async.py | 50 - ..._center_delete_notification_config_sync.py | 50 - ...nter_delete_resource_value_config_async.py | 50 - ...enter_delete_resource_value_config_sync.py | 50 - ...ty_health_analytics_custom_module_async.py | 50 - ...ity_health_analytics_custom_module_sync.py | 50 - ...urity_center_get_big_query_export_async.py | 52 - ...curity_center_get_big_query_export_sync.py | 52 - ...nt_threat_detection_custom_module_async.py | 52 - ...ent_threat_detection_custom_module_sync.py | 52 - ...ty_health_analytics_custom_module_async.py | 52 - ...ity_health_analytics_custom_module_sync.py | 52 - ...nt_threat_detection_custom_module_async.py | 52 - ...ent_threat_detection_custom_module_sync.py | 52 - ...ed_security_center_get_iam_policy_async.py | 53 - ...ted_security_center_get_iam_policy_sync.py | 53 - ...d_security_center_get_mute_config_async.py | 52 - ...ed_security_center_get_mute_config_sync.py | 52 - ...ty_center_get_notification_config_async.py | 52 - ...ity_center_get_notification_config_sync.py | 52 - ..._center_get_organization_settings_async.py | 52 - ...y_center_get_organization_settings_sync.py | 52 - ..._center_get_resource_value_config_async.py | 52 - ...y_center_get_resource_value_config_sync.py | 52 - ...ty_health_analytics_custom_module_async.py | 52 - ...ity_health_analytics_custom_module_sync.py | 52 - ...ed_security_center_get_simulation_async.py | 52 - ...ted_security_center_get_simulation_sync.py | 52 - ...erated_security_center_get_source_async.py | 52 - ...nerated_security_center_get_source_sync.py | 52 - ...curity_center_get_valued_resource_async.py | 52 - ...ecurity_center_get_valued_resource_sync.py | 52 - ...ated_security_center_group_assets_async.py | 54 - ...rated_security_center_group_assets_sync.py | 54 - ...ed_security_center_group_findings_async.py | 54 - ...ted_security_center_group_findings_sync.py | 54 - ...rated_security_center_list_assets_async.py | 53 - ...erated_security_center_list_assets_sync.py | 53 - ...security_center_list_attack_paths_async.py | 53 - ..._security_center_list_attack_paths_sync.py | 53 - ...ity_center_list_big_query_exports_async.py | 53 - ...rity_center_list_big_query_exports_sync.py | 53 - ...t_threat_detection_custom_modules_async.py | 53 - ...nt_threat_detection_custom_modules_sync.py | 53 - ...y_health_analytics_custom_modules_async.py | 53 - ...ty_health_analytics_custom_modules_sync.py | 53 - ...t_threat_detection_custom_modules_async.py | 53 - ...nt_threat_detection_custom_modules_sync.py | 53 - ...y_health_analytics_custom_modules_async.py | 53 - ...ty_health_analytics_custom_modules_sync.py | 53 - ...t_threat_detection_custom_modules_async.py | 53 - ...nt_threat_detection_custom_modules_sync.py | 53 - ...ted_security_center_list_findings_async.py | 53 - ...ated_security_center_list_findings_sync.py | 53 - ...security_center_list_mute_configs_async.py | 53 - ..._security_center_list_mute_configs_sync.py | 53 - ..._center_list_notification_configs_async.py | 53 - ...y_center_list_notification_configs_sync.py | 53 - ...enter_list_resource_value_configs_async.py | 53 - ...center_list_resource_value_configs_sync.py | 53 - ...y_health_analytics_custom_modules_async.py | 53 - ...ty_health_analytics_custom_modules_sync.py | 53 - ...ated_security_center_list_sources_async.py | 53 - ...rated_security_center_list_sources_sync.py | 53 - ...rity_center_list_valued_resources_async.py | 53 - ...urity_center_list_valued_resources_sync.py | 53 - ...curity_center_run_asset_discovery_async.py | 56 - ...ecurity_center_run_asset_discovery_sync.py | 56 - ...security_center_set_finding_state_async.py | 53 - ..._security_center_set_finding_state_sync.py | 53 - ...ed_security_center_set_iam_policy_async.py | 53 - ...ted_security_center_set_iam_policy_sync.py | 53 - ...enerated_security_center_set_mute_async.py | 53 - ...generated_security_center_set_mute_sync.py | 53 - ...ty_health_analytics_custom_module_async.py | 56 - ...ity_health_analytics_custom_module_sync.py | 56 - ...urity_center_test_iam_permissions_async.py | 54 - ...curity_center_test_iam_permissions_sync.py | 54 - ...ty_center_update_big_query_export_async.py | 51 - ...ity_center_update_big_query_export_sync.py | 51 - ...nt_threat_detection_custom_module_async.py | 51 - ...ent_threat_detection_custom_module_sync.py | 51 - ...ity_center_update_external_system_async.py | 51 - ...rity_center_update_external_system_sync.py | 51 - ...ed_security_center_update_finding_async.py | 51 - ...ted_security_center_update_finding_sync.py | 51 - ...ecurity_center_update_mute_config_async.py | 55 - ...security_center_update_mute_config_sync.py | 55 - ...center_update_notification_config_async.py | 51 - ..._center_update_notification_config_sync.py | 51 - ...nter_update_organization_settings_async.py | 51 - ...enter_update_organization_settings_sync.py | 51 - ...nter_update_resource_value_config_async.py | 56 - ...enter_update_resource_value_config_sync.py | 56 - ...ty_health_analytics_custom_module_async.py | 51 - ...ity_health_analytics_custom_module_sync.py | 51 - ...rity_center_update_security_marks_async.py | 51 - ...urity_center_update_security_marks_sync.py | 51 - ...ted_security_center_update_source_async.py | 51 - ...ated_security_center_update_source_sync.py | 51 - ...nt_threat_detection_custom_module_async.py | 54 - ...ent_threat_detection_custom_module_sync.py | 54 - ...tadata_google.cloud.securitycenter.v1.json | 10298 ---- .../fixup_securitycenter_v1_keywords.py | 238 - .../google-cloud-securitycenter/v1/setup.py | 94 - .../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/securitycenter_v1/__init__.py | 16 - .../securitycenter_v1/test_security_center.py | 48250 ---------------- .../v1beta1/.coveragerc | 13 - .../v1beta1/.flake8 | 33 - .../v1beta1/MANIFEST.in | 2 - .../v1beta1/README.rst | 49 - .../v1beta1/docs/_static/custom.css | 3 - .../v1beta1/docs/conf.py | 376 - .../v1beta1/docs/index.rst | 7 - .../security_center.rst | 10 - .../docs/securitycenter_v1beta1/services_.rst | 6 - .../docs/securitycenter_v1beta1/types_.rst | 6 - .../google/cloud/securitycenter/__init__.py | 81 - .../cloud/securitycenter/gapic_version.py | 16 - .../google/cloud/securitycenter/py.typed | 2 - .../cloud/securitycenter_v1beta1/__init__.py | 82 - .../gapic_metadata.json | 298 - .../securitycenter_v1beta1/gapic_version.py | 16 - .../cloud/securitycenter_v1beta1/py.typed | 2 - .../services/__init__.py | 15 - .../services/security_center/__init__.py | 22 - .../services/security_center/async_client.py | 2364 - .../services/security_center/client.py | 2755 - .../services/security_center/pagers.py | 704 - .../security_center/transports/__init__.py | 38 - .../security_center/transports/base.py | 498 - .../security_center/transports/grpc.py | 760 - .../transports/grpc_asyncio.py | 945 - .../security_center/transports/rest.py | 2542 - .../securitycenter_v1beta1/types/__init__.py | 86 - .../securitycenter_v1beta1/types/asset.py | 155 - .../securitycenter_v1beta1/types/finding.py | 165 - .../types/organization_settings.py | 115 - .../types/run_asset_discovery_response.py | 76 - .../types/security_marks.py | 68 - .../types/securitycenter_service.py | 1053 - .../securitycenter_v1beta1/types/source.py | 77 - .../v1beta1/mypy.ini | 3 - .../v1beta1/noxfile.py | 280 - ...ed_security_center_create_finding_async.py | 53 - ...ted_security_center_create_finding_sync.py | 53 - ...ted_security_center_create_source_async.py | 52 - ...ated_security_center_create_source_sync.py | 52 - ...ed_security_center_get_iam_policy_async.py | 53 - ...ted_security_center_get_iam_policy_sync.py | 53 - ..._center_get_organization_settings_async.py | 52 - ...y_center_get_organization_settings_sync.py | 52 - ...erated_security_center_get_source_async.py | 52 - ...nerated_security_center_get_source_sync.py | 52 - ...ated_security_center_group_assets_async.py | 54 - ...rated_security_center_group_assets_sync.py | 54 - ...ed_security_center_group_findings_async.py | 54 - ...ted_security_center_group_findings_sync.py | 54 - ...rated_security_center_list_assets_async.py | 53 - ...erated_security_center_list_assets_sync.py | 53 - ...ted_security_center_list_findings_async.py | 53 - ...ated_security_center_list_findings_sync.py | 53 - ...ated_security_center_list_sources_async.py | 53 - ...rated_security_center_list_sources_sync.py | 53 - ...curity_center_run_asset_discovery_async.py | 56 - ...ecurity_center_run_asset_discovery_sync.py | 56 - ...security_center_set_finding_state_async.py | 53 - ..._security_center_set_finding_state_sync.py | 53 - ...ed_security_center_set_iam_policy_async.py | 53 - ...ted_security_center_set_iam_policy_sync.py | 53 - ...urity_center_test_iam_permissions_async.py | 54 - ...curity_center_test_iam_permissions_sync.py | 54 - ...ed_security_center_update_finding_async.py | 51 - ...ted_security_center_update_finding_sync.py | 51 - ...nter_update_organization_settings_async.py | 51 - ...enter_update_organization_settings_sync.py | 51 - ...rity_center_update_security_marks_async.py | 51 - ...urity_center_update_security_marks_sync.py | 51 - ...ted_security_center_update_source_async.py | 51 - ...ated_security_center_update_source_sync.py | 51 - ...a_google.cloud.securitycenter.v1beta1.json | 2945 - .../fixup_securitycenter_v1beta1_keywords.py | 193 - .../v1beta1/setup.py | 94 - .../v1beta1/testing/constraints-3.10.txt | 7 - .../v1beta1/testing/constraints-3.11.txt | 7 - .../v1beta1/testing/constraints-3.12.txt | 7 - .../v1beta1/testing/constraints-3.7.txt | 11 - .../v1beta1/testing/constraints-3.8.txt | 7 - .../v1beta1/testing/constraints-3.9.txt | 7 - .../v1beta1/tests/__init__.py | 16 - .../v1beta1/tests/unit/__init__.py | 16 - .../v1beta1/tests/unit/gapic/__init__.py | 16 - .../gapic/securitycenter_v1beta1/__init__.py | 16 - .../test_security_center.py | 14372 ----- .../v1p1beta1/.coveragerc | 13 - .../v1p1beta1/.flake8 | 33 - .../v1p1beta1/MANIFEST.in | 2 - .../v1p1beta1/README.rst | 49 - .../v1p1beta1/docs/_static/custom.css | 3 - .../v1p1beta1/docs/conf.py | 376 - .../v1p1beta1/docs/index.rst | 7 - .../security_center.rst | 10 - .../securitycenter_v1p1beta1/services_.rst | 6 - .../docs/securitycenter_v1p1beta1/types_.rst | 6 - .../google/cloud/securitycenter/__init__.py | 101 - .../cloud/securitycenter/gapic_version.py | 16 - .../google/cloud/securitycenter/py.typed | 2 - .../securitycenter_v1p1beta1/__init__.py | 102 - .../gapic_metadata.json | 373 - .../securitycenter_v1p1beta1/gapic_version.py | 16 - .../cloud/securitycenter_v1p1beta1/py.typed | 2 - .../services/__init__.py | 15 - .../services/security_center/__init__.py | 22 - .../services/security_center/async_client.py | 3039 - .../services/security_center/client.py | 3441 -- .../services/security_center/pagers.py | 839 - .../security_center/transports/__init__.py | 38 - .../security_center/transports/base.py | 591 - .../security_center/transports/grpc.py | 895 - .../transports/grpc_asyncio.py | 1125 - .../security_center/transports/rest.py | 3197 - .../types/__init__.py | 114 - .../securitycenter_v1p1beta1/types/asset.py | 227 - .../securitycenter_v1p1beta1/types/finding.py | 209 - .../securitycenter_v1p1beta1/types/folder.py | 54 - .../types/notification_config.py | 143 - .../types/notification_message.py | 69 - .../types/organization_settings.py | 123 - .../types/resource.py | 85 - .../types/run_asset_discovery_response.py | 76 - .../types/security_marks.py | 80 - .../types/securitycenter_service.py | 1641 - .../securitycenter_v1p1beta1/types/source.py | 88 - .../v1p1beta1/mypy.ini | 3 - .../v1p1beta1/noxfile.py | 280 - ...ed_security_center_create_finding_async.py | 53 - ...ted_security_center_create_finding_sync.py | 53 - ...center_create_notification_config_async.py | 53 - ..._center_create_notification_config_sync.py | 53 - ...ted_security_center_create_source_async.py | 52 - ...ated_security_center_create_source_sync.py | 52 - ...center_delete_notification_config_async.py | 50 - ..._center_delete_notification_config_sync.py | 50 - ...ed_security_center_get_iam_policy_async.py | 53 - ...ted_security_center_get_iam_policy_sync.py | 53 - ...ty_center_get_notification_config_async.py | 52 - ...ity_center_get_notification_config_sync.py | 52 - ..._center_get_organization_settings_async.py | 52 - ...y_center_get_organization_settings_sync.py | 52 - ...erated_security_center_get_source_async.py | 52 - ...nerated_security_center_get_source_sync.py | 52 - ...ated_security_center_group_assets_async.py | 54 - ...rated_security_center_group_assets_sync.py | 54 - ...ed_security_center_group_findings_async.py | 54 - ...ted_security_center_group_findings_sync.py | 54 - ...rated_security_center_list_assets_async.py | 53 - ...erated_security_center_list_assets_sync.py | 53 - ...ted_security_center_list_findings_async.py | 53 - ...ated_security_center_list_findings_sync.py | 53 - ..._center_list_notification_configs_async.py | 53 - ...y_center_list_notification_configs_sync.py | 53 - ...ated_security_center_list_sources_async.py | 53 - ...rated_security_center_list_sources_sync.py | 53 - ...curity_center_run_asset_discovery_async.py | 56 - ...ecurity_center_run_asset_discovery_sync.py | 56 - ...security_center_set_finding_state_async.py | 53 - ..._security_center_set_finding_state_sync.py | 53 - ...ed_security_center_set_iam_policy_async.py | 53 - ...ted_security_center_set_iam_policy_sync.py | 53 - ...urity_center_test_iam_permissions_async.py | 54 - ...curity_center_test_iam_permissions_sync.py | 54 - ...ed_security_center_update_finding_async.py | 51 - ...ted_security_center_update_finding_sync.py | 51 - ...center_update_notification_config_async.py | 51 - ..._center_update_notification_config_sync.py | 51 - ...nter_update_organization_settings_async.py | 51 - ...enter_update_organization_settings_sync.py | 51 - ...rity_center_update_security_marks_async.py | 51 - ...urity_center_update_security_marks_sync.py | 51 - ...ted_security_center_update_source_async.py | 51 - ...ated_security_center_update_source_sync.py | 51 - ...google.cloud.securitycenter.v1p1beta1.json | 3808 -- ...fixup_securitycenter_v1p1beta1_keywords.py | 198 - .../v1p1beta1/setup.py | 94 - .../v1p1beta1/testing/constraints-3.10.txt | 7 - .../v1p1beta1/testing/constraints-3.11.txt | 7 - .../v1p1beta1/testing/constraints-3.12.txt | 7 - .../v1p1beta1/testing/constraints-3.7.txt | 11 - .../v1p1beta1/testing/constraints-3.8.txt | 7 - .../v1p1beta1/testing/constraints-3.9.txt | 7 - .../v1p1beta1/tests/__init__.py | 16 - .../v1p1beta1/tests/unit/__init__.py | 16 - .../v1p1beta1/tests/unit/gapic/__init__.py | 16 - .../securitycenter_v1p1beta1/__init__.py | 16 - .../test_security_center.py | 18405 ------ .../v2/.coveragerc | 13 - .../google-cloud-securitycenter/v2/.flake8 | 33 - .../v2/MANIFEST.in | 2 - .../google-cloud-securitycenter/v2/README.rst | 49 - .../v2/docs/_static/custom.css | 3 - .../v2/docs/conf.py | 376 - .../v2/docs/index.rst | 7 - .../securitycenter_v2/security_center.rst | 10 - .../v2/docs/securitycenter_v2/services_.rst | 6 - .../v2/docs/securitycenter_v2/types_.rst | 6 - .../google/cloud/securitycenter/__init__.py | 257 - .../cloud/securitycenter/gapic_version.py | 16 - .../v2/google/cloud/securitycenter/py.typed | 2 - .../cloud/securitycenter_v2/__init__.py | 258 - .../securitycenter_v2/gapic_metadata.json | 628 - .../cloud/securitycenter_v2/gapic_version.py | 16 - .../google/cloud/securitycenter_v2/py.typed | 2 - .../securitycenter_v2/services/__init__.py | 15 - .../services/security_center/__init__.py | 22 - .../services/security_center/async_client.py | 5422 -- .../services/security_center/client.py | 5948 -- .../services/security_center/pagers.py | 1249 - .../security_center/transports/__init__.py | 38 - .../security_center/transports/base.py | 761 - .../security_center/transports/grpc.py | 1452 - .../transports/grpc_asyncio.py | 1657 - .../security_center/transports/rest.py | 5820 -- .../cloud/securitycenter_v2/types/__init__.py | 336 - .../cloud/securitycenter_v2/types/access.py | 193 - .../securitycenter_v2/types/application.py | 55 - .../types/attack_exposure.py | 113 - .../securitycenter_v2/types/attack_path.py | 223 - .../types/backup_disaster_recovery.py | 137 - .../types/bigquery_export.py | 141 - .../securitycenter_v2/types/cloud_armor.py | 217 - .../types/cloud_dlp_data_profile.py | 71 - .../types/cloud_dlp_inspection.py | 70 - .../securitycenter_v2/types/compliance.py | 61 - .../securitycenter_v2/types/connection.py | 97 - .../types/contact_details.py | 61 - .../securitycenter_v2/types/container.py | 80 - .../cloud/securitycenter_v2/types/database.py | 98 - .../securitycenter_v2/types/exfiltration.py | 96 - .../types/external_system.py | 192 - .../cloud/securitycenter_v2/types/file.py | 113 - .../cloud/securitycenter_v2/types/finding.py | 808 - .../cloud/securitycenter_v2/types/folder.py | 54 - .../types/group_membership.py | 65 - .../securitycenter_v2/types/iam_binding.py | 77 - .../securitycenter_v2/types/indicator.py | 186 - .../securitycenter_v2/types/kernel_rootkit.py | 107 - .../securitycenter_v2/types/kubernetes.py | 398 - .../cloud/securitycenter_v2/types/label.py | 54 - .../securitycenter_v2/types/load_balancer.py | 47 - .../securitycenter_v2/types/log_entry.py | 95 - .../securitycenter_v2/types/mitre_attack.py | 340 - .../securitycenter_v2/types/mute_config.py | 166 - .../cloud/securitycenter_v2/types/notebook.py | 72 - .../types/notification_config.py | 129 - .../types/notification_message.py | 70 - .../securitycenter_v2/types/org_policy.py | 47 - .../cloud/securitycenter_v2/types/process.py | 136 - .../cloud/securitycenter_v2/types/resource.py | 493 - .../types/resource_value_config.py | 190 - .../securitycenter_v2/types/security_marks.py | 101 - .../types/security_posture.py | 128 - .../types/securitycenter_service.py | 1932 - .../securitycenter_v2/types/simulation.py | 73 - .../cloud/securitycenter_v2/types/source.py | 88 - .../types/toxic_combination.py | 60 - .../types/valued_resource.py | 126 - .../securitycenter_v2/types/vulnerability.py | 546 - .../google-cloud-securitycenter/v2/mypy.ini | 3 - .../google-cloud-securitycenter/v2/noxfile.py | 280 - ...tch_create_resource_value_configs_async.py | 56 - ...atch_create_resource_value_configs_sync.py | 56 - ...ecurity_center_bulk_mute_findings_async.py | 56 - ...security_center_bulk_mute_findings_sync.py | 56 - ...ty_center_create_big_query_export_async.py | 53 - ...ity_center_create_big_query_export_sync.py | 53 - ...ed_security_center_create_finding_async.py | 53 - ...ted_security_center_create_finding_sync.py | 53 - ...ecurity_center_create_mute_config_async.py | 58 - ...security_center_create_mute_config_sync.py | 58 - ...center_create_notification_config_async.py | 53 - ..._center_create_notification_config_sync.py | 53 - ...ted_security_center_create_source_async.py | 52 - ...ated_security_center_create_source_sync.py | 52 - ...ty_center_delete_big_query_export_async.py | 50 - ...ity_center_delete_big_query_export_sync.py | 50 - ...ecurity_center_delete_mute_config_async.py | 50 - ...security_center_delete_mute_config_sync.py | 50 - ...center_delete_notification_config_async.py | 50 - ..._center_delete_notification_config_sync.py | 50 - ...nter_delete_resource_value_config_async.py | 50 - ...enter_delete_resource_value_config_sync.py | 50 - ...urity_center_get_big_query_export_async.py | 52 - ...curity_center_get_big_query_export_sync.py | 52 - ...ed_security_center_get_iam_policy_async.py | 53 - ...ted_security_center_get_iam_policy_sync.py | 53 - ...d_security_center_get_mute_config_async.py | 52 - ...ed_security_center_get_mute_config_sync.py | 52 - ...ty_center_get_notification_config_async.py | 52 - ...ity_center_get_notification_config_sync.py | 52 - ..._center_get_resource_value_config_async.py | 52 - ...y_center_get_resource_value_config_sync.py | 52 - ...ed_security_center_get_simulation_async.py | 52 - ...ted_security_center_get_simulation_sync.py | 52 - ...erated_security_center_get_source_async.py | 52 - ...nerated_security_center_get_source_sync.py | 52 - ...curity_center_get_valued_resource_async.py | 52 - ...ecurity_center_get_valued_resource_sync.py | 52 - ...ed_security_center_group_findings_async.py | 54 - ...ted_security_center_group_findings_sync.py | 54 - ...security_center_list_attack_paths_async.py | 53 - ..._security_center_list_attack_paths_sync.py | 53 - ...ity_center_list_big_query_exports_async.py | 53 - ...rity_center_list_big_query_exports_sync.py | 53 - ...ted_security_center_list_findings_async.py | 53 - ...ated_security_center_list_findings_sync.py | 53 - ...security_center_list_mute_configs_async.py | 53 - ..._security_center_list_mute_configs_sync.py | 53 - ..._center_list_notification_configs_async.py | 53 - ...y_center_list_notification_configs_sync.py | 53 - ...enter_list_resource_value_configs_async.py | 53 - ...center_list_resource_value_configs_sync.py | 53 - ...ated_security_center_list_sources_async.py | 53 - ...rated_security_center_list_sources_sync.py | 53 - ...rity_center_list_valued_resources_async.py | 53 - ...urity_center_list_valued_resources_sync.py | 53 - ...security_center_set_finding_state_async.py | 53 - ..._security_center_set_finding_state_sync.py | 53 - ...ed_security_center_set_iam_policy_async.py | 53 - ...ted_security_center_set_iam_policy_sync.py | 53 - ...enerated_security_center_set_mute_async.py | 53 - ...generated_security_center_set_mute_sync.py | 53 - ...urity_center_test_iam_permissions_async.py | 54 - ...curity_center_test_iam_permissions_sync.py | 54 - ...ty_center_update_big_query_export_async.py | 51 - ...ity_center_update_big_query_export_sync.py | 51 - ...ity_center_update_external_system_async.py | 51 - ...rity_center_update_external_system_sync.py | 51 - ...ed_security_center_update_finding_async.py | 51 - ...ted_security_center_update_finding_sync.py | 51 - ...ecurity_center_update_mute_config_async.py | 56 - ...security_center_update_mute_config_sync.py | 56 - ...center_update_notification_config_async.py | 51 - ..._center_update_notification_config_sync.py | 51 - ...nter_update_resource_value_config_async.py | 51 - ...enter_update_resource_value_config_sync.py | 51 - ...rity_center_update_security_marks_async.py | 51 - ...urity_center_update_security_marks_sync.py | 51 - ...ted_security_center_update_source_async.py | 51 - ...ated_security_center_update_source_sync.py | 51 - ...tadata_google.cloud.securitycenter.v2.json | 6607 --- .../fixup_securitycenter_v2_keywords.py | 215 - .../google-cloud-securitycenter/v2/setup.py | 94 - .../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 - .../v2/tests/__init__.py | 16 - .../v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/securitycenter_v2/__init__.py | 16 - .../securitycenter_v2/test_security_center.py | 31716 ---------- .../cloud/securitycenter/gapic_version.py | 2 +- .../cloud/securitycenter_v1/gapic_version.py | 2 +- .../securitycenter_v1beta1/gapic_version.py | 2 +- .../securitycenter_v1p1beta1/gapic_version.py | 2 +- .../cloud/securitycenter_v2/gapic_version.py | 2 +- .../services/security_center/async_client.py | 79 +- .../services/security_center/client.py | 79 +- .../types/attack_exposure.py | 8 +- .../securitycenter_v2/types/attack_path.py | 9 +- .../types/bigquery_export.py | 4 +- .../cloud/securitycenter_v2/types/finding.py | 85 + .../securitycenter_v2/types/mitre_attack.py | 10 +- .../securitycenter_v2/types/mute_config.py | 26 +- .../types/notification_config.py | 3 +- .../cloud/securitycenter_v2/types/resource.py | 14 +- .../types/resource_value_config.py | 32 +- .../types/securitycenter_service.py | 103 +- .../securitycenter_v2/types/simulation.py | 3 +- .../securitycenter_v2/types/vulnerability.py | 8 + ...tch_create_resource_value_configs_async.py | 1 - ...atch_create_resource_value_configs_sync.py | 1 - ...ecurity_center_create_mute_config_async.py | 2 +- ...security_center_create_mute_config_sync.py | 2 +- ...ecurity_center_update_mute_config_async.py | 2 +- ...security_center_update_mute_config_sync.py | 2 +- ...nter_update_resource_value_config_async.py | 4 - ...enter_update_resource_value_config_sync.py | 4 - ...tadata_google.cloud.securitycenter.v1.json | 2 +- ...a_google.cloud.securitycenter.v1beta1.json | 2 +- ...google.cloud.securitycenter.v1p1beta1.json | 2 +- ...tadata_google.cloud.securitycenter.v2.json | 58 +- .../fixup_securitycenter_v2_keywords.py | 2 +- .../securitycenter_v2/test_security_center.py | 16 + 612 files changed, 358 insertions(+), 265318 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/setup.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/setup.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/.flake8 delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/README.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/setup.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc deleted file mode 100644 index 45cb273f8f7c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/securitycenter/__init__.py - google/cloud/securitycenter/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-securitycenter/v1/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v1/MANIFEST.in deleted file mode 100644 index a18e3d0b6821..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/securitycenter *.py -recursive-include google/cloud/securitycenter_v1 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/README.rst b/owl-bot-staging/google-cloud-securitycenter/v1/README.rst deleted file mode 100644 index f8c63f4cb48a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v1/docs/conf.py deleted file mode 100644 index 8e92d2319721..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter 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-securitycenter" -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-securitycenter-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-securitycenter.tex", - u"google-cloud-securitycenter 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-securitycenter", - u"Google Cloud Securitycenter 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-securitycenter", - u"google-cloud-securitycenter Documentation", - author, - "google-cloud-securitycenter", - "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v1/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/index.rst deleted file mode 100644 index 47fc2db7cc98..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - securitycenter_v1/services - securitycenter_v1/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst deleted file mode 100644 index bc6175c8b5cc..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst +++ /dev/null @@ -1,10 +0,0 @@ -SecurityCenter --------------------------------- - -.. automodule:: google.cloud.securitycenter_v1.services.security_center - :members: - :inherited-members: - -.. automodule:: google.cloud.securitycenter_v1.services.security_center.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst deleted file mode 100644 index 295acede4385..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Securitycenter v1 API -=============================================== -.. toctree:: - :maxdepth: 2 - - security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst deleted file mode 100644 index f7497757d041..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Securitycenter v1 API -============================================ - -.. automodule:: google.cloud.securitycenter_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.py deleted file mode 100644 index 7c15b78219eb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.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. -# -from google.cloud.securitycenter import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.securitycenter_v1.services.security_center.client import SecurityCenterClient -from google.cloud.securitycenter_v1.services.security_center.async_client import SecurityCenterAsyncClient - -from google.cloud.securitycenter_v1.types.access import Access -from google.cloud.securitycenter_v1.types.access import Geolocation -from google.cloud.securitycenter_v1.types.access import ServiceAccountDelegationInfo -from google.cloud.securitycenter_v1.types.application import Application -from google.cloud.securitycenter_v1.types.asset import Asset -from google.cloud.securitycenter_v1.types.attack_exposure import AttackExposure -from google.cloud.securitycenter_v1.types.attack_path import AttackPath -from google.cloud.securitycenter_v1.types.backup_disaster_recovery import BackupDisasterRecovery -from google.cloud.securitycenter_v1.types.bigquery_export import BigQueryExport -from google.cloud.securitycenter_v1.types.cloud_armor import AdaptiveProtection -from google.cloud.securitycenter_v1.types.cloud_armor import Attack -from google.cloud.securitycenter_v1.types.cloud_armor import CloudArmor -from google.cloud.securitycenter_v1.types.cloud_armor import Requests -from google.cloud.securitycenter_v1.types.cloud_armor import SecurityPolicy -from google.cloud.securitycenter_v1.types.cloud_dlp_data_profile import CloudDlpDataProfile -from google.cloud.securitycenter_v1.types.cloud_dlp_inspection import CloudDlpInspection -from google.cloud.securitycenter_v1.types.compliance import Compliance -from google.cloud.securitycenter_v1.types.connection import Connection -from google.cloud.securitycenter_v1.types.contact_details import Contact -from google.cloud.securitycenter_v1.types.contact_details import ContactDetails -from google.cloud.securitycenter_v1.types.container import Container -from google.cloud.securitycenter_v1.types.database import Database -from google.cloud.securitycenter_v1.types.effective_event_threat_detection_custom_module import EffectiveEventThreatDetectionCustomModule -from google.cloud.securitycenter_v1.types.effective_security_health_analytics_custom_module import EffectiveSecurityHealthAnalyticsCustomModule -from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module import EventThreatDetectionCustomModule -from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationError -from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationErrors -from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module_validation_errors import Position -from google.cloud.securitycenter_v1.types.exfiltration import ExfilResource -from google.cloud.securitycenter_v1.types.exfiltration import Exfiltration -from google.cloud.securitycenter_v1.types.external_system import ExternalSystem -from google.cloud.securitycenter_v1.types.file import File -from google.cloud.securitycenter_v1.types.finding import Finding -from google.cloud.securitycenter_v1.types.folder import Folder -from google.cloud.securitycenter_v1.types.group_membership import GroupMembership -from google.cloud.securitycenter_v1.types.iam_binding import IamBinding -from google.cloud.securitycenter_v1.types.indicator import Indicator -from google.cloud.securitycenter_v1.types.kernel_rootkit import KernelRootkit -from google.cloud.securitycenter_v1.types.kubernetes import Kubernetes -from google.cloud.securitycenter_v1.types.label import Label -from google.cloud.securitycenter_v1.types.load_balancer import LoadBalancer -from google.cloud.securitycenter_v1.types.log_entry import CloudLoggingEntry -from google.cloud.securitycenter_v1.types.log_entry import LogEntry -from google.cloud.securitycenter_v1.types.mitre_attack import MitreAttack -from google.cloud.securitycenter_v1.types.mute_config import MuteConfig -from google.cloud.securitycenter_v1.types.notebook import Notebook -from google.cloud.securitycenter_v1.types.notification_config import NotificationConfig -from google.cloud.securitycenter_v1.types.notification_message import NotificationMessage -from google.cloud.securitycenter_v1.types.org_policy import OrgPolicy -from google.cloud.securitycenter_v1.types.organization_settings import OrganizationSettings -from google.cloud.securitycenter_v1.types.process import EnvironmentVariable -from google.cloud.securitycenter_v1.types.process import Process -from google.cloud.securitycenter_v1.types.resource import AwsMetadata -from google.cloud.securitycenter_v1.types.resource import AzureMetadata -from google.cloud.securitycenter_v1.types.resource import Resource -from google.cloud.securitycenter_v1.types.resource import ResourcePath -from google.cloud.securitycenter_v1.types.resource import CloudProvider -from google.cloud.securitycenter_v1.types.resource_value_config import ResourceValueConfig -from google.cloud.securitycenter_v1.types.resource_value_config import ResourceValue -from google.cloud.securitycenter_v1.types.run_asset_discovery_response import RunAssetDiscoveryResponse -from google.cloud.securitycenter_v1.types.security_health_analytics_custom_config import CustomConfig -from google.cloud.securitycenter_v1.types.security_health_analytics_custom_module import SecurityHealthAnalyticsCustomModule -from google.cloud.securitycenter_v1.types.security_marks import SecurityMarks -from google.cloud.securitycenter_v1.types.security_posture import SecurityPosture -from google.cloud.securitycenter_v1.types.securitycenter_service import BatchCreateResourceValueConfigsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import BatchCreateResourceValueConfigsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import BulkMuteFindingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import BulkMuteFindingsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateBigQueryExportRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateEventThreatDetectionCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateFindingRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateMuteConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateNotificationConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateResourceValueConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateSecurityHealthAnalyticsCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateSourceRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteBigQueryExportRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteEventThreatDetectionCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteMuteConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteNotificationConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteResourceValueConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteSecurityHealthAnalyticsCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetBigQueryExportRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetEffectiveEventThreatDetectionCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetEffectiveSecurityHealthAnalyticsCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetEventThreatDetectionCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetMuteConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetNotificationConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetOrganizationSettingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetResourceValueConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetSecurityHealthAnalyticsCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetSimulationRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetSourceRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetValuedResourceRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupAssetsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupAssetsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupFindingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupFindingsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupResult -from google.cloud.securitycenter_v1.types.securitycenter_service import ListAssetsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListAssetsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListAttackPathsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListAttackPathsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListBigQueryExportsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListBigQueryExportsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListEventThreatDetectionCustomModulesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListEventThreatDetectionCustomModulesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListFindingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListFindingsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListMuteConfigsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListMuteConfigsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListNotificationConfigsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListNotificationConfigsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListResourceValueConfigsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListResourceValueConfigsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListSourcesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListSourcesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListValuedResourcesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListValuedResourcesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import RunAssetDiscoveryRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import SetFindingStateRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import SetMuteRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateBigQueryExportRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateEventThreatDetectionCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateExternalSystemRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateFindingRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateMuteConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateNotificationConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateOrganizationSettingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateResourceValueConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSecurityHealthAnalyticsCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSecurityMarksRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSourceRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ValidateEventThreatDetectionCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ValidateEventThreatDetectionCustomModuleResponse -from google.cloud.securitycenter_v1.types.simulation import Simulation -from google.cloud.securitycenter_v1.types.source import Source -from google.cloud.securitycenter_v1.types.toxic_combination import ToxicCombination -from google.cloud.securitycenter_v1.types.valued_resource import ResourceValueConfigMetadata -from google.cloud.securitycenter_v1.types.valued_resource import ValuedResource -from google.cloud.securitycenter_v1.types.vulnerability import Cve -from google.cloud.securitycenter_v1.types.vulnerability import Cvssv3 -from google.cloud.securitycenter_v1.types.vulnerability import Package -from google.cloud.securitycenter_v1.types.vulnerability import Reference -from google.cloud.securitycenter_v1.types.vulnerability import SecurityBulletin -from google.cloud.securitycenter_v1.types.vulnerability import Vulnerability - -__all__ = ('SecurityCenterClient', - 'SecurityCenterAsyncClient', - 'Access', - 'Geolocation', - 'ServiceAccountDelegationInfo', - 'Application', - 'Asset', - 'AttackExposure', - 'AttackPath', - 'BackupDisasterRecovery', - 'BigQueryExport', - 'AdaptiveProtection', - 'Attack', - 'CloudArmor', - 'Requests', - 'SecurityPolicy', - 'CloudDlpDataProfile', - 'CloudDlpInspection', - 'Compliance', - 'Connection', - 'Contact', - 'ContactDetails', - 'Container', - 'Database', - 'EffectiveEventThreatDetectionCustomModule', - 'EffectiveSecurityHealthAnalyticsCustomModule', - 'EventThreatDetectionCustomModule', - 'CustomModuleValidationError', - 'CustomModuleValidationErrors', - 'Position', - 'ExfilResource', - 'Exfiltration', - 'ExternalSystem', - 'File', - 'Finding', - 'Folder', - 'GroupMembership', - 'IamBinding', - 'Indicator', - 'KernelRootkit', - 'Kubernetes', - 'Label', - 'LoadBalancer', - 'CloudLoggingEntry', - 'LogEntry', - 'MitreAttack', - 'MuteConfig', - 'Notebook', - 'NotificationConfig', - 'NotificationMessage', - 'OrgPolicy', - 'OrganizationSettings', - 'EnvironmentVariable', - 'Process', - 'AwsMetadata', - 'AzureMetadata', - 'Resource', - 'ResourcePath', - 'CloudProvider', - 'ResourceValueConfig', - 'ResourceValue', - 'RunAssetDiscoveryResponse', - 'CustomConfig', - 'SecurityHealthAnalyticsCustomModule', - 'SecurityMarks', - 'SecurityPosture', - 'BatchCreateResourceValueConfigsRequest', - 'BatchCreateResourceValueConfigsResponse', - 'BulkMuteFindingsRequest', - 'BulkMuteFindingsResponse', - 'CreateBigQueryExportRequest', - 'CreateEventThreatDetectionCustomModuleRequest', - 'CreateFindingRequest', - 'CreateMuteConfigRequest', - 'CreateNotificationConfigRequest', - 'CreateResourceValueConfigRequest', - 'CreateSecurityHealthAnalyticsCustomModuleRequest', - 'CreateSourceRequest', - 'DeleteBigQueryExportRequest', - 'DeleteEventThreatDetectionCustomModuleRequest', - 'DeleteMuteConfigRequest', - 'DeleteNotificationConfigRequest', - 'DeleteResourceValueConfigRequest', - 'DeleteSecurityHealthAnalyticsCustomModuleRequest', - 'GetBigQueryExportRequest', - 'GetEffectiveEventThreatDetectionCustomModuleRequest', - 'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', - 'GetEventThreatDetectionCustomModuleRequest', - 'GetMuteConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetResourceValueConfigRequest', - 'GetSecurityHealthAnalyticsCustomModuleRequest', - 'GetSimulationRequest', - 'GetSourceRequest', - 'GetValuedResourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListAttackPathsRequest', - 'ListAttackPathsResponse', - 'ListBigQueryExportsRequest', - 'ListBigQueryExportsResponse', - 'ListDescendantEventThreatDetectionCustomModulesRequest', - 'ListDescendantEventThreatDetectionCustomModulesResponse', - 'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', - 'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', - 'ListEffectiveEventThreatDetectionCustomModulesRequest', - 'ListEffectiveEventThreatDetectionCustomModulesResponse', - 'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', - 'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', - 'ListEventThreatDetectionCustomModulesRequest', - 'ListEventThreatDetectionCustomModulesResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListMuteConfigsRequest', - 'ListMuteConfigsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListResourceValueConfigsRequest', - 'ListResourceValueConfigsResponse', - 'ListSecurityHealthAnalyticsCustomModulesRequest', - 'ListSecurityHealthAnalyticsCustomModulesResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListValuedResourcesRequest', - 'ListValuedResourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'SetMuteRequest', - 'SimulateSecurityHealthAnalyticsCustomModuleRequest', - 'SimulateSecurityHealthAnalyticsCustomModuleResponse', - 'UpdateBigQueryExportRequest', - 'UpdateEventThreatDetectionCustomModuleRequest', - 'UpdateExternalSystemRequest', - 'UpdateFindingRequest', - 'UpdateMuteConfigRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateResourceValueConfigRequest', - 'UpdateSecurityHealthAnalyticsCustomModuleRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'ValidateEventThreatDetectionCustomModuleRequest', - 'ValidateEventThreatDetectionCustomModuleResponse', - 'Simulation', - 'Source', - 'ToxicCombination', - 'ResourceValueConfigMetadata', - 'ValuedResource', - 'Cve', - 'Cvssv3', - 'Package', - 'Reference', - 'SecurityBulletin', - 'Vulnerability', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/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-securitycenter/v1/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.py deleted file mode 100644 index ac4fb60e1479..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.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. -# -from google.cloud.securitycenter_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.security_center import SecurityCenterClient -from .services.security_center import SecurityCenterAsyncClient - -from .types.access import Access -from .types.access import Geolocation -from .types.access import ServiceAccountDelegationInfo -from .types.application import Application -from .types.asset import Asset -from .types.attack_exposure import AttackExposure -from .types.attack_path import AttackPath -from .types.backup_disaster_recovery import BackupDisasterRecovery -from .types.bigquery_export import BigQueryExport -from .types.cloud_armor import AdaptiveProtection -from .types.cloud_armor import Attack -from .types.cloud_armor import CloudArmor -from .types.cloud_armor import Requests -from .types.cloud_armor import SecurityPolicy -from .types.cloud_dlp_data_profile import CloudDlpDataProfile -from .types.cloud_dlp_inspection import CloudDlpInspection -from .types.compliance import Compliance -from .types.connection import Connection -from .types.contact_details import Contact -from .types.contact_details import ContactDetails -from .types.container import Container -from .types.database import Database -from .types.effective_event_threat_detection_custom_module import EffectiveEventThreatDetectionCustomModule -from .types.effective_security_health_analytics_custom_module import EffectiveSecurityHealthAnalyticsCustomModule -from .types.event_threat_detection_custom_module import EventThreatDetectionCustomModule -from .types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationError -from .types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationErrors -from .types.event_threat_detection_custom_module_validation_errors import Position -from .types.exfiltration import ExfilResource -from .types.exfiltration import Exfiltration -from .types.external_system import ExternalSystem -from .types.file import File -from .types.finding import Finding -from .types.folder import Folder -from .types.group_membership import GroupMembership -from .types.iam_binding import IamBinding -from .types.indicator import Indicator -from .types.kernel_rootkit import KernelRootkit -from .types.kubernetes import Kubernetes -from .types.label import Label -from .types.load_balancer import LoadBalancer -from .types.log_entry import CloudLoggingEntry -from .types.log_entry import LogEntry -from .types.mitre_attack import MitreAttack -from .types.mute_config import MuteConfig -from .types.notebook import Notebook -from .types.notification_config import NotificationConfig -from .types.notification_message import NotificationMessage -from .types.org_policy import OrgPolicy -from .types.organization_settings import OrganizationSettings -from .types.process import EnvironmentVariable -from .types.process import Process -from .types.resource import AwsMetadata -from .types.resource import AzureMetadata -from .types.resource import Resource -from .types.resource import ResourcePath -from .types.resource import CloudProvider -from .types.resource_value_config import ResourceValueConfig -from .types.resource_value_config import ResourceValue -from .types.run_asset_discovery_response import RunAssetDiscoveryResponse -from .types.security_health_analytics_custom_config import CustomConfig -from .types.security_health_analytics_custom_module import SecurityHealthAnalyticsCustomModule -from .types.security_marks import SecurityMarks -from .types.security_posture import SecurityPosture -from .types.securitycenter_service import BatchCreateResourceValueConfigsRequest -from .types.securitycenter_service import BatchCreateResourceValueConfigsResponse -from .types.securitycenter_service import BulkMuteFindingsRequest -from .types.securitycenter_service import BulkMuteFindingsResponse -from .types.securitycenter_service import CreateBigQueryExportRequest -from .types.securitycenter_service import CreateEventThreatDetectionCustomModuleRequest -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateMuteConfigRequest -from .types.securitycenter_service import CreateNotificationConfigRequest -from .types.securitycenter_service import CreateResourceValueConfigRequest -from .types.securitycenter_service import CreateSecurityHealthAnalyticsCustomModuleRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import DeleteBigQueryExportRequest -from .types.securitycenter_service import DeleteEventThreatDetectionCustomModuleRequest -from .types.securitycenter_service import DeleteMuteConfigRequest -from .types.securitycenter_service import DeleteNotificationConfigRequest -from .types.securitycenter_service import DeleteResourceValueConfigRequest -from .types.securitycenter_service import DeleteSecurityHealthAnalyticsCustomModuleRequest -from .types.securitycenter_service import GetBigQueryExportRequest -from .types.securitycenter_service import GetEffectiveEventThreatDetectionCustomModuleRequest -from .types.securitycenter_service import GetEffectiveSecurityHealthAnalyticsCustomModuleRequest -from .types.securitycenter_service import GetEventThreatDetectionCustomModuleRequest -from .types.securitycenter_service import GetMuteConfigRequest -from .types.securitycenter_service import GetNotificationConfigRequest -from .types.securitycenter_service import GetOrganizationSettingsRequest -from .types.securitycenter_service import GetResourceValueConfigRequest -from .types.securitycenter_service import GetSecurityHealthAnalyticsCustomModuleRequest -from .types.securitycenter_service import GetSimulationRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GetValuedResourceRequest -from .types.securitycenter_service import GroupAssetsRequest -from .types.securitycenter_service import GroupAssetsResponse -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAssetsRequest -from .types.securitycenter_service import ListAssetsResponse -from .types.securitycenter_service import ListAttackPathsRequest -from .types.securitycenter_service import ListAttackPathsResponse -from .types.securitycenter_service import ListBigQueryExportsRequest -from .types.securitycenter_service import ListBigQueryExportsResponse -from .types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesRequest -from .types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesResponse -from .types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesRequest -from .types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesResponse -from .types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesRequest -from .types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesResponse -from .types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesRequest -from .types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesResponse -from .types.securitycenter_service import ListEventThreatDetectionCustomModulesRequest -from .types.securitycenter_service import ListEventThreatDetectionCustomModulesResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListMuteConfigsRequest -from .types.securitycenter_service import ListMuteConfigsResponse -from .types.securitycenter_service import ListNotificationConfigsRequest -from .types.securitycenter_service import ListNotificationConfigsResponse -from .types.securitycenter_service import ListResourceValueConfigsRequest -from .types.securitycenter_service import ListResourceValueConfigsResponse -from .types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesRequest -from .types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import ListValuedResourcesRequest -from .types.securitycenter_service import ListValuedResourcesResponse -from .types.securitycenter_service import RunAssetDiscoveryRequest -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import SetMuteRequest -from .types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleRequest -from .types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleResponse -from .types.securitycenter_service import UpdateBigQueryExportRequest -from .types.securitycenter_service import UpdateEventThreatDetectionCustomModuleRequest -from .types.securitycenter_service import UpdateExternalSystemRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateMuteConfigRequest -from .types.securitycenter_service import UpdateNotificationConfigRequest -from .types.securitycenter_service import UpdateOrganizationSettingsRequest -from .types.securitycenter_service import UpdateResourceValueConfigRequest -from .types.securitycenter_service import UpdateSecurityHealthAnalyticsCustomModuleRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.securitycenter_service import ValidateEventThreatDetectionCustomModuleRequest -from .types.securitycenter_service import ValidateEventThreatDetectionCustomModuleResponse -from .types.simulation import Simulation -from .types.source import Source -from .types.toxic_combination import ToxicCombination -from .types.valued_resource import ResourceValueConfigMetadata -from .types.valued_resource import ValuedResource -from .types.vulnerability import Cve -from .types.vulnerability import Cvssv3 -from .types.vulnerability import Package -from .types.vulnerability import Reference -from .types.vulnerability import SecurityBulletin -from .types.vulnerability import Vulnerability - -__all__ = ( - 'SecurityCenterAsyncClient', -'Access', -'AdaptiveProtection', -'Application', -'Asset', -'Attack', -'AttackExposure', -'AttackPath', -'AwsMetadata', -'AzureMetadata', -'BackupDisasterRecovery', -'BatchCreateResourceValueConfigsRequest', -'BatchCreateResourceValueConfigsResponse', -'BigQueryExport', -'BulkMuteFindingsRequest', -'BulkMuteFindingsResponse', -'CloudArmor', -'CloudDlpDataProfile', -'CloudDlpInspection', -'CloudLoggingEntry', -'CloudProvider', -'Compliance', -'Connection', -'Contact', -'ContactDetails', -'Container', -'CreateBigQueryExportRequest', -'CreateEventThreatDetectionCustomModuleRequest', -'CreateFindingRequest', -'CreateMuteConfigRequest', -'CreateNotificationConfigRequest', -'CreateResourceValueConfigRequest', -'CreateSecurityHealthAnalyticsCustomModuleRequest', -'CreateSourceRequest', -'CustomConfig', -'CustomModuleValidationError', -'CustomModuleValidationErrors', -'Cve', -'Cvssv3', -'Database', -'DeleteBigQueryExportRequest', -'DeleteEventThreatDetectionCustomModuleRequest', -'DeleteMuteConfigRequest', -'DeleteNotificationConfigRequest', -'DeleteResourceValueConfigRequest', -'DeleteSecurityHealthAnalyticsCustomModuleRequest', -'EffectiveEventThreatDetectionCustomModule', -'EffectiveSecurityHealthAnalyticsCustomModule', -'EnvironmentVariable', -'EventThreatDetectionCustomModule', -'ExfilResource', -'Exfiltration', -'ExternalSystem', -'File', -'Finding', -'Folder', -'Geolocation', -'GetBigQueryExportRequest', -'GetEffectiveEventThreatDetectionCustomModuleRequest', -'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', -'GetEventThreatDetectionCustomModuleRequest', -'GetMuteConfigRequest', -'GetNotificationConfigRequest', -'GetOrganizationSettingsRequest', -'GetResourceValueConfigRequest', -'GetSecurityHealthAnalyticsCustomModuleRequest', -'GetSimulationRequest', -'GetSourceRequest', -'GetValuedResourceRequest', -'GroupAssetsRequest', -'GroupAssetsResponse', -'GroupFindingsRequest', -'GroupFindingsResponse', -'GroupMembership', -'GroupResult', -'IamBinding', -'Indicator', -'KernelRootkit', -'Kubernetes', -'Label', -'ListAssetsRequest', -'ListAssetsResponse', -'ListAttackPathsRequest', -'ListAttackPathsResponse', -'ListBigQueryExportsRequest', -'ListBigQueryExportsResponse', -'ListDescendantEventThreatDetectionCustomModulesRequest', -'ListDescendantEventThreatDetectionCustomModulesResponse', -'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', -'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', -'ListEffectiveEventThreatDetectionCustomModulesRequest', -'ListEffectiveEventThreatDetectionCustomModulesResponse', -'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', -'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', -'ListEventThreatDetectionCustomModulesRequest', -'ListEventThreatDetectionCustomModulesResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListMuteConfigsRequest', -'ListMuteConfigsResponse', -'ListNotificationConfigsRequest', -'ListNotificationConfigsResponse', -'ListResourceValueConfigsRequest', -'ListResourceValueConfigsResponse', -'ListSecurityHealthAnalyticsCustomModulesRequest', -'ListSecurityHealthAnalyticsCustomModulesResponse', -'ListSourcesRequest', -'ListSourcesResponse', -'ListValuedResourcesRequest', -'ListValuedResourcesResponse', -'LoadBalancer', -'LogEntry', -'MitreAttack', -'MuteConfig', -'Notebook', -'NotificationConfig', -'NotificationMessage', -'OrgPolicy', -'OrganizationSettings', -'Package', -'Position', -'Process', -'Reference', -'Requests', -'Resource', -'ResourcePath', -'ResourceValue', -'ResourceValueConfig', -'ResourceValueConfigMetadata', -'RunAssetDiscoveryRequest', -'RunAssetDiscoveryResponse', -'SecurityBulletin', -'SecurityCenterClient', -'SecurityHealthAnalyticsCustomModule', -'SecurityMarks', -'SecurityPolicy', -'SecurityPosture', -'ServiceAccountDelegationInfo', -'SetFindingStateRequest', -'SetMuteRequest', -'SimulateSecurityHealthAnalyticsCustomModuleRequest', -'SimulateSecurityHealthAnalyticsCustomModuleResponse', -'Simulation', -'Source', -'ToxicCombination', -'UpdateBigQueryExportRequest', -'UpdateEventThreatDetectionCustomModuleRequest', -'UpdateExternalSystemRequest', -'UpdateFindingRequest', -'UpdateMuteConfigRequest', -'UpdateNotificationConfigRequest', -'UpdateOrganizationSettingsRequest', -'UpdateResourceValueConfigRequest', -'UpdateSecurityHealthAnalyticsCustomModuleRequest', -'UpdateSecurityMarksRequest', -'UpdateSourceRequest', -'ValidateEventThreatDetectionCustomModuleRequest', -'ValidateEventThreatDetectionCustomModuleResponse', -'ValuedResource', -'Vulnerability', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json deleted file mode 100644 index 3bca8f8a0f67..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json +++ /dev/null @@ -1,973 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.securitycenter_v1", - "protoPackage": "google.cloud.securitycenter.v1", - "schema": "1.0", - "services": { - "SecurityCenter": { - "clients": { - "grpc": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "BatchCreateResourceValueConfigs": { - "methods": [ - "batch_create_resource_value_configs" - ] - }, - "BulkMuteFindings": { - "methods": [ - "bulk_mute_findings" - ] - }, - "CreateBigQueryExport": { - "methods": [ - "create_big_query_export" - ] - }, - "CreateEventThreatDetectionCustomModule": { - "methods": [ - "create_event_threat_detection_custom_module" - ] - }, - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateMuteConfig": { - "methods": [ - "create_mute_config" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "create_security_health_analytics_custom_module" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteBigQueryExport": { - "methods": [ - "delete_big_query_export" - ] - }, - "DeleteEventThreatDetectionCustomModule": { - "methods": [ - "delete_event_threat_detection_custom_module" - ] - }, - "DeleteMuteConfig": { - "methods": [ - "delete_mute_config" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "DeleteResourceValueConfig": { - "methods": [ - "delete_resource_value_config" - ] - }, - "DeleteSecurityHealthAnalyticsCustomModule": { - "methods": [ - "delete_security_health_analytics_custom_module" - ] - }, - "GetBigQueryExport": { - "methods": [ - "get_big_query_export" - ] - }, - "GetEffectiveEventThreatDetectionCustomModule": { - "methods": [ - "get_effective_event_threat_detection_custom_module" - ] - }, - "GetEffectiveSecurityHealthAnalyticsCustomModule": { - "methods": [ - "get_effective_security_health_analytics_custom_module" - ] - }, - "GetEventThreatDetectionCustomModule": { - "methods": [ - "get_event_threat_detection_custom_module" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetMuteConfig": { - "methods": [ - "get_mute_config" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetResourceValueConfig": { - "methods": [ - "get_resource_value_config" - ] - }, - "GetSecurityHealthAnalyticsCustomModule": { - "methods": [ - "get_security_health_analytics_custom_module" - ] - }, - "GetSimulation": { - "methods": [ - "get_simulation" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GetValuedResource": { - "methods": [ - "get_valued_resource" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListAttackPaths": { - "methods": [ - "list_attack_paths" - ] - }, - "ListBigQueryExports": { - "methods": [ - "list_big_query_exports" - ] - }, - "ListDescendantEventThreatDetectionCustomModules": { - "methods": [ - "list_descendant_event_threat_detection_custom_modules" - ] - }, - "ListDescendantSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_descendant_security_health_analytics_custom_modules" - ] - }, - "ListEffectiveEventThreatDetectionCustomModules": { - "methods": [ - "list_effective_event_threat_detection_custom_modules" - ] - }, - "ListEffectiveSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_effective_security_health_analytics_custom_modules" - ] - }, - "ListEventThreatDetectionCustomModules": { - "methods": [ - "list_event_threat_detection_custom_modules" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListMuteConfigs": { - "methods": [ - "list_mute_configs" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListResourceValueConfigs": { - "methods": [ - "list_resource_value_configs" - ] - }, - "ListSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_security_health_analytics_custom_modules" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "ListValuedResources": { - "methods": [ - "list_valued_resources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "SetMute": { - "methods": [ - "set_mute" - ] - }, - "SimulateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "simulate_security_health_analytics_custom_module" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateBigQueryExport": { - "methods": [ - "update_big_query_export" - ] - }, - "UpdateEventThreatDetectionCustomModule": { - "methods": [ - "update_event_threat_detection_custom_module" - ] - }, - "UpdateExternalSystem": { - "methods": [ - "update_external_system" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateMuteConfig": { - "methods": [ - "update_mute_config" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateResourceValueConfig": { - "methods": [ - "update_resource_value_config" - ] - }, - "UpdateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "update_security_health_analytics_custom_module" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - }, - "ValidateEventThreatDetectionCustomModule": { - "methods": [ - "validate_event_threat_detection_custom_module" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SecurityCenterAsyncClient", - "rpcs": { - "BatchCreateResourceValueConfigs": { - "methods": [ - "batch_create_resource_value_configs" - ] - }, - "BulkMuteFindings": { - "methods": [ - "bulk_mute_findings" - ] - }, - "CreateBigQueryExport": { - "methods": [ - "create_big_query_export" - ] - }, - "CreateEventThreatDetectionCustomModule": { - "methods": [ - "create_event_threat_detection_custom_module" - ] - }, - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateMuteConfig": { - "methods": [ - "create_mute_config" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "create_security_health_analytics_custom_module" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteBigQueryExport": { - "methods": [ - "delete_big_query_export" - ] - }, - "DeleteEventThreatDetectionCustomModule": { - "methods": [ - "delete_event_threat_detection_custom_module" - ] - }, - "DeleteMuteConfig": { - "methods": [ - "delete_mute_config" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "DeleteResourceValueConfig": { - "methods": [ - "delete_resource_value_config" - ] - }, - "DeleteSecurityHealthAnalyticsCustomModule": { - "methods": [ - "delete_security_health_analytics_custom_module" - ] - }, - "GetBigQueryExport": { - "methods": [ - "get_big_query_export" - ] - }, - "GetEffectiveEventThreatDetectionCustomModule": { - "methods": [ - "get_effective_event_threat_detection_custom_module" - ] - }, - "GetEffectiveSecurityHealthAnalyticsCustomModule": { - "methods": [ - "get_effective_security_health_analytics_custom_module" - ] - }, - "GetEventThreatDetectionCustomModule": { - "methods": [ - "get_event_threat_detection_custom_module" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetMuteConfig": { - "methods": [ - "get_mute_config" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetResourceValueConfig": { - "methods": [ - "get_resource_value_config" - ] - }, - "GetSecurityHealthAnalyticsCustomModule": { - "methods": [ - "get_security_health_analytics_custom_module" - ] - }, - "GetSimulation": { - "methods": [ - "get_simulation" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GetValuedResource": { - "methods": [ - "get_valued_resource" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListAttackPaths": { - "methods": [ - "list_attack_paths" - ] - }, - "ListBigQueryExports": { - "methods": [ - "list_big_query_exports" - ] - }, - "ListDescendantEventThreatDetectionCustomModules": { - "methods": [ - "list_descendant_event_threat_detection_custom_modules" - ] - }, - "ListDescendantSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_descendant_security_health_analytics_custom_modules" - ] - }, - "ListEffectiveEventThreatDetectionCustomModules": { - "methods": [ - "list_effective_event_threat_detection_custom_modules" - ] - }, - "ListEffectiveSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_effective_security_health_analytics_custom_modules" - ] - }, - "ListEventThreatDetectionCustomModules": { - "methods": [ - "list_event_threat_detection_custom_modules" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListMuteConfigs": { - "methods": [ - "list_mute_configs" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListResourceValueConfigs": { - "methods": [ - "list_resource_value_configs" - ] - }, - "ListSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_security_health_analytics_custom_modules" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "ListValuedResources": { - "methods": [ - "list_valued_resources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "SetMute": { - "methods": [ - "set_mute" - ] - }, - "SimulateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "simulate_security_health_analytics_custom_module" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateBigQueryExport": { - "methods": [ - "update_big_query_export" - ] - }, - "UpdateEventThreatDetectionCustomModule": { - "methods": [ - "update_event_threat_detection_custom_module" - ] - }, - "UpdateExternalSystem": { - "methods": [ - "update_external_system" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateMuteConfig": { - "methods": [ - "update_mute_config" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateResourceValueConfig": { - "methods": [ - "update_resource_value_config" - ] - }, - "UpdateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "update_security_health_analytics_custom_module" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - }, - "ValidateEventThreatDetectionCustomModule": { - "methods": [ - "validate_event_threat_detection_custom_module" - ] - } - } - }, - "rest": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "BatchCreateResourceValueConfigs": { - "methods": [ - "batch_create_resource_value_configs" - ] - }, - "BulkMuteFindings": { - "methods": [ - "bulk_mute_findings" - ] - }, - "CreateBigQueryExport": { - "methods": [ - "create_big_query_export" - ] - }, - "CreateEventThreatDetectionCustomModule": { - "methods": [ - "create_event_threat_detection_custom_module" - ] - }, - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateMuteConfig": { - "methods": [ - "create_mute_config" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "create_security_health_analytics_custom_module" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteBigQueryExport": { - "methods": [ - "delete_big_query_export" - ] - }, - "DeleteEventThreatDetectionCustomModule": { - "methods": [ - "delete_event_threat_detection_custom_module" - ] - }, - "DeleteMuteConfig": { - "methods": [ - "delete_mute_config" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "DeleteResourceValueConfig": { - "methods": [ - "delete_resource_value_config" - ] - }, - "DeleteSecurityHealthAnalyticsCustomModule": { - "methods": [ - "delete_security_health_analytics_custom_module" - ] - }, - "GetBigQueryExport": { - "methods": [ - "get_big_query_export" - ] - }, - "GetEffectiveEventThreatDetectionCustomModule": { - "methods": [ - "get_effective_event_threat_detection_custom_module" - ] - }, - "GetEffectiveSecurityHealthAnalyticsCustomModule": { - "methods": [ - "get_effective_security_health_analytics_custom_module" - ] - }, - "GetEventThreatDetectionCustomModule": { - "methods": [ - "get_event_threat_detection_custom_module" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetMuteConfig": { - "methods": [ - "get_mute_config" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetResourceValueConfig": { - "methods": [ - "get_resource_value_config" - ] - }, - "GetSecurityHealthAnalyticsCustomModule": { - "methods": [ - "get_security_health_analytics_custom_module" - ] - }, - "GetSimulation": { - "methods": [ - "get_simulation" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GetValuedResource": { - "methods": [ - "get_valued_resource" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListAttackPaths": { - "methods": [ - "list_attack_paths" - ] - }, - "ListBigQueryExports": { - "methods": [ - "list_big_query_exports" - ] - }, - "ListDescendantEventThreatDetectionCustomModules": { - "methods": [ - "list_descendant_event_threat_detection_custom_modules" - ] - }, - "ListDescendantSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_descendant_security_health_analytics_custom_modules" - ] - }, - "ListEffectiveEventThreatDetectionCustomModules": { - "methods": [ - "list_effective_event_threat_detection_custom_modules" - ] - }, - "ListEffectiveSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_effective_security_health_analytics_custom_modules" - ] - }, - "ListEventThreatDetectionCustomModules": { - "methods": [ - "list_event_threat_detection_custom_modules" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListMuteConfigs": { - "methods": [ - "list_mute_configs" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListResourceValueConfigs": { - "methods": [ - "list_resource_value_configs" - ] - }, - "ListSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_security_health_analytics_custom_modules" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "ListValuedResources": { - "methods": [ - "list_valued_resources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "SetMute": { - "methods": [ - "set_mute" - ] - }, - "SimulateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "simulate_security_health_analytics_custom_module" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateBigQueryExport": { - "methods": [ - "update_big_query_export" - ] - }, - "UpdateEventThreatDetectionCustomModule": { - "methods": [ - "update_event_threat_detection_custom_module" - ] - }, - "UpdateExternalSystem": { - "methods": [ - "update_external_system" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateMuteConfig": { - "methods": [ - "update_mute_config" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateResourceValueConfig": { - "methods": [ - "update_resource_value_config" - ] - }, - "UpdateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "update_security_health_analytics_custom_module" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - }, - "ValidateEventThreatDetectionCustomModule": { - "methods": [ - "validate_event_threat_detection_custom_module" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_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-securitycenter/v1/google/cloud/securitycenter_v1/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_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-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py deleted file mode 100644 index bffcff5da306..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - 'SecurityCenterClient', - 'SecurityCenterAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py deleted file mode 100644 index 08b61bf6e289..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ /dev/null @@ -1,7965 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union -import warnings - -from google.cloud.securitycenter_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.securitycenter_v1.services.security_center import pagers -from google.cloud.securitycenter_v1.types import access -from google.cloud.securitycenter_v1.types import application -from google.cloud.securitycenter_v1.types import attack_exposure -from google.cloud.securitycenter_v1.types import attack_path -from google.cloud.securitycenter_v1.types import backup_disaster_recovery -from google.cloud.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import cloud_armor -from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile -from google.cloud.securitycenter_v1.types import cloud_dlp_inspection -from google.cloud.securitycenter_v1.types import compliance -from google.cloud.securitycenter_v1.types import connection -from google.cloud.securitycenter_v1.types import container -from google.cloud.securitycenter_v1.types import database -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors -from google.cloud.securitycenter_v1.types import exfiltration -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import file -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import group_membership -from google.cloud.securitycenter_v1.types import iam_binding -from google.cloud.securitycenter_v1.types import indicator -from google.cloud.securitycenter_v1.types import kernel_rootkit -from google.cloud.securitycenter_v1.types import kubernetes -from google.cloud.securitycenter_v1.types import load_balancer -from google.cloud.securitycenter_v1.types import log_entry -from google.cloud.securitycenter_v1.types import mitre_attack -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notebook -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import org_policy -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import process -from google.cloud.securitycenter_v1.types import resource -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import security_posture -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import toxic_combination -from google.cloud.securitycenter_v1.types import valued_resource -from google.cloud.securitycenter_v1.types import vulnerability -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 empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V1 APIs for Security Center service.""" - - _client: SecurityCenterClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE - - asset_path = staticmethod(SecurityCenterClient.asset_path) - parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) - attack_path_path = staticmethod(SecurityCenterClient.attack_path_path) - parse_attack_path_path = staticmethod(SecurityCenterClient.parse_attack_path_path) - big_query_export_path = staticmethod(SecurityCenterClient.big_query_export_path) - parse_big_query_export_path = staticmethod(SecurityCenterClient.parse_big_query_export_path) - dlp_job_path = staticmethod(SecurityCenterClient.dlp_job_path) - parse_dlp_job_path = staticmethod(SecurityCenterClient.parse_dlp_job_path) - effective_event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.effective_event_threat_detection_custom_module_path) - parse_effective_event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.parse_effective_event_threat_detection_custom_module_path) - effective_security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.effective_security_health_analytics_custom_module_path) - parse_effective_security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.parse_effective_security_health_analytics_custom_module_path) - event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.event_threat_detection_custom_module_path) - parse_event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.parse_event_threat_detection_custom_module_path) - external_system_path = staticmethod(SecurityCenterClient.external_system_path) - parse_external_system_path = staticmethod(SecurityCenterClient.parse_external_system_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) - parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) - mute_config_path = staticmethod(SecurityCenterClient.mute_config_path) - parse_mute_config_path = staticmethod(SecurityCenterClient.parse_mute_config_path) - notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) - parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) - organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) - parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) - policy_path = staticmethod(SecurityCenterClient.policy_path) - parse_policy_path = staticmethod(SecurityCenterClient.parse_policy_path) - resource_value_config_path = staticmethod(SecurityCenterClient.resource_value_config_path) - parse_resource_value_config_path = staticmethod(SecurityCenterClient.parse_resource_value_config_path) - security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.security_health_analytics_custom_module_path) - parse_security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.parse_security_health_analytics_custom_module_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) - simulation_path = staticmethod(SecurityCenterClient.simulation_path) - parse_simulation_path = staticmethod(SecurityCenterClient.parse_simulation_path) - source_path = staticmethod(SecurityCenterClient.source_path) - parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) - table_data_profile_path = staticmethod(SecurityCenterClient.table_data_profile_path) - parse_table_data_profile_path = staticmethod(SecurityCenterClient.parse_table_data_profile_path) - topic_path = staticmethod(SecurityCenterClient.topic_path) - parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) - valued_resource_path = staticmethod(SecurityCenterClient.valued_resource_path) - parse_valued_resource_path = staticmethod(SecurityCenterClient.parse_valued_resource_path) - common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) - parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) - common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) - parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) - parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) - parse_common_location_path = staticmethod(SecurityCenterClient.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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def bulk_mute_findings(self, - request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), - ) -> operation_async.AsyncOperation: - r"""Kicks off an LRO to bulk mute findings for a parent - based on a filter. The parent can be either an - organization, folder or project. The findings matched by - the filter will be muted after the LRO is done. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest, dict]]): - The request object. Request message for bulk findings - update. - Note: - - 1. If multiple bulk update requests - match the same resource, the order - in which they get executed is not - defined. - 2. Once a bulk operation is started, - there is no way to stop it. - parent (:class:`str`): - Required. The parent, at which bulk action needs to be - applied. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1.types.BulkMuteFindingsResponse` - The response to a BulkMute request. Contains the LRO - 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]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): - request = securitycenter_service.BulkMuteFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.bulk_mute_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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - securitycenter_service.BulkMuteFindingsResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - async def create_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - parent: Optional[str] = None, - security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Creates a resident - SecurityHealthAnalyticsCustomModule at the scope of the - given CRM parent, and also creates inherited - SecurityHealthAnalyticsCustomModules for all CRM - descendants of the given parent. These modules are - enabled by default. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_create_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Request message for creating Security - Health Analytics custom modules. - parent (:class:`str`): - Required. Resource name of the new custom module's - parent. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - security_health_analytics_custom_module (:class:`google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule`): - Required. SecurityHealthAnalytics - custom module to create. The provided - name is ignored and reset with provided - parent information and server-generated - ID. - - This corresponds to the ``security_health_analytics_custom_module`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, security_health_analytics_custom_module]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if security_health_analytics_custom_module is not None: - request.security_health_analytics_custom_module = security_health_analytics_custom_module - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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 create_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v1 - - async def sample_create_source(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateSourceRequest, dict]]): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be ``organizations/[organization_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`google.cloud.securitycenter_v1.types.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = 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_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding_id: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_create_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateFindingRequest, dict]]): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - ``organizations/[organization_id]/sources/[source_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`google.cloud.securitycenter_v1.types.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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 create_mute_config(self, - request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - mute_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Creates a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_create_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = await client.create_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateMuteConfigRequest, dict]]): - The request object. Request message for creating a mute - config. - parent (:class:`str`): - Required. Resource name of the new mute configs's - parent. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config (:class:`google.cloud.securitycenter_v1.types.MuteConfig`): - Required. The mute config being - created. - - This corresponds to the ``mute_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``mute_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.cloud.securitycenter_v1.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): - request = securitycenter_service.CreateMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if mute_config is not None: - request.mute_config = mute_config - if mute_config_id is not None: - request.mute_config_id = mute_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_mute_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 create_notification_config(self, - request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - config_id: Optional[str] = None, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_create_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.create_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest, dict]]): - The request object. Request message for creating a - notification config. - parent (:class:`str`): - Required. Resource name of the new notification config's - parent. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (:class:`str`): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters and contain - alphanumeric characters, underscores, or - hyphens only. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_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.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_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_notification_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_mute_config(self, - request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_delete_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_mute_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest, dict]]): - The request object. Request message for deleting a mute - config. - name (:class:`str`): - Required. Name of the mute config to delete. Its format - is - ``organizations/{organization}/muteConfigs/{config_id}``, - ``folders/{folder}/muteConfigs/{config_id}``, - ``projects/{project}/muteConfigs/{config_id}``, - ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, - ``folders/{folder}/locations/global/muteConfigs/{config_id}``, - or - ``projects/{project}/locations/global/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): - request = securitycenter_service.DeleteMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_mute_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 delete_notification_config(self, - request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest, dict]]): - The request object. Request message for deleting a - notification config. - name (:class:`str`): - Required. Name of the notification config to delete. Its - format is - ``organizations/[organization_id]/notificationConfigs/[config_id]``, - ``folders/[folder_id]/notificationConfigs/[config_id]``, - or - ``projects/[project_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 delete_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]] = 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 - SecurityHealthAnalyticsCustomModule and all of its - descendants in the CRM hierarchy. This method is only - supported for resident custom modules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_delete_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - await client.delete_security_health_analytics_custom_module(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Request message for deleting Security - Health Analytics custom modules. - name (:class:`str`): - Required. Name of the custom module to delete. Its - format is - ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be 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, securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_simulation(self, - request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> simulation.Simulation: - r"""Get the simulation by name or the latest simulation - for the given organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_simulation(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_simulation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetSimulationRequest, dict]]): - The request object. Request message for getting - simulation. Simulation name can include - "latest" to retrieve the latest - simulation For example, - "organizations/123/simulations/latest". - name (:class:`str`): - Required. The organization name or simulation name of - this simulation - - Valid format: - ``organizations/{organization}/simulations/latest`` - ``organizations/{organization}/simulations/{simulation}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Simulation: - Attack path simulation - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSimulationRequest): - request = securitycenter_service.GetSimulationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_simulation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_valued_resource(self, - request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> valued_resource.ValuedResource: - r"""Get the valued resource by 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 import securitycenter_v1 - - async def sample_get_valued_resource(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_valued_resource(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetValuedResourceRequest, dict]]): - The request object. Request message for getting a valued - resource. - name (:class:`str`): - Required. The name of this valued resource - - Valid format: - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v1.types.ValuedResource: - A resource that is determined to have - value to a user's system - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetValuedResourceRequest): - request = securitycenter_service.GetValuedResourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_valued_resource] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_big_query_export(self, - request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Gets a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = await client.get_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetBigQueryExportRequest, dict]]): - The request object. Request message for retrieving a - BigQuery export. - name (:class:`str`): - Required. Name of the BigQuery export to retrieve. Its - format is - ``organizations/{organization}/bigQueryExports/{export_id}``, - ``folders/{folder}/bigQueryExports/{export_id}``, or - ``projects/{project}/bigQueryExports/{export_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.cloud.securitycenter_v1.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): - request = securitycenter_service.GetBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 get_mute_config(self, - request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> mute_config.MuteConfig: - r"""Gets a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetMuteConfigRequest, dict]]): - The request object. Request message for retrieving a mute - config. - name (:class:`str`): - Required. Name of the mute config to retrieve. Its - format is - ``organizations/{organization}/muteConfigs/{config_id}``, - ``folders/{folder}/muteConfigs/{config_id}``, - ``projects/{project}/muteConfigs/{config_id}``, - ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, - ``folders/{folder}/locations/global/muteConfigs/{config_id}``, - or - ``projects/{project}/locations/global/muteConfigs/{config_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.cloud.securitycenter_v1.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetMuteConfigRequest): - request = securitycenter_service.GetMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_mute_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 get_notification_config(self, - request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetNotificationConfigRequest, dict]]): - The request object. Request message for getting a - notification config. - name (:class:`str`): - Required. Name of the notification config to get. Its - format is - ``organizations/[organization_id]/notificationConfigs/[config_id]``, - ``folders/[folder_id]/notificationConfigs/[config_id]``, - or - ``projects/[project_id]/notificationConfigs/[config_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.cloud.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 get_organization_settings(self, - request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest, dict]]): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - ``organizations/[organization_id]/organizationSettings``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_organization_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 get_effective_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: - r"""Retrieves an - EffectiveSecurityHealthAnalyticsCustomModule. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_effective_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_effective_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Request message for getting effective - Security Health Analytics custom - modules. - name (:class:`str`): - Required. Name of the effective custom module to get. - Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule: - An EffectiveSecurityHealthAnalyticsCustomModule is the representation of - a Security Health Analytics custom module at a - specified level of the resource hierarchy: - organization, folder, or project. If a custom module - is inherited from a parent organization or folder, - the value of the enablementState property in - EffectiveSecurityHealthAnalyticsCustomModule is set - to the value that is effective in the parent, instead - of INHERITED. For example, if the module is enabled - in a parent organization or folder, the effective - enablement_state for the module in all child folders - or projects is also enabled. - EffectiveSecurityHealthAnalyticsCustomModule is - read-only. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_effective_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Retrieves a SecurityHealthAnalyticsCustomModule. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Request message for getting Security - Health Analytics custom modules. - name (:class:`str`): - Required. Name of the custom module to get. Its format - is - ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v1 - - async def sample_get_source(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetSourceRequest, dict]]): - The request object. Request message for getting a source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 group_assets(self, - request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsAsyncPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_group_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GroupAssetsRequest, dict]]): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsAsyncPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - warnings.warn("SecurityCenterAsyncClient.group_assets is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.GroupAssetsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_group_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GroupFindingsRequest, dict]]): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - ``organizations/[organization_id]/sources/[source_id]``, - ``folders/[folder_id]/sources/[source_id]``, or - ``projects/[project_id]/sources/[source_id]``. To - groupBy across all sources provide a source_id of ``-``. - For example: - ``organizations/{organization_id}/sources/-, folders/{folder_id}/sources/-``, - or ``projects/{project_id}/sources/-`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported when compare_duration - is set: - - - state_change - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_assets(self, - request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsAsyncPager: - r"""Lists an organization's assets. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListAssetsRequest, dict]]): - The request object. Request message for listing assets. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsAsyncPager: - Response message for listing assets. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - warnings.warn("SecurityCenterAsyncClient.list_assets is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(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_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListAssetsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_descendant_security_health_analytics_custom_modules(self, - request: Optional[Union[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, 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.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: - r"""Returns a list of all resident - SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent’s CRM descendants. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_descendant_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, dict]]): - The request object. Request message for listing - descendant Security Health Analytics - custom modules. - parent (:class:`str`): - Required. Name of parent to list descendant custom - modules. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - 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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: - Response message for listing - descendant Security Health Analytics - custom modules. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_descendant_security_health_analytics_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings(self, - request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListFindingsRequest( - parent="parent_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.securitycenter_v1.types.ListFindingsRequest, dict]]): - The request object. Request message for listing findings. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.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_mute_configs(self, - request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsAsyncPager: - r"""Lists mute configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_mute_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListMuteConfigsRequest, dict]]): - The request object. Request message for listing mute - configs at a given scope e.g. - organization, folder or project. - parent (:class:`str`): - Required. The parent, which owns the collection of mute - configs. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - - 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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsAsyncPager: - Response message for listing mute - configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): - request = securitycenter_service.ListMuteConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_mute_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.ListMuteConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_notification_configs(self, - request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsAsyncPager: - r"""Lists notification configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest, dict]]): - The request object. Request message for listing - notification configs. - parent (:class:`str`): - Required. The name of the parent in which to list the - notification configurations. Its format is - "organizations/[organization_id]", - "folders/[folder_id]", or "projects/[project_id]". - - 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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsAsyncPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListNotificationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_effective_security_health_analytics_custom_modules(self, - request: Optional[Union[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, 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.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: - r"""Returns a list of all - EffectiveSecurityHealthAnalyticsCustomModules for the - given parent. This includes resident modules defined at - the scope of the parent, and inherited modules, - inherited from CRM ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_effective_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_security_health_analytics_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, dict]]): - The request object. Request message for listing effective - Security Health Analytics custom - modules. - parent (:class:`str`): - Required. Name of parent to list effective custom - modules. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - 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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: - Response message for listing - effective Security Health Analytics - custom modules. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_effective_security_health_analytics_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_security_health_analytics_custom_modules(self, - request: Optional[Union[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, 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.ListSecurityHealthAnalyticsCustomModulesAsyncPager: - r"""Returns a list of all - SecurityHealthAnalyticsCustomModules for the given - parent. This includes resident modules defined at the - scope of the parent, and inherited modules, inherited - from CRM ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_security_health_analytics_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest, dict]]): - The request object. Request message for listing Security - Health Analytics custom modules. - parent (:class:`str`): - Required. Name of parent to list custom modules. Its - format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - 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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager: - Response message for listing Security - Health Analytics custom modules. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_security_health_analytics_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListSecurityHealthAnalyticsCustomModulesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_sources(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListSourcesRequest, dict]]): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - 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.securitycenter_v1.services.security_center.pagers.ListSourcesAsyncPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_asset_discovery(self, - request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), - ) -> operation_async.AsyncOperation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS 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 securitycenter_v1 - - async def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest, dict]]): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - ``organizations/[organization_id]``. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` - Response of asset discovery run - - """ - warnings.warn("SecurityCenterAsyncClient.run_asset_discovery is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - async def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - start_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of 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 securitycenter_v1 - - async def sample_set_finding_state(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.SetFindingStateRequest, dict]]): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The `relative resource - name `__ - of the finding. Example: - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`google.cloud.securitycenter_v1.types.Finding.State`): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_mute(self, - request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, - *, - name: Optional[str] = None, - mute: Optional[finding.Finding.Mute] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the mute state of 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 securitycenter_v1 - - async def sample_set_mute(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = await client.set_mute(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.SetMuteRequest, dict]]): - The request object. Request message for updating a - finding's mute status. - name (:class:`str`): - Required. The `relative resource - name `__ - of the finding. Example: - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute (:class:`google.cloud.securitycenter_v1.types.Finding.Mute`): - Required. The desired state of the - Mute. - - This corresponds to the ``mute`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, mute]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetMuteRequest): - request = securitycenter_service.SetMuteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if mute is not None: - request.mute = mute - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.set_mute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 simulate_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - parent: Optional[str] = None, - custom_config: Optional[security_health_analytics_custom_config.CustomConfig] = None, - resource: Optional[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: - r"""Simulates a given SecurityHealthAnalyticsCustomModule - and Resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_simulate_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - resource = securitycenter_v1.SimulatedResource() - resource.resource_type = "resource_type_value" - - request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - resource=resource, - ) - - # Make the request - response = await client.simulate_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Request message to simulate a - CustomConfig against a given test - resource. Maximum size of the request is - 4 MB by default. - parent (:class:`str`): - Required. The relative resource name of the - organization, project, or folder. For more information - about relative resource names, see `Relative Resource - Name `__ - Example: ``organizations/{organization_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - custom_config (:class:`google.cloud.securitycenter_v1.types.CustomConfig`): - Required. The custom configuration - that you need to test. - - This corresponds to the ``custom_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (:class:`google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource`): - Required. Resource data to simulate - custom module against. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse: - Response message for simulating a SecurityHealthAnalyticsCustomModule - against a given 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, custom_config, resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if custom_config is not None: - request.custom_config = custom_config - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.simulate_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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_external_system(self, - request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, - *, - external_system: Optional[gcs_external_system.ExternalSystem] = None, - update_mask: 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]] = (), - ) -> gcs_external_system.ExternalSystem: - r"""Updates external system. This is for a given 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 securitycenter_v1 - - async def sample_update_external_system(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateExternalSystemRequest( - ) - - # Make the request - response = await client.update_external_system(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest, dict]]): - The request object. Request message for updating a - ExternalSystem resource. - external_system (:class:`google.cloud.securitycenter_v1.types.ExternalSystem`): - Required. The external system - resource to update. - - This corresponds to the ``external_system`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the external system resource. - If empty all mutable fields 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.cloud.securitycenter_v1.types.ExternalSystem: - Representation of third party - SIEM/SOAR fields within SCC. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): - request = securitycenter_service.UpdateExternalSystemRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if external_system is not None: - request.external_system = external_system - 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_external_system] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("external_system.name", request.external_system.name), - )), - ) - - # Validate the universe domain. - self._client._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_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateFindingRequest, dict]]): - The request object. Request message for updating or - creating a finding. - finding (:class:`google.cloud.securitycenter_v1.types.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe domain. - self._client._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_mute_config(self, - request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, - *, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - update_mask: 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]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Updates a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = await client.update_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest, dict]]): - The request object. Request message for updating a mute - config. - mute_config (:class:`google.cloud.securitycenter_v1.types.MuteConfig`): - Required. The mute config being - updated. - - This corresponds to the ``mute_config`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): - request = securitycenter_service.UpdateMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if mute_config is not None: - request.mute_config = mute_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_mute_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("mute_config.name", request.mute_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 update_notification_config(self, - request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, - *, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - update_mask: 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]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = await client.update_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest, dict]]): - The request object. Request message for updating a - notification config. - notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the notification config. - If empty all mutable fields 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.cloud.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_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 update_organization_settings(self, - request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, - *, - organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = await client.update_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest, dict]]): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`google.cloud.securitycenter_v1.types.OrganizationSettings`): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_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 update_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, - update_mask: 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]] = (), - ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Updates the SecurityHealthAnalyticsCustomModule under - the given name based on the given update mask. Updating - the enablement state is supported on both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name and custom config of a module is supported - on resident modules only. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( - ) - - # Make the request - response = await client.update_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Request message for updating Security - Health Analytics custom modules. - security_health_analytics_custom_module (:class:`google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule`): - Required. The SecurityHealthAnalytics - custom module to update. - - This corresponds to the ``security_health_analytics_custom_module`` 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 only fields that - can be updated are ``enablement_state`` and - ``custom_config``. If empty or set to the wildcard value - ``*``, both ``enablement_state`` and ``custom_config`` - are 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.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_health_analytics_custom_module, 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, securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_health_analytics_custom_module is not None: - request.security_health_analytics_custom_module = security_health_analytics_custom_module - 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_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_health_analytics_custom_module.name", request.security_health_analytics_custom_module.name), - )), - ) - - # Validate the universe domain. - self._client._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_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v1 - - async def sample_update_source(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateSourceRequest, dict]]): - The request object. Request message for updating a - source. - source (:class:`google.cloud.securitycenter_v1.types.Source`): - Required. The source resource to - update. - - This corresponds to the ``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.cloud.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_security_marks(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest, dict]]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`google.cloud.securitycenter_v1.types.SecurityMarks`): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe domain. - self._client._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_big_query_export(self, - request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, - *, - parent: Optional[str] = None, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - big_query_export_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Creates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_create_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = await client.create_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest, dict]]): - The request object. Request message for creating a - BigQuery export. - parent (:class:`str`): - Required. The name of the parent resource of the new - BigQuery export. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export (:class:`google.cloud.securitycenter_v1.types.BigQueryExport`): - Required. The BigQuery export being - created. - - This corresponds to the ``big_query_export`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``big_query_export_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.cloud.securitycenter_v1.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): - request = securitycenter_service.CreateBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if big_query_export is not None: - request.big_query_export = big_query_export - if big_query_export_id is not None: - request.big_query_export_id = big_query_export_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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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_big_query_export(self, - request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - await client.delete_big_query_export(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest, dict]]): - The request object. Request message for deleting a - BigQuery export. - name (:class:`str`): - Required. The name of the BigQuery export to delete. Its - format is - ``organizations/{organization}/bigQueryExports/{export_id}``, - ``folders/{folder}/bigQueryExports/{export_id}``, or - ``projects/{project}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): - request = securitycenter_service.DeleteBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_big_query_export(self, - request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, - *, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - update_mask: 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]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Updates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateBigQueryExportRequest( - ) - - # Make the request - response = await client.update_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest, dict]]): - The request object. Request message for updating a - BigQuery export. - big_query_export (:class:`google.cloud.securitycenter_v1.types.BigQueryExport`): - Required. The BigQuery export being - updated. - - This corresponds to the ``big_query_export`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): - request = securitycenter_service.UpdateBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if big_query_export is not None: - request.big_query_export = big_query_export - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("big_query_export.name", request.big_query_export.name), - )), - ) - - # Validate the universe domain. - self._client._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_big_query_exports(self, - request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsAsyncPager: - r"""Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are 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 securitycenter_v1 - - async def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest, dict]]): - The request object. Request message for listing BigQuery - exports at a given scope e.g. - organization, folder or project. - parent (:class:`str`): - Required. The parent, which owns the collection of - BigQuery exports. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - - 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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsAsyncPager: - Response message for listing BigQuery - exports. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): - request = securitycenter_service.ListBigQueryExportsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_big_query_exports] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListBigQueryExportsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - parent: Optional[str] = None, - event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Creates a resident Event Threat Detection custom - module at the scope of the given Resource Manager - parent, and also creates inherited custom modules for - all descendants of the given parent. These modules are - enabled by default. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_create_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Request to create an Event Threat - Detection custom module. - parent (:class:`str`): - Required. The new custom module's parent. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - event_threat_detection_custom_module (:class:`google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule`): - Required. The module to create. The - event_threat_detection_custom_module.name will be - ignored and server generated. - - This corresponds to the ``event_threat_detection_custom_module`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, event_threat_detection_custom_module]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if event_threat_detection_custom_module is not None: - request.event_threat_detection_custom_module = event_threat_detection_custom_module - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, dict]] = 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 Event Threat Detection custom - module and all of its descendants in the Resource - Manager hierarchy. This method is only supported for - resident custom modules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_delete_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - await client.delete_event_threat_detection_custom_module(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Request to delete an Event Threat - Detection custom module. - name (:class:`str`): - Required. Name of the custom module to delete. - - Its format is: - - - "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}". - - "folders/{folder}/eventThreatDetectionSettings/customModules/{module}". - - "projects/{project}/eventThreatDetectionSettings/customModules/{module}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be 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, securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.GetEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Gets an Event Threat Detection custom module. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Request to get an Event Threat - Detection custom module. - name (:class:`str`): - Required. Name of the custom module to get. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_descendant_event_threat_detection_custom_modules(self, - request: Optional[Union[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, 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.ListDescendantEventThreatDetectionCustomModulesAsyncPager: - r"""Lists all resident Event Threat Detection custom - modules under the given Resource Manager parent and its - descendants. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_descendant_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest, dict]]): - The request object. Request to list current and - descendant resident Event Threat - Detection custom modules. - parent (:class:`str`): - Required. Name of the parent to list custom modules - under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - 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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager: - Response for listing current and - descendant resident Event Threat - Detection custom modules. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_descendant_event_threat_detection_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListDescendantEventThreatDetectionCustomModulesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_event_threat_detection_custom_modules(self, - request: Optional[Union[securitycenter_service.ListEventThreatDetectionCustomModulesRequest, 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.ListEventThreatDetectionCustomModulesAsyncPager: - r"""Lists all Event Threat Detection custom modules for - the given Resource Manager parent. This includes - resident modules defined at the scope of the parent - along with modules inherited from ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_event_threat_detection_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest, dict]]): - The request object. Request to list Event Threat - Detection custom modules. - parent (:class:`str`): - Required. Name of the parent to list custom modules - under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - 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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesAsyncPager: - Response for listing Event Threat - Detection custom modules. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListEventThreatDetectionCustomModulesRequest): - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_event_threat_detection_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListEventThreatDetectionCustomModulesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, - update_mask: 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]] = (), - ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Updates the Event Threat Detection custom module with - the given name based on the given update mask. Updating - the enablement state is supported for both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name or configuration of a module is supported - for resident modules only. The type of a module cannot - be changed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( - ) - - # Make the request - response = await client.update_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Request to update an Event Threat - Detection custom module. - event_threat_detection_custom_module (:class:`google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule`): - Required. The module being updated. - This corresponds to the ``event_threat_detection_custom_module`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([event_threat_detection_custom_module, 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, securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if event_threat_detection_custom_module is not None: - request.event_threat_detection_custom_module = event_threat_detection_custom_module - 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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("event_threat_detection_custom_module.name", request.event_threat_detection_custom_module.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def validate_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: - r"""Validates the given Event Threat Detection custom - module. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_validate_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - raw_text="raw_text_value", - type_="type__value", - ) - - # Make the request - response = await client.validate_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Request to validate an Event Threat - Detection custom module. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse: - Response to validating an Event - Threat Detection custom module. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest(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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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_effective_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: - r"""Gets an effective Event Threat Detection custom - module at the given level. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_effective_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_effective_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Request to get an - EffectiveEventThreatDetectionCustomModule. - name (:class:`str`): - Required. The resource name of the effective Event - Threat Detection custom module. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule: - An EffectiveEventThreatDetectionCustomModule is the representation of - an Event Threat Detection custom module at a - specified level of the resource hierarchy: - organization, folder, or project. If a custom module - is inherited from a parent organization or folder, - the value of the enablement_state property in - EffectiveEventThreatDetectionCustomModule is set to - the value that is effective in the parent, instead of - INHERITED. For example, if the module is enabled in a - parent organization or folder, the effective - enablement_state for the module in all child folders - or projects is also enabled. - EffectiveEventThreatDetectionCustomModule is - read-only. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_effective_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_effective_event_threat_detection_custom_modules(self, - request: Optional[Union[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, 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.ListEffectiveEventThreatDetectionCustomModulesAsyncPager: - r"""Lists all effective Event Threat Detection custom - modules for the given parent. This includes resident - modules defined at the scope of the parent along with - modules inherited from its ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_effective_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_event_threat_detection_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest, dict]]): - The request object. Request to list effective Event - Threat Detection custom modules. - parent (:class:`str`): - Required. Name of the parent to list custom modules for. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - 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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesAsyncPager: - Response for listing - EffectiveEventThreatDetectionCustomModules. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_effective_event_threat_detection_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListEffectiveEventThreatDetectionCustomModulesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_create_resource_value_configs(self, - request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - r"""Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - requests = securitycenter_v1.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - requests.resource_value_config.resource_value = "NONE" - requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest, dict]]): - The request object. Request message to create multiple - resource value configs - parent (:class:`str`): - Required. Resource name of the new - ResourceValueConfig's parent. The parent - field in the - CreateResourceValueConfigRequest - messages must either be empty or match - this field. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - requests (:class:`MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]`): - Required. The resource value configs - to be created. - - This corresponds to the ``requests`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse: - Response message for - BatchCreateResourceValueConfigs - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, requests]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): - request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if requests: - request.requests.extend(requests) - - # 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_resource_value_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, - ) - - # Done; return the response. - return response - - async def delete_resource_value_config(self, - request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_resource_value_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest, dict]]): - The request object. Request message to delete resource - value config - name (:class:`str`): - Required. Name of the - ResourceValueConfig 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. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): - request = securitycenter_service.DeleteResourceValueConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_resource_value_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_resource_value_config(self, - request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resource_value_config.ResourceValueConfig: - r"""Gets a ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest, dict]]): - The request object. Request message to get resource value - config - name (:class:`str`): - Required. Name of the resource value config to retrieve. - Its format is - ``organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v1.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): - request = securitycenter_service.GetResourceValueConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_resource_value_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_resource_value_configs(self, - request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsAsyncPager: - r"""Lists all ResourceValueConfigs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest, dict]]): - The request object. Request message to list resource - value configs of a parent - parent (:class:`str`): - Required. The parent, which owns the collection of - resource value configs. Its format is - ``organizations/[organization_id]`` - - 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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsAsyncPager: - Response message to list resource - value configs - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): - request = securitycenter_service.ListResourceValueConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_resource_value_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.ListResourceValueConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_resource_value_config(self, - request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, - *, - resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, - update_mask: 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]] = (), - ) -> gcs_resource_value_config.ResourceValueConfig: - r"""Updates an existing ResourceValueConfigs with new - rules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - resource_value_config = securitycenter_v1.ResourceValueConfig() - resource_value_config.resource_value = "NONE" - resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.UpdateResourceValueConfigRequest( - resource_value_config=resource_value_config, - ) - - # Make the request - response = await client.update_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest, dict]]): - The request object. Request message to update resource - value config - resource_value_config (:class:`google.cloud.securitycenter_v1.types.ResourceValueConfig`): - Required. The resource value config - being updated. - - This corresponds to the ``resource_value_config`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): - request = securitycenter_service.UpdateResourceValueConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if resource_value_config is not None: - request.resource_value_config = resource_value_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_resource_value_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource_value_config.name", request.resource_value_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 list_valued_resources(self, - request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesAsyncPager: - r"""Lists the valued resources for a set of simulation - results and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_valued_resources(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListValuedResourcesRequest, dict]]): - The request object. Request message for listing the - valued resources for a given simulation. - parent (:class:`str`): - Required. Name of parent to list valued resources. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - - 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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesAsyncPager: - Response message for listing the - valued resources for a given simulation. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): - request = securitycenter_service.ListValuedResourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_valued_resources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListValuedResourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_attack_paths(self, - request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsAsyncPager: - r"""Lists the attack paths for a set of simulation - results or valued resources and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_attack_paths(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListAttackPathsRequest, dict]]): - The request object. Request message for listing the - attack paths for a given simulation or - valued resource. - parent (:class:`str`): - Required. Name of parent to list attack paths. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - - 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.securitycenter_v1.services.security_center.pagers.ListAttackPathsAsyncPager: - Response message for listing the - attack paths for a given simulation or - valued resource. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): - request = securitycenter_service.ListAttackPathsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_attack_paths] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListAttackPathsAsyncPager( - method=rpc, - request=request, - response=response, - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self) -> "SecurityCenterAsyncClient": - 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__ = ( - "SecurityCenterAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py deleted file mode 100644 index 2b23b6e3a02c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py +++ /dev/null @@ -1,8455 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_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.securitycenter_v1.services.security_center import pagers -from google.cloud.securitycenter_v1.types import access -from google.cloud.securitycenter_v1.types import application -from google.cloud.securitycenter_v1.types import attack_exposure -from google.cloud.securitycenter_v1.types import attack_path -from google.cloud.securitycenter_v1.types import backup_disaster_recovery -from google.cloud.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import cloud_armor -from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile -from google.cloud.securitycenter_v1.types import cloud_dlp_inspection -from google.cloud.securitycenter_v1.types import compliance -from google.cloud.securitycenter_v1.types import connection -from google.cloud.securitycenter_v1.types import container -from google.cloud.securitycenter_v1.types import database -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors -from google.cloud.securitycenter_v1.types import exfiltration -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import file -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import group_membership -from google.cloud.securitycenter_v1.types import iam_binding -from google.cloud.securitycenter_v1.types import indicator -from google.cloud.securitycenter_v1.types import kernel_rootkit -from google.cloud.securitycenter_v1.types import kubernetes -from google.cloud.securitycenter_v1.types import load_balancer -from google.cloud.securitycenter_v1.types import log_entry -from google.cloud.securitycenter_v1.types import mitre_attack -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notebook -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import org_policy -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import process -from google.cloud.securitycenter_v1.types import resource -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import security_posture -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import toxic_combination -from google.cloud.securitycenter_v1.types import valued_resource -from google.cloud.securitycenter_v1.types import vulnerability -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 empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .transports.rest import SecurityCenterRestTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - _transport_registry["rest"] = SecurityCenterRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SecurityCenterTransport]: - """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V1 APIs for Security Center 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 = "securitycenter.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: - SecurityCenterClient: 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: - SecurityCenterClient: 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) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def asset_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified asset string.""" - return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_asset_path(path: str) -> Dict[str,str]: - """Parses a asset path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def attack_path_path(organization: str,simulation: str,valued_resource: str,attack_path: str,) -> str: - """Returns a fully-qualified attack_path string.""" - return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) - - @staticmethod - def parse_attack_path_path(path: str) -> Dict[str,str]: - """Parses a attack_path path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?P.+?)/attackPaths/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def big_query_export_path(organization: str,export: str,) -> str: - """Returns a fully-qualified big_query_export string.""" - return "organizations/{organization}/bigQueryExports/{export}".format(organization=organization, export=export, ) - - @staticmethod - def parse_big_query_export_path(path: str) -> Dict[str,str]: - """Parses a big_query_export path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/bigQueryExports/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def dlp_job_path(project: str,dlp_job: str,) -> str: - """Returns a fully-qualified dlp_job string.""" - return "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) - - @staticmethod - def parse_dlp_job_path(path: str) -> Dict[str,str]: - """Parses a dlp_job path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/dlpJobs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def effective_event_threat_detection_custom_module_path(organization: str,module: str,) -> str: - """Returns a fully-qualified effective_event_threat_detection_custom_module string.""" - return "organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}".format(organization=organization, module=module, ) - - @staticmethod - def parse_effective_event_threat_detection_custom_module_path(path: str) -> Dict[str,str]: - """Parses a effective_event_threat_detection_custom_module path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/eventThreatDetectionSettings/effectiveCustomModules/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def effective_security_health_analytics_custom_module_path(organization: str,effective_custom_module: str,) -> str: - """Returns a fully-qualified effective_security_health_analytics_custom_module string.""" - return "organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{effective_custom_module}".format(organization=organization, effective_custom_module=effective_custom_module, ) - - @staticmethod - def parse_effective_security_health_analytics_custom_module_path(path: str) -> Dict[str,str]: - """Parses a effective_security_health_analytics_custom_module path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/securityHealthAnalyticsSettings/effectiveCustomModules/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def event_threat_detection_custom_module_path(organization: str,module: str,) -> str: - """Returns a fully-qualified event_threat_detection_custom_module string.""" - return "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}".format(organization=organization, module=module, ) - - @staticmethod - def parse_event_threat_detection_custom_module_path(path: str) -> Dict[str,str]: - """Parses a event_threat_detection_custom_module path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/eventThreatDetectionSettings/customModules/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def external_system_path(organization: str,source: str,finding: str,externalsystem: str,) -> str: - """Returns a fully-qualified external_system string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) - - @staticmethod - def parse_external_system_path(path: str) -> Dict[str,str]: - """Parses a external_system path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)/externalSystems/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def finding_path(organization: str,source: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def mute_config_path(organization: str,mute_config: str,) -> str: - """Returns a fully-qualified mute_config string.""" - return "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) - - @staticmethod - def parse_mute_config_path(path: str) -> Dict[str,str]: - """Parses a mute_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/muteConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def notification_config_path(organization: str,notification_config: str,) -> str: - """Returns a fully-qualified notification_config string.""" - return "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) - - @staticmethod - def parse_notification_config_path(path: str) -> Dict[str,str]: - """Parses a notification_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def organization_settings_path(organization: str,) -> str: - """Returns a fully-qualified organization_settings string.""" - return "organizations/{organization}/organizationSettings".format(organization=organization, ) - - @staticmethod - def parse_organization_settings_path(path: str) -> Dict[str,str]: - """Parses a organization_settings path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) - return m.groupdict() if m else {} - - @staticmethod - def policy_path(organization: str,constraint_name: str,) -> str: - """Returns a fully-qualified policy string.""" - return "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) - - @staticmethod - def parse_policy_path(path: str) -> Dict[str,str]: - """Parses a policy path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/policies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def resource_value_config_path(organization: str,resource_value_config: str,) -> str: - """Returns a fully-qualified resource_value_config string.""" - return "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) - - @staticmethod - def parse_resource_value_config_path(path: str) -> Dict[str,str]: - """Parses a resource_value_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/resourceValueConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_health_analytics_custom_module_path(organization: str,custom_module: str,) -> str: - """Returns a fully-qualified security_health_analytics_custom_module string.""" - return "organizations/{organization}/securityHealthAnalyticsSettings/customModules/{custom_module}".format(organization=organization, custom_module=custom_module, ) - - @staticmethod - def parse_security_health_analytics_custom_module_path(path: str) -> Dict[str,str]: - """Parses a security_health_analytics_custom_module path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/securityHealthAnalyticsSettings/customModules/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str,str]: - """Parses a security_marks path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) - return m.groupdict() if m else {} - - @staticmethod - def simulation_path(organization: str,simulation: str,) -> str: - """Returns a fully-qualified simulation string.""" - return "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) - - @staticmethod - def parse_simulation_path(path: str) -> Dict[str,str]: - """Parses a simulation path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str,source: str,) -> str: - """Returns a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str,str]: - """Parses a source path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def table_data_profile_path(project: str,table_profile: str,) -> str: - """Returns a fully-qualified table_data_profile string.""" - return "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) - - @staticmethod - def parse_table_data_profile_path(path: str) -> Dict[str,str]: - """Parses a table_data_profile path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/tableProfiles/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def topic_path(project: str,topic: str,) -> str: - """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - - @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: - """Parses a topic path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def valued_resource_path(organization: str,simulation: str,valued_resource: str,) -> str: - """Returns a fully-qualified valued_resource string.""" - return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) - - @staticmethod - def parse_valued_resource_path(path: str) -> Dict[str,str]: - """Parses a valued_resource path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 - SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient._read_environment_variables() - self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) - if transport_provided: - # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( - type(self).get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., SecurityCenterTransport], 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 bulk_mute_findings(self, - request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), - ) -> operation.Operation: - r"""Kicks off an LRO to bulk mute findings for a parent - based on a filter. The parent can be either an - organization, folder or project. The findings matched by - the filter will be muted after the LRO is done. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest, dict]): - The request object. Request message for bulk findings - update. - Note: - - 1. If multiple bulk update requests - match the same resource, the order - in which they get executed is not - defined. - 2. Once a bulk operation is started, - there is no way to stop it. - parent (str): - Required. The parent, at which bulk action needs to be - applied. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1.types.BulkMuteFindingsResponse` - The response to a BulkMute request. Contains the LRO - 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): - request = securitycenter_service.BulkMuteFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.bulk_mute_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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - securitycenter_service.BulkMuteFindingsResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - def create_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - parent: Optional[str] = None, - security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Creates a resident - SecurityHealthAnalyticsCustomModule at the scope of the - given CRM parent, and also creates inherited - SecurityHealthAnalyticsCustomModules for all CRM - descendants of the given parent. These modules are - enabled by default. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_create_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Request message for creating Security - Health Analytics custom modules. - parent (str): - Required. Resource name of the new custom module's - parent. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): - Required. SecurityHealthAnalytics - custom module to create. The provided - name is ignored and reset with provided - parent information and server-generated - ID. - - This corresponds to the ``security_health_analytics_custom_module`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, security_health_analytics_custom_module]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if security_health_analytics_custom_module is not None: - request.security_health_analytics_custom_module = security_health_analytics_custom_module - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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 create_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v1 - - def sample_create_source(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateSourceRequest, dict]): - The request object. Request message for creating a - source. - parent (str): - Required. Resource name of the new source's parent. Its - format should be ``organizations/[organization_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (google.cloud.securitycenter_v1.types.Source): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding_id: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_create_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateFindingRequest, dict]): - The request object. Request message for creating a - finding. - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - ``organizations/[organization_id]/sources/[source_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (google.cloud.securitycenter_v1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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 create_mute_config(self, - request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - mute_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Creates a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_create_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = client.create_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateMuteConfigRequest, dict]): - The request object. Request message for creating a mute - config. - parent (str): - Required. Resource name of the new mute configs's - parent. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config (google.cloud.securitycenter_v1.types.MuteConfig): - Required. The mute config being - created. - - This corresponds to the ``mute_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``mute_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.cloud.securitycenter_v1.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): - request = securitycenter_service.CreateMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if mute_config is not None: - request.mute_config = mute_config - if mute_config_id is not None: - request.mute_config_id = mute_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_mute_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 create_notification_config(self, - request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - config_id: Optional[str] = None, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_create_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = client.create_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest, dict]): - The request object. Request message for creating a - notification config. - parent (str): - Required. Resource name of the new notification config's - parent. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (str): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters and contain - alphanumeric characters, underscores, or - hyphens only. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_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.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_notification_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_mute_config(self, - request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_delete_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_mute_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest, dict]): - The request object. Request message for deleting a mute - config. - name (str): - Required. Name of the mute config to delete. Its format - is - ``organizations/{organization}/muteConfigs/{config_id}``, - ``folders/{folder}/muteConfigs/{config_id}``, - ``projects/{project}/muteConfigs/{config_id}``, - ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, - ``folders/{folder}/locations/global/muteConfigs/{config_id}``, - or - ``projects/{project}/locations/global/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): - request = securitycenter_service.DeleteMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_mute_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 delete_notification_config(self, - request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest, dict]): - The request object. Request message for deleting a - notification config. - name (str): - Required. Name of the notification config to delete. Its - format is - ``organizations/[organization_id]/notificationConfigs/[config_id]``, - ``folders/[folder_id]/notificationConfigs/[config_id]``, - or - ``projects/[project_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 delete_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]] = 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 - SecurityHealthAnalyticsCustomModule and all of its - descendants in the CRM hierarchy. This method is only - supported for resident custom modules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_delete_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - client.delete_security_health_analytics_custom_module(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Request message for deleting Security - Health Analytics custom modules. - name (str): - Required. Name of the custom module to delete. Its - format is - ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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, securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - 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_simulation(self, - request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> simulation.Simulation: - r"""Get the simulation by name or the latest simulation - for the given organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_simulation(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = client.get_simulation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetSimulationRequest, dict]): - The request object. Request message for getting - simulation. Simulation name can include - "latest" to retrieve the latest - simulation For example, - "organizations/123/simulations/latest". - name (str): - Required. The organization name or simulation name of - this simulation - - Valid format: - ``organizations/{organization}/simulations/latest`` - ``organizations/{organization}/simulations/{simulation}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Simulation: - Attack path simulation - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSimulationRequest): - request = securitycenter_service.GetSimulationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_simulation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_valued_resource(self, - request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> valued_resource.ValuedResource: - r"""Get the valued resource by 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 import securitycenter_v1 - - def sample_get_valued_resource(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_valued_resource(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetValuedResourceRequest, dict]): - The request object. Request message for getting a valued - resource. - name (str): - Required. The name of this valued resource - - Valid format: - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v1.types.ValuedResource: - A resource that is determined to have - value to a user's system - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetValuedResourceRequest): - request = securitycenter_service.GetValuedResourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_valued_resource] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_big_query_export(self, - request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Gets a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = client.get_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetBigQueryExportRequest, dict]): - The request object. Request message for retrieving a - BigQuery export. - name (str): - Required. Name of the BigQuery export to retrieve. Its - format is - ``organizations/{organization}/bigQueryExports/{export_id}``, - ``folders/{folder}/bigQueryExports/{export_id}``, or - ``projects/{project}/bigQueryExports/{export_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.cloud.securitycenter_v1.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): - request = securitycenter_service.GetBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 get_mute_config(self, - request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> mute_config.MuteConfig: - r"""Gets a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetMuteConfigRequest, dict]): - The request object. Request message for retrieving a mute - config. - name (str): - Required. Name of the mute config to retrieve. Its - format is - ``organizations/{organization}/muteConfigs/{config_id}``, - ``folders/{folder}/muteConfigs/{config_id}``, - ``projects/{project}/muteConfigs/{config_id}``, - ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, - ``folders/{folder}/locations/global/muteConfigs/{config_id}``, - or - ``projects/{project}/locations/global/muteConfigs/{config_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.cloud.securitycenter_v1.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetMuteConfigRequest): - request = securitycenter_service.GetMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_mute_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 get_notification_config(self, - request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetNotificationConfigRequest, dict]): - The request object. Request message for getting a - notification config. - name (str): - Required. Name of the notification config to get. Its - format is - ``organizations/[organization_id]/notificationConfigs/[config_id]``, - ``folders/[folder_id]/notificationConfigs/[config_id]``, - or - ``projects/[project_id]/notificationConfigs/[config_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.cloud.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 get_organization_settings(self, - request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest, dict]): - The request object. Request message for getting - organization settings. - name (str): - Required. Name of the organization to get organization - settings for. Its format is - ``organizations/[organization_id]/organizationSettings``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_organization_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 get_effective_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: - r"""Retrieves an - EffectiveSecurityHealthAnalyticsCustomModule. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_effective_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_effective_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Request message for getting effective - Security Health Analytics custom - modules. - name (str): - Required. Name of the effective custom module to get. - Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule: - An EffectiveSecurityHealthAnalyticsCustomModule is the representation of - a Security Health Analytics custom module at a - specified level of the resource hierarchy: - organization, folder, or project. If a custom module - is inherited from a parent organization or folder, - the value of the enablementState property in - EffectiveSecurityHealthAnalyticsCustomModule is set - to the value that is effective in the parent, instead - of INHERITED. For example, if the module is enabled - in a parent organization or folder, the effective - enablement_state for the module in all child folders - or projects is also enabled. - EffectiveSecurityHealthAnalyticsCustomModule is - read-only. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_effective_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Retrieves a SecurityHealthAnalyticsCustomModule. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Request message for getting Security - Health Analytics custom modules. - name (str): - Required. Name of the custom module to get. Its format - is - ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v1 - - def sample_get_source(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetSourceRequest, dict]): - The request object. Request message for getting a source. - name (str): - Required. Relative resource name of the source. Its - format is - ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 group_assets(self, - request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_group_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GroupAssetsRequest, dict]): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - warnings.warn("SecurityCenterClient.group_assets is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.GroupAssetsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_group_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GroupFindingsRequest, dict]): - The request object. Request message for grouping by - findings. - parent (str): - Required. Name of the source to groupBy. Its format is - ``organizations/[organization_id]/sources/[source_id]``, - ``folders/[folder_id]/sources/[source_id]``, or - ``projects/[project_id]/sources/[source_id]``. To - groupBy across all sources provide a source_id of ``-``. - For example: - ``organizations/{organization_id}/sources/-, folders/{folder_id}/sources/-``, - or ``projects/{project_id}/sources/-`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (str): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported when compare_duration - is set: - - - state_change - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_assets(self, - request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsPager: - r"""Lists an organization's assets. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListAssetsRequest, dict]): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsPager: - Response message for listing assets. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - warnings.warn("SecurityCenterClient.list_assets is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListAssetsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_descendant_security_health_analytics_custom_modules(self, - request: Optional[Union[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, 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.ListDescendantSecurityHealthAnalyticsCustomModulesPager: - r"""Returns a list of all resident - SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent’s CRM descendants. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_descendant_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, dict]): - The request object. Request message for listing - descendant Security Health Analytics - custom modules. - parent (str): - Required. Name of parent to list descendant custom - modules. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - 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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager: - Response message for listing - descendant Security Health Analytics - custom modules. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_descendant_security_health_analytics_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListDescendantSecurityHealthAnalyticsCustomModulesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings(self, - request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListFindingsRequest( - parent="parent_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.securitycenter_v1.types.ListFindingsRequest, dict]): - The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.ListFindingsPager: - Response message for listing - findings. - 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.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_mute_configs(self, - request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsPager: - r"""Lists mute configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_mute_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListMuteConfigsRequest, dict]): - The request object. Request message for listing mute - configs at a given scope e.g. - organization, folder or project. - parent (str): - Required. The parent, which owns the collection of mute - configs. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - - 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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsPager: - Response message for listing mute - configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): - request = securitycenter_service.ListMuteConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_mute_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.ListMuteConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_notification_configs(self, - request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsPager: - r"""Lists notification configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest, dict]): - The request object. Request message for listing - notification configs. - parent (str): - Required. The name of the parent in which to list the - notification configurations. Its format is - "organizations/[organization_id]", - "folders/[folder_id]", or "projects/[project_id]". - - 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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListNotificationConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_effective_security_health_analytics_custom_modules(self, - request: Optional[Union[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, 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.ListEffectiveSecurityHealthAnalyticsCustomModulesPager: - r"""Returns a list of all - EffectiveSecurityHealthAnalyticsCustomModules for the - given parent. This includes resident modules defined at - the scope of the parent, and inherited modules, - inherited from CRM ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_effective_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_security_health_analytics_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, dict]): - The request object. Request message for listing effective - Security Health Analytics custom - modules. - parent (str): - Required. Name of parent to list effective custom - modules. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - 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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager: - Response message for listing - effective Security Health Analytics - custom modules. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_effective_security_health_analytics_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListEffectiveSecurityHealthAnalyticsCustomModulesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_security_health_analytics_custom_modules(self, - request: Optional[Union[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, 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.ListSecurityHealthAnalyticsCustomModulesPager: - r"""Returns a list of all - SecurityHealthAnalyticsCustomModules for the given - parent. This includes resident modules defined at the - scope of the parent, and inherited modules, inherited - from CRM ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_security_health_analytics_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest, dict]): - The request object. Request message for listing Security - Health Analytics custom modules. - parent (str): - Required. Name of parent to list custom modules. Its - format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - 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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesPager: - Response message for listing Security - Health Analytics custom modules. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_security_health_analytics_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListSecurityHealthAnalyticsCustomModulesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_sources(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListSourcesRequest, dict]): - The request object. Request message for listing sources. - parent (str): - Required. Resource name of the parent of sources to - list. Its format should be - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - 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.securitycenter_v1.services.security_center.pagers.ListSourcesPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_asset_discovery(self, - request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), - ) -> operation.Operation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS 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 securitycenter_v1 - - def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest, dict]): - The request object. Request message for running asset - discovery for an organization. - parent (str): - Required. Name of the organization to run asset - discovery for. Its format is - ``organizations/[organization_id]``. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` - Response of asset discovery run - - """ - warnings.warn("SecurityCenterClient.run_asset_discovery is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - start_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of 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 securitycenter_v1 - - def sample_set_finding_state(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.SetFindingStateRequest, dict]): - The request object. Request message for updating a - finding's state. - name (str): - Required. The `relative resource - name `__ - of the finding. Example: - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (google.cloud.securitycenter_v1.types.Finding.State): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_mute(self, - request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, - *, - name: Optional[str] = None, - mute: Optional[finding.Finding.Mute] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the mute state of 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 securitycenter_v1 - - def sample_set_mute(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = client.set_mute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.SetMuteRequest, dict]): - The request object. Request message for updating a - finding's mute status. - name (str): - Required. The `relative resource - name `__ - of the finding. Example: - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute (google.cloud.securitycenter_v1.types.Finding.Mute): - Required. The desired state of the - Mute. - - This corresponds to the ``mute`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, mute]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetMuteRequest): - request = securitycenter_service.SetMuteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if mute is not None: - request.mute = mute - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_mute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # 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 - - def simulate_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - parent: Optional[str] = None, - custom_config: Optional[security_health_analytics_custom_config.CustomConfig] = None, - resource: Optional[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: - r"""Simulates a given SecurityHealthAnalyticsCustomModule - and Resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_simulate_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - resource = securitycenter_v1.SimulatedResource() - resource.resource_type = "resource_type_value" - - request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - resource=resource, - ) - - # Make the request - response = client.simulate_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Request message to simulate a - CustomConfig against a given test - resource. Maximum size of the request is - 4 MB by default. - parent (str): - Required. The relative resource name of the - organization, project, or folder. For more information - about relative resource names, see `Relative Resource - Name `__ - Example: ``organizations/{organization_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - custom_config (google.cloud.securitycenter_v1.types.CustomConfig): - Required. The custom configuration - that you need to test. - - This corresponds to the ``custom_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource): - Required. Resource data to simulate - custom module against. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse: - Response message for simulating a SecurityHealthAnalyticsCustomModule - against a given 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, custom_config, resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if custom_config is not None: - request.custom_config = custom_config - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.simulate_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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_external_system(self, - request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, - *, - external_system: Optional[gcs_external_system.ExternalSystem] = None, - update_mask: 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]] = (), - ) -> gcs_external_system.ExternalSystem: - r"""Updates external system. This is for a given 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 securitycenter_v1 - - def sample_update_external_system(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateExternalSystemRequest( - ) - - # Make the request - response = client.update_external_system(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest, dict]): - The request object. Request message for updating a - ExternalSystem resource. - external_system (google.cloud.securitycenter_v1.types.ExternalSystem): - Required. The external system - resource to update. - - This corresponds to the ``external_system`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the external system resource. - If empty all mutable fields 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.cloud.securitycenter_v1.types.ExternalSystem: - Representation of third party - SIEM/SOAR fields within SCC. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): - request = securitycenter_service.UpdateExternalSystemRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if external_system is not None: - request.external_system = external_system - 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_external_system] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("external_system.name", request.external_system.name), - )), - ) - - # Validate the universe 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_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateFindingRequest, dict]): - The request object. Request message for updating or - creating a finding. - finding (google.cloud.securitycenter_v1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe 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_mute_config(self, - request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, - *, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - update_mask: 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]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Updates a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = client.update_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest, dict]): - The request object. Request message for updating a mute - config. - mute_config (google.cloud.securitycenter_v1.types.MuteConfig): - Required. The mute config being - updated. - - This corresponds to the ``mute_config`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): - request = securitycenter_service.UpdateMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if mute_config is not None: - request.mute_config = mute_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_mute_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("mute_config.name", request.mute_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 update_notification_config(self, - request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, - *, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - update_mask: 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]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = client.update_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest, dict]): - The request object. Request message for updating a - notification config. - notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the notification config. - If empty all mutable fields 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.cloud.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_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 update_organization_settings(self, - request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, - *, - organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = client.update_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest, dict]): - The request object. Request message for updating an - organization's settings. - organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_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 update_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, - update_mask: 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]] = (), - ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Updates the SecurityHealthAnalyticsCustomModule under - the given name based on the given update mask. Updating - the enablement state is supported on both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name and custom config of a module is supported - on resident modules only. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( - ) - - # Make the request - response = client.update_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Request message for updating Security - Health Analytics custom modules. - security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): - Required. The SecurityHealthAnalytics - custom module to update. - - This corresponds to the ``security_health_analytics_custom_module`` 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 only fields that - can be updated are ``enablement_state`` and - ``custom_config``. If empty or set to the wildcard value - ``*``, both ``enablement_state`` and ``custom_config`` - are 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.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_health_analytics_custom_module, 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, securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_health_analytics_custom_module is not None: - request.security_health_analytics_custom_module = security_health_analytics_custom_module - 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_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_health_analytics_custom_module.name", request.security_health_analytics_custom_module.name), - )), - ) - - # Validate the universe 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_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v1 - - def sample_update_source(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateSourceRequest, dict]): - The request object. Request message for updating a - source. - source (google.cloud.securitycenter_v1.types.Source): - Required. The source resource to - update. - - This corresponds to the ``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.cloud.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_security_marks(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest, dict]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe 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_big_query_export(self, - request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, - *, - parent: Optional[str] = None, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - big_query_export_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Creates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_create_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = client.create_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest, dict]): - The request object. Request message for creating a - BigQuery export. - parent (str): - Required. The name of the parent resource of the new - BigQuery export. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): - Required. The BigQuery export being - created. - - This corresponds to the ``big_query_export`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``big_query_export_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.cloud.securitycenter_v1.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): - request = securitycenter_service.CreateBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if big_query_export is not None: - request.big_query_export = big_query_export - if big_query_export_id is not None: - request.big_query_export_id = big_query_export_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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_big_query_export(self, - request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - client.delete_big_query_export(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest, dict]): - The request object. Request message for deleting a - BigQuery export. - name (str): - Required. The name of the BigQuery export to delete. Its - format is - ``organizations/{organization}/bigQueryExports/{export_id}``, - ``folders/{folder}/bigQueryExports/{export_id}``, or - ``projects/{project}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): - request = securitycenter_service.DeleteBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - 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_big_query_export(self, - request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, - *, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - update_mask: 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]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Updates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateBigQueryExportRequest( - ) - - # Make the request - response = client.update_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest, dict]): - The request object. Request message for updating a - BigQuery export. - big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): - Required. The BigQuery export being - updated. - - This corresponds to the ``big_query_export`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): - request = securitycenter_service.UpdateBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if big_query_export is not None: - request.big_query_export = big_query_export - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("big_query_export.name", request.big_query_export.name), - )), - ) - - # Validate the universe 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_big_query_exports(self, - request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsPager: - r"""Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are 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 securitycenter_v1 - - def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest, dict]): - The request object. Request message for listing BigQuery - exports at a given scope e.g. - organization, folder or project. - parent (str): - Required. The parent, which owns the collection of - BigQuery exports. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - - 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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsPager: - Response message for listing BigQuery - exports. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): - request = securitycenter_service.ListBigQueryExportsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_big_query_exports] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListBigQueryExportsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - parent: Optional[str] = None, - event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Creates a resident Event Threat Detection custom - module at the scope of the given Resource Manager - parent, and also creates inherited custom modules for - all descendants of the given parent. These modules are - enabled by default. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_create_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest, dict]): - The request object. Request to create an Event Threat - Detection custom module. - parent (str): - Required. The new custom module's parent. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): - Required. The module to create. The - event_threat_detection_custom_module.name will be - ignored and server generated. - - This corresponds to the ``event_threat_detection_custom_module`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, event_threat_detection_custom_module]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if event_threat_detection_custom_module is not None: - request.event_threat_detection_custom_module = event_threat_detection_custom_module - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, dict]] = 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 Event Threat Detection custom - module and all of its descendants in the Resource - Manager hierarchy. This method is only supported for - resident custom modules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_delete_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - client.delete_event_threat_detection_custom_module(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest, dict]): - The request object. Request to delete an Event Threat - Detection custom module. - name (str): - Required. Name of the custom module to delete. - - Its format is: - - - "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}". - - "folders/{folder}/eventThreatDetectionSettings/customModules/{module}". - - "projects/{project}/eventThreatDetectionSettings/customModules/{module}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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, securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - 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_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.GetEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Gets an Event Threat Detection custom module. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest, dict]): - The request object. Request to get an Event Threat - Detection custom module. - name (str): - Required. Name of the custom module to get. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_descendant_event_threat_detection_custom_modules(self, - request: Optional[Union[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, 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.ListDescendantEventThreatDetectionCustomModulesPager: - r"""Lists all resident Event Threat Detection custom - modules under the given Resource Manager parent and its - descendants. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_descendant_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest, dict]): - The request object. Request to list current and - descendant resident Event Threat - Detection custom modules. - parent (str): - Required. Name of the parent to list custom modules - under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - 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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesPager: - Response for listing current and - descendant resident Event Threat - Detection custom modules. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_descendant_event_threat_detection_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListDescendantEventThreatDetectionCustomModulesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_event_threat_detection_custom_modules(self, - request: Optional[Union[securitycenter_service.ListEventThreatDetectionCustomModulesRequest, 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.ListEventThreatDetectionCustomModulesPager: - r"""Lists all Event Threat Detection custom modules for - the given Resource Manager parent. This includes - resident modules defined at the scope of the parent - along with modules inherited from ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_event_threat_detection_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest, dict]): - The request object. Request to list Event Threat - Detection custom modules. - parent (str): - Required. Name of the parent to list custom modules - under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - 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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesPager: - Response for listing Event Threat - Detection custom modules. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListEventThreatDetectionCustomModulesRequest): - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_event_threat_detection_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListEventThreatDetectionCustomModulesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, - update_mask: 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]] = (), - ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Updates the Event Threat Detection custom module with - the given name based on the given update mask. Updating - the enablement state is supported for both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name or configuration of a module is supported - for resident modules only. The type of a module cannot - be changed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( - ) - - # Make the request - response = client.update_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest, dict]): - The request object. Request to update an Event Threat - Detection custom module. - event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): - Required. The module being updated. - This corresponds to the ``event_threat_detection_custom_module`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([event_threat_detection_custom_module, 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, securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if event_threat_detection_custom_module is not None: - request.event_threat_detection_custom_module = event_threat_detection_custom_module - 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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("event_threat_detection_custom_module.name", request.event_threat_detection_custom_module.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def validate_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: - r"""Validates the given Event Threat Detection custom - module. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_validate_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - raw_text="raw_text_value", - type_="type__value", - ) - - # Make the request - response = client.validate_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest, dict]): - The request object. Request to validate an Event Threat - Detection custom module. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse: - Response to validating an Event - Threat Detection custom module. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.validate_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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_effective_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: - r"""Gets an effective Event Threat Detection custom - module at the given level. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_effective_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_effective_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]): - The request object. Request to get an - EffectiveEventThreatDetectionCustomModule. - name (str): - Required. The resource name of the effective Event - Threat Detection custom module. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule: - An EffectiveEventThreatDetectionCustomModule is the representation of - an Event Threat Detection custom module at a - specified level of the resource hierarchy: - organization, folder, or project. If a custom module - is inherited from a parent organization or folder, - the value of the enablement_state property in - EffectiveEventThreatDetectionCustomModule is set to - the value that is effective in the parent, instead of - INHERITED. For example, if the module is enabled in a - parent organization or folder, the effective - enablement_state for the module in all child folders - or projects is also enabled. - EffectiveEventThreatDetectionCustomModule is - read-only. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_effective_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_effective_event_threat_detection_custom_modules(self, - request: Optional[Union[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, 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.ListEffectiveEventThreatDetectionCustomModulesPager: - r"""Lists all effective Event Threat Detection custom - modules for the given parent. This includes resident - modules defined at the scope of the parent along with - modules inherited from its ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_effective_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_event_threat_detection_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest, dict]): - The request object. Request to list effective Event - Threat Detection custom modules. - parent (str): - Required. Name of the parent to list custom modules for. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - 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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesPager: - Response for listing - EffectiveEventThreatDetectionCustomModules. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_effective_event_threat_detection_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListEffectiveEventThreatDetectionCustomModulesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_create_resource_value_configs(self, - request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - r"""Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - requests = securitycenter_v1.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - requests.resource_value_config.resource_value = "NONE" - requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest, dict]): - The request object. Request message to create multiple - resource value configs - parent (str): - Required. Resource name of the new - ResourceValueConfig's parent. The parent - field in the - CreateResourceValueConfigRequest - messages must either be empty or match - this field. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - requests (MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]): - Required. The resource value configs - to be created. - - This corresponds to the ``requests`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse: - Response message for - BatchCreateResourceValueConfigs - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, requests]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): - request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if requests is not None: - request.requests = requests - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_resource_value_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, - ) - - # Done; return the response. - return response - - def delete_resource_value_config(self, - request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_resource_value_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest, dict]): - The request object. Request message to delete resource - value config - name (str): - Required. Name of the - ResourceValueConfig 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. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): - request = securitycenter_service.DeleteResourceValueConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_resource_value_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_resource_value_config(self, - request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resource_value_config.ResourceValueConfig: - r"""Gets a ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest, dict]): - The request object. Request message to get resource value - config - name (str): - Required. Name of the resource value config to retrieve. - Its format is - ``organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v1.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): - request = securitycenter_service.GetResourceValueConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_resource_value_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_resource_value_configs(self, - request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsPager: - r"""Lists all ResourceValueConfigs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest, dict]): - The request object. Request message to list resource - value configs of a parent - parent (str): - Required. The parent, which owns the collection of - resource value configs. Its format is - ``organizations/[organization_id]`` - - 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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsPager: - Response message to list resource - value configs - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): - request = securitycenter_service.ListResourceValueConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_resource_value_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.ListResourceValueConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_resource_value_config(self, - request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, - *, - resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, - update_mask: 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]] = (), - ) -> gcs_resource_value_config.ResourceValueConfig: - r"""Updates an existing ResourceValueConfigs with new - rules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - resource_value_config = securitycenter_v1.ResourceValueConfig() - resource_value_config.resource_value = "NONE" - resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.UpdateResourceValueConfigRequest( - resource_value_config=resource_value_config, - ) - - # Make the request - response = client.update_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest, dict]): - The request object. Request message to update resource - value config - resource_value_config (google.cloud.securitycenter_v1.types.ResourceValueConfig): - Required. The resource value config - being updated. - - This corresponds to the ``resource_value_config`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): - request = securitycenter_service.UpdateResourceValueConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if resource_value_config is not None: - request.resource_value_config = resource_value_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_resource_value_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource_value_config.name", request.resource_value_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 list_valued_resources(self, - request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesPager: - r"""Lists the valued resources for a set of simulation - results and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_valued_resources(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListValuedResourcesRequest, dict]): - The request object. Request message for listing the - valued resources for a given simulation. - parent (str): - Required. Name of parent to list valued resources. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - - 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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesPager: - Response message for listing the - valued resources for a given simulation. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): - request = securitycenter_service.ListValuedResourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_valued_resources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListValuedResourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_attack_paths(self, - request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsPager: - r"""Lists the attack paths for a set of simulation - results or valued resources and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_attack_paths(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListAttackPathsRequest, dict]): - The request object. Request message for listing the - attack paths for a given simulation or - valued resource. - parent (str): - Required. Name of parent to list attack paths. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - - 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.securitycenter_v1.services.security_center.pagers.ListAttackPathsPager: - Response message for listing the - attack paths for a given simulation or - valued resource. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): - request = securitycenter_service.ListAttackPathsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_attack_paths] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListAttackPathsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "SecurityCenterClient": - 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 = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - 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 = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SecurityCenterClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py deleted file mode 100644 index 6fb1704f990d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py +++ /dev/null @@ -1,2333 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.securitycenter_v1.types import attack_path -from google.cloud.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import valued_resource - - -class GroupAssetsPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupAssetsResponse], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - 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[securitycenter_service.GroupAssetsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupAssetsAsyncPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` - attributes are available on the 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[securitycenter_service.GroupAssetsResponse]], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - 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[securitycenter_service.GroupAssetsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` - attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListAssetsResponse], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - 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[securitycenter_service.ListAssetsResponse]: - 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - for page in self.pages: - yield from page.list_assets_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` - attributes are available on the 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[securitycenter_service.ListAssetsResponse]], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - 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[securitycenter_service.ListAssetsResponse]: - 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_assets_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDescendantSecurityHealthAnalyticsCustomModulesPager: - """A pager for iterating through ``list_descendant_security_health_analytics_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``security_health_analytics_custom_modules`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDescendantSecurityHealthAnalyticsCustomModules`` requests and continue to iterate - through the ``security_health_analytics_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse], - request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, - response: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse): - 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 = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) - 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[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: - 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - for page in self.pages: - yield from page.security_health_analytics_custom_modules - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: - """A pager for iterating through ``list_descendant_security_health_analytics_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``security_health_analytics_custom_modules`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDescendantSecurityHealthAnalyticsCustomModules`` requests and continue to iterate - through the ``security_health_analytics_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` - attributes are available on the 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[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]], - request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, - response: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse): - 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 = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) - 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[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: - 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - async def async_generator(): - async for page in self.pages: - for response in page.security_health_analytics_custom_modules: - 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.securitycenter_v1.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_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[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - for page in self.pages: - yield from page.list_findings_results - - 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.securitycenter_v1.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_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[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_findings_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMuteConfigsPager: - """A pager for iterating through ``list_mute_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``mute_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListMuteConfigs`` requests and continue to iterate - through the ``mute_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListMuteConfigsResponse], - request: securitycenter_service.ListMuteConfigsRequest, - response: securitycenter_service.ListMuteConfigsResponse, - *, - 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.securitycenter_v1.types.ListMuteConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListMuteConfigsResponse): - 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 = securitycenter_service.ListMuteConfigsRequest(request) - 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[securitycenter_service.ListMuteConfigsResponse]: - 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[mute_config.MuteConfig]: - for page in self.pages: - yield from page.mute_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMuteConfigsAsyncPager: - """A pager for iterating through ``list_mute_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``mute_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListMuteConfigs`` requests and continue to iterate - through the ``mute_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` - attributes are available on the 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[securitycenter_service.ListMuteConfigsResponse]], - request: securitycenter_service.ListMuteConfigsRequest, - response: securitycenter_service.ListMuteConfigsResponse, - *, - 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.securitycenter_v1.types.ListMuteConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListMuteConfigsResponse): - 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 = securitycenter_service.ListMuteConfigsRequest(request) - 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[securitycenter_service.ListMuteConfigsResponse]: - 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[mute_config.MuteConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.mute_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v1.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - 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[securitycenter_service.ListNotificationConfigsResponse]: - 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[notification_config.NotificationConfig]: - for page in self.pages: - yield from page.notification_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsAsyncPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` - attributes are available on the 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[securitycenter_service.ListNotificationConfigsResponse]], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v1.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - 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[securitycenter_service.ListNotificationConfigsResponse]: - 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[notification_config.NotificationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.notification_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEffectiveSecurityHealthAnalyticsCustomModulesPager: - """A pager for iterating through ``list_effective_security_health_analytics_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``effective_security_health_analytics_custom_modules`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEffectiveSecurityHealthAnalyticsCustomModules`` requests and continue to iterate - through the ``effective_security_health_analytics_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse], - request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, - response: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse): - 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 = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) - 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[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: - 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[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: - for page in self.pages: - yield from page.effective_security_health_analytics_custom_modules - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: - """A pager for iterating through ``list_effective_security_health_analytics_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``effective_security_health_analytics_custom_modules`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEffectiveSecurityHealthAnalyticsCustomModules`` requests and continue to iterate - through the ``effective_security_health_analytics_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` - attributes are available on the 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[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]], - request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, - response: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse): - 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 = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) - 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[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: - 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[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: - async def async_generator(): - async for page in self.pages: - for response in page.effective_security_health_analytics_custom_modules: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSecurityHealthAnalyticsCustomModulesPager: - """A pager for iterating through ``list_security_health_analytics_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``security_health_analytics_custom_modules`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSecurityHealthAnalyticsCustomModules`` requests and continue to iterate - through the ``security_health_analytics_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse], - request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, - response: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse): - 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 = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) - 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[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: - 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - for page in self.pages: - yield from page.security_health_analytics_custom_modules - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSecurityHealthAnalyticsCustomModulesAsyncPager: - """A pager for iterating through ``list_security_health_analytics_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``security_health_analytics_custom_modules`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSecurityHealthAnalyticsCustomModules`` requests and continue to iterate - through the ``security_health_analytics_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` - attributes are available on the 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[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]], - request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, - response: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse): - 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 = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) - 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[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: - 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - async def async_generator(): - async for page in self.pages: - for response in page.security_health_analytics_custom_modules: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` - attributes are available on the 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[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.sources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBigQueryExportsPager: - """A pager for iterating through ``list_big_query_exports`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``big_query_exports`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListBigQueryExports`` requests and continue to iterate - through the ``big_query_exports`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListBigQueryExportsResponse], - request: securitycenter_service.ListBigQueryExportsRequest, - response: securitycenter_service.ListBigQueryExportsResponse, - *, - 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.securitycenter_v1.types.ListBigQueryExportsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse): - 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 = securitycenter_service.ListBigQueryExportsRequest(request) - 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[securitycenter_service.ListBigQueryExportsResponse]: - 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[bigquery_export.BigQueryExport]: - for page in self.pages: - yield from page.big_query_exports - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBigQueryExportsAsyncPager: - """A pager for iterating through ``list_big_query_exports`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``big_query_exports`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListBigQueryExports`` requests and continue to iterate - through the ``big_query_exports`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` - attributes are available on the 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[securitycenter_service.ListBigQueryExportsResponse]], - request: securitycenter_service.ListBigQueryExportsRequest, - response: securitycenter_service.ListBigQueryExportsResponse, - *, - 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.securitycenter_v1.types.ListBigQueryExportsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse): - 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 = securitycenter_service.ListBigQueryExportsRequest(request) - 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[securitycenter_service.ListBigQueryExportsResponse]: - 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[bigquery_export.BigQueryExport]: - async def async_generator(): - async for page in self.pages: - for response in page.big_query_exports: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDescendantEventThreatDetectionCustomModulesPager: - """A pager for iterating through ``list_descendant_event_threat_detection_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``event_threat_detection_custom_modules`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDescendantEventThreatDetectionCustomModules`` requests and continue to iterate - through the ``event_threat_detection_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse], - request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, - response: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse): - 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 = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) - 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[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: - 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - for page in self.pages: - yield from page.event_threat_detection_custom_modules - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDescendantEventThreatDetectionCustomModulesAsyncPager: - """A pager for iterating through ``list_descendant_event_threat_detection_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``event_threat_detection_custom_modules`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDescendantEventThreatDetectionCustomModules`` requests and continue to iterate - through the ``event_threat_detection_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` - attributes are available on the 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[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]], - request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, - response: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse): - 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 = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) - 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[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: - 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - async def async_generator(): - async for page in self.pages: - for response in page.event_threat_detection_custom_modules: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEventThreatDetectionCustomModulesPager: - """A pager for iterating through ``list_event_threat_detection_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``event_threat_detection_custom_modules`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEventThreatDetectionCustomModules`` requests and continue to iterate - through the ``event_threat_detection_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListEventThreatDetectionCustomModulesResponse], - request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, - response: securitycenter_service.ListEventThreatDetectionCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse): - 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 = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) - 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[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: - 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - for page in self.pages: - yield from page.event_threat_detection_custom_modules - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEventThreatDetectionCustomModulesAsyncPager: - """A pager for iterating through ``list_event_threat_detection_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``event_threat_detection_custom_modules`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEventThreatDetectionCustomModules`` requests and continue to iterate - through the ``event_threat_detection_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` - attributes are available on the 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[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]], - request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, - response: securitycenter_service.ListEventThreatDetectionCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse): - 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 = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) - 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[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: - 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - async def async_generator(): - async for page in self.pages: - for response in page.event_threat_detection_custom_modules: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEffectiveEventThreatDetectionCustomModulesPager: - """A pager for iterating through ``list_effective_event_threat_detection_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``effective_event_threat_detection_custom_modules`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEffectiveEventThreatDetectionCustomModules`` requests and continue to iterate - through the ``effective_event_threat_detection_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse], - request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, - response: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse): - 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 = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) - 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[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: - 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[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: - for page in self.pages: - yield from page.effective_event_threat_detection_custom_modules - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEffectiveEventThreatDetectionCustomModulesAsyncPager: - """A pager for iterating through ``list_effective_event_threat_detection_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``effective_event_threat_detection_custom_modules`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEffectiveEventThreatDetectionCustomModules`` requests and continue to iterate - through the ``effective_event_threat_detection_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` - attributes are available on the 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[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]], - request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, - response: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse): - 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 = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) - 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[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: - 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[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: - async def async_generator(): - async for page in self.pages: - for response in page.effective_event_threat_detection_custom_modules: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourceValueConfigsPager: - """A pager for iterating through ``list_resource_value_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``resource_value_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListResourceValueConfigs`` requests and continue to iterate - through the ``resource_value_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListResourceValueConfigsResponse], - request: securitycenter_service.ListResourceValueConfigsRequest, - response: securitycenter_service.ListResourceValueConfigsResponse, - *, - 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.securitycenter_v1.types.ListResourceValueConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse): - 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 = securitycenter_service.ListResourceValueConfigsRequest(request) - 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[securitycenter_service.ListResourceValueConfigsResponse]: - 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[resource_value_config.ResourceValueConfig]: - for page in self.pages: - yield from page.resource_value_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourceValueConfigsAsyncPager: - """A pager for iterating through ``list_resource_value_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``resource_value_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListResourceValueConfigs`` requests and continue to iterate - through the ``resource_value_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` - attributes are available on the 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[securitycenter_service.ListResourceValueConfigsResponse]], - request: securitycenter_service.ListResourceValueConfigsRequest, - response: securitycenter_service.ListResourceValueConfigsResponse, - *, - 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.securitycenter_v1.types.ListResourceValueConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse): - 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 = securitycenter_service.ListResourceValueConfigsRequest(request) - 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[securitycenter_service.ListResourceValueConfigsResponse]: - 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[resource_value_config.ResourceValueConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.resource_value_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListValuedResourcesPager: - """A pager for iterating through ``list_valued_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``valued_resources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListValuedResources`` requests and continue to iterate - through the ``valued_resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListValuedResourcesResponse], - request: securitycenter_service.ListValuedResourcesRequest, - response: securitycenter_service.ListValuedResourcesResponse, - *, - 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.securitycenter_v1.types.ListValuedResourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListValuedResourcesResponse): - 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 = securitycenter_service.ListValuedResourcesRequest(request) - 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[securitycenter_service.ListValuedResourcesResponse]: - 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[valued_resource.ValuedResource]: - for page in self.pages: - yield from page.valued_resources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListValuedResourcesAsyncPager: - """A pager for iterating through ``list_valued_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``valued_resources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListValuedResources`` requests and continue to iterate - through the ``valued_resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` - attributes are available on the 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[securitycenter_service.ListValuedResourcesResponse]], - request: securitycenter_service.ListValuedResourcesRequest, - response: securitycenter_service.ListValuedResourcesResponse, - *, - 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.securitycenter_v1.types.ListValuedResourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListValuedResourcesResponse): - 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 = securitycenter_service.ListValuedResourcesRequest(request) - 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[securitycenter_service.ListValuedResourcesResponse]: - 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[valued_resource.ValuedResource]: - async def async_generator(): - async for page in self.pages: - for response in page.valued_resources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAttackPathsPager: - """A pager for iterating through ``list_attack_paths`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``attack_paths`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAttackPaths`` requests and continue to iterate - through the ``attack_paths`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListAttackPathsResponse], - request: securitycenter_service.ListAttackPathsRequest, - response: securitycenter_service.ListAttackPathsResponse, - *, - 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.securitycenter_v1.types.ListAttackPathsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListAttackPathsResponse): - 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 = securitycenter_service.ListAttackPathsRequest(request) - 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[securitycenter_service.ListAttackPathsResponse]: - 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[attack_path.AttackPath]: - for page in self.pages: - yield from page.attack_paths - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAttackPathsAsyncPager: - """A pager for iterating through ``list_attack_paths`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``attack_paths`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAttackPaths`` requests and continue to iterate - through the ``attack_paths`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` - attributes are available on the 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[securitycenter_service.ListAttackPathsResponse]], - request: securitycenter_service.ListAttackPathsRequest, - response: securitycenter_service.ListAttackPathsResponse, - *, - 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.securitycenter_v1.types.ListAttackPathsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListAttackPathsResponse): - 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 = securitycenter_service.ListAttackPathsRequest(request) - 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[securitycenter_service.ListAttackPathsResponse]: - 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[attack_path.AttackPath]: - async def async_generator(): - async for page in self.pages: - for response in page.attack_paths: - 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-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py deleted file mode 100644 index 9d36139c1a9b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/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 SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .rest import SecurityCenterRestTransport -from .rest import SecurityCenterRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry['grpc'] = SecurityCenterGrpcTransport -_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport -_transport_registry['rest'] = SecurityCenterRestTransport - -__all__ = ( - 'SecurityCenterTransport', - 'SecurityCenterGrpcTransport', - 'SecurityCenterGrpcAsyncIOTransport', - 'SecurityCenterRestTransport', - 'SecurityCenterRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py deleted file mode 100644 index 0e98676ba56d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py +++ /dev/null @@ -1,1251 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.securitycenter_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.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import valued_resource -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 empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'securitycenter.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.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: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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.bulk_mute_findings: gapic_v1.method.wrap_method( - self.bulk_mute_findings, - default_timeout=None, - client_info=client_info, - ), - self.create_security_health_analytics_custom_module: gapic_v1.method.wrap_method( - self.create_security_health_analytics_custom_module, - default_timeout=60.0, - client_info=client_info, - ), - self.create_source: gapic_v1.method.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.create_mute_config: gapic_v1.method.wrap_method( - self.create_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method.wrap_method( - self.create_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_mute_config: gapic_v1.method.wrap_method( - self.delete_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method.wrap_method( - self.delete_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_security_health_analytics_custom_module: gapic_v1.method.wrap_method( - self.delete_security_health_analytics_custom_module, - default_timeout=60.0, - client_info=client_info, - ), - self.get_simulation: gapic_v1.method.wrap_method( - self.get_simulation, - default_timeout=None, - client_info=client_info, - ), - self.get_valued_resource: gapic_v1.method.wrap_method( - self.get_valued_resource, - default_timeout=None, - client_info=client_info, - ), - self.get_big_query_export: gapic_v1.method.wrap_method( - self.get_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_mute_config: gapic_v1.method.wrap_method( - self.get_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.get_notification_config: gapic_v1.method.wrap_method( - self.get_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_organization_settings: gapic_v1.method.wrap_method( - self.get_organization_settings, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_effective_security_health_analytics_custom_module: gapic_v1.method.wrap_method( - self.get_effective_security_health_analytics_custom_module, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_security_health_analytics_custom_module: gapic_v1.method.wrap_method( - self.get_security_health_analytics_custom_module, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_source: gapic_v1.method.wrap_method( - self.get_source, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.group_assets: gapic_v1.method.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_descendant_security_health_analytics_custom_modules: gapic_v1.method.wrap_method( - self.list_descendant_security_health_analytics_custom_modules, - 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=60.0, - ), - default_timeout=60.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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_mute_configs: gapic_v1.method.wrap_method( - self.list_mute_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method.wrap_method( - self.list_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_effective_security_health_analytics_custom_modules: gapic_v1.method.wrap_method( - self.list_effective_security_health_analytics_custom_modules, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_security_health_analytics_custom_modules: gapic_v1.method.wrap_method( - self.list_security_health_analytics_custom_modules, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_sources: gapic_v1.method.wrap_method( - self.list_sources, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.run_asset_discovery: gapic_v1.method.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_mute: gapic_v1.method.wrap_method( - self.set_mute, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.simulate_security_health_analytics_custom_module: gapic_v1.method.wrap_method( - self.simulate_security_health_analytics_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.update_external_system: gapic_v1.method.wrap_method( - self.update_external_system, - default_timeout=None, - client_info=client_info, - ), - self.update_finding: gapic_v1.method.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_mute_config: gapic_v1.method.wrap_method( - self.update_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method.wrap_method( - self.update_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_health_analytics_custom_module: gapic_v1.method.wrap_method( - self.update_security_health_analytics_custom_module, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=client_info, - ), - self.create_big_query_export: gapic_v1.method.wrap_method( - self.create_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.delete_big_query_export: gapic_v1.method.wrap_method( - self.delete_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.update_big_query_export: gapic_v1.method.wrap_method( - self.update_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.list_big_query_exports: gapic_v1.method.wrap_method( - self.list_big_query_exports, - default_timeout=None, - client_info=client_info, - ), - self.create_event_threat_detection_custom_module: gapic_v1.method.wrap_method( - self.create_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.delete_event_threat_detection_custom_module: gapic_v1.method.wrap_method( - self.delete_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.get_event_threat_detection_custom_module: gapic_v1.method.wrap_method( - self.get_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.list_descendant_event_threat_detection_custom_modules: gapic_v1.method.wrap_method( - self.list_descendant_event_threat_detection_custom_modules, - default_timeout=None, - client_info=client_info, - ), - self.list_event_threat_detection_custom_modules: gapic_v1.method.wrap_method( - self.list_event_threat_detection_custom_modules, - default_timeout=None, - client_info=client_info, - ), - self.update_event_threat_detection_custom_module: gapic_v1.method.wrap_method( - self.update_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.validate_event_threat_detection_custom_module: gapic_v1.method.wrap_method( - self.validate_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.get_effective_event_threat_detection_custom_module: gapic_v1.method.wrap_method( - self.get_effective_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.list_effective_event_threat_detection_custom_modules: gapic_v1.method.wrap_method( - self.list_effective_event_threat_detection_custom_modules, - default_timeout=None, - client_info=client_info, - ), - self.batch_create_resource_value_configs: gapic_v1.method.wrap_method( - self.batch_create_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.delete_resource_value_config: gapic_v1.method.wrap_method( - self.delete_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.get_resource_value_config: gapic_v1.method.wrap_method( - self.get_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.list_resource_value_configs: gapic_v1.method.wrap_method( - self.list_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.update_resource_value_config: gapic_v1.method.wrap_method( - self.update_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.list_valued_resources: gapic_v1.method.wrap_method( - self.list_valued_resources, - default_timeout=None, - client_info=client_info, - ), - self.list_attack_paths: gapic_v1.method.wrap_method( - self.list_attack_paths, - 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 bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def create_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], - Union[ - gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] - ]]: - raise NotImplementedError() - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - Union[ - gcs_mute_config.MuteConfig, - Awaitable[gcs_mute_config.MuteConfig] - ]]: - raise NotImplementedError() - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def delete_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - Union[ - simulation.Simulation, - Awaitable[simulation.Simulation] - ]]: - raise NotImplementedError() - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - Union[ - valued_resource.ValuedResource, - Awaitable[valued_resource.ValuedResource] - ]]: - raise NotImplementedError() - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - Union[ - bigquery_export.BigQueryExport, - Awaitable[bigquery_export.BigQueryExport] - ]]: - 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 get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - Union[ - mute_config.MuteConfig, - Awaitable[mute_config.MuteConfig] - ]]: - raise NotImplementedError() - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Union[ - notification_config.NotificationConfig, - Awaitable[notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Union[ - organization_settings.OrganizationSettings, - Awaitable[organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def get_effective_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], - Union[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule, - Awaitable[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule] - ]]: - raise NotImplementedError() - - @property - def get_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], - Union[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - Awaitable[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] - ]]: - raise NotImplementedError() - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Union[ - source.Source, - Awaitable[source.Source] - ]]: - raise NotImplementedError() - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Union[ - securitycenter_service.GroupAssetsResponse, - Awaitable[securitycenter_service.GroupAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Union[ - securitycenter_service.GroupFindingsResponse, - Awaitable[securitycenter_service.GroupFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Union[ - securitycenter_service.ListAssetsResponse, - Awaitable[securitycenter_service.ListAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], - Union[ - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse, - Awaitable[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Union[ - securitycenter_service.ListFindingsResponse, - Awaitable[securitycenter_service.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - Union[ - securitycenter_service.ListMuteConfigsResponse, - Awaitable[securitycenter_service.ListMuteConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Union[ - securitycenter_service.ListNotificationConfigsResponse, - Awaitable[securitycenter_service.ListNotificationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_effective_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], - Union[ - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, - Awaitable[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse] - ]]: - raise NotImplementedError() - - @property - def list_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], - Union[ - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse, - Awaitable[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse] - ]]: - raise NotImplementedError() - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Union[ - securitycenter_service.ListSourcesResponse, - Awaitable[securitycenter_service.ListSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - raise NotImplementedError() - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - 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 test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - @property - def simulate_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], - Union[ - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse, - Awaitable[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse] - ]]: - raise NotImplementedError() - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - Union[ - gcs_external_system.ExternalSystem, - Awaitable[gcs_external_system.ExternalSystem] - ]]: - raise NotImplementedError() - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - Union[ - gcs_mute_config.MuteConfig, - Awaitable[gcs_mute_config.MuteConfig] - ]]: - raise NotImplementedError() - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Union[ - gcs_organization_settings.OrganizationSettings, - Awaitable[gcs_organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def update_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], - Union[ - gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] - ]]: - raise NotImplementedError() - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Union[ - gcs_security_marks.SecurityMarks, - Awaitable[gcs_security_marks.SecurityMarks] - ]]: - raise NotImplementedError() - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - Union[ - bigquery_export.BigQueryExport, - Awaitable[bigquery_export.BigQueryExport] - ]]: - raise NotImplementedError() - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - Union[ - bigquery_export.BigQueryExport, - Awaitable[bigquery_export.BigQueryExport] - ]]: - raise NotImplementedError() - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - Union[ - securitycenter_service.ListBigQueryExportsResponse, - Awaitable[securitycenter_service.ListBigQueryExportsResponse] - ]]: - raise NotImplementedError() - - @property - def create_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], - Union[ - gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, - Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] - ]]: - raise NotImplementedError() - - @property - def delete_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], - Union[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule, - Awaitable[event_threat_detection_custom_module.EventThreatDetectionCustomModule] - ]]: - raise NotImplementedError() - - @property - def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], - Union[ - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse, - Awaitable[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse] - ]]: - raise NotImplementedError() - - @property - def list_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], - Union[ - securitycenter_service.ListEventThreatDetectionCustomModulesResponse, - Awaitable[securitycenter_service.ListEventThreatDetectionCustomModulesResponse] - ]]: - raise NotImplementedError() - - @property - def update_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], - Union[ - gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, - Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] - ]]: - raise NotImplementedError() - - @property - def validate_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], - Union[ - securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse, - Awaitable[securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse] - ]]: - raise NotImplementedError() - - @property - def get_effective_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], - Union[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule, - Awaitable[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule] - ]]: - raise NotImplementedError() - - @property - def list_effective_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], - Union[ - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse, - Awaitable[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse] - ]]: - raise NotImplementedError() - - @property - def batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - Union[ - securitycenter_service.BatchCreateResourceValueConfigsResponse, - Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - Union[ - resource_value_config.ResourceValueConfig, - Awaitable[resource_value_config.ResourceValueConfig] - ]]: - raise NotImplementedError() - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - Union[ - securitycenter_service.ListResourceValueConfigsResponse, - Awaitable[securitycenter_service.ListResourceValueConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - Union[ - gcs_resource_value_config.ResourceValueConfig, - Awaitable[gcs_resource_value_config.ResourceValueConfig] - ]]: - raise NotImplementedError() - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - Union[ - securitycenter_service.ListValuedResourcesResponse, - Awaitable[securitycenter_service.ListValuedResourcesResponse] - ]]: - raise NotImplementedError() - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - Union[ - securitycenter_service.ListAttackPathsResponse, - Awaitable[securitycenter_service.ListAttackPathsResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SecurityCenterTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py deleted file mode 100644 index a8d1ee71ce17..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py +++ /dev/null @@ -1,2103 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import valued_resource -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 empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V1 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: 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 bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - operations_pb2.Operation]: - r"""Return a callable for the bulk mute findings method over gRPC. - - Kicks off an LRO to bulk mute findings for a parent - based on a filter. The parent can be either an - organization, folder or project. The findings matched by - the filter will be muted after the LRO is done. - - Returns: - Callable[[~.BulkMuteFindingsRequest], - ~.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 'bulk_mute_findings' not in self._stubs: - self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/BulkMuteFindings', - request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['bulk_mute_findings'] - - @property - def create_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], - gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - r"""Return a callable for the create security health - analytics custom module method over gRPC. - - Creates a resident - SecurityHealthAnalyticsCustomModule at the scope of the - given CRM parent, and also creates inherited - SecurityHealthAnalyticsCustomModules for all CRM - descendants of the given parent. These modules are - enabled by default. - - Returns: - Callable[[~.CreateSecurityHealthAnalyticsCustomModuleRequest], - ~.SecurityHealthAnalyticsCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: - self._stubs['create_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['create_security_health_analytics_custom_module'] - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - r"""Return a callable for the create mute config method over gRPC. - - Creates a mute config. - - Returns: - Callable[[~.CreateMuteConfigRequest], - ~.MuteConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateMuteConfig', - request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['create_mute_config'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete mute config method over gRPC. - - Deletes an existing mute config. - - Returns: - Callable[[~.DeleteMuteConfigRequest], - ~.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_mute_config' not in self._stubs: - self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteMuteConfig', - request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_mute_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - ~.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_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @property - def delete_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete security health - analytics custom module method over gRPC. - - Deletes the specified - SecurityHealthAnalyticsCustomModule and all of its - descendants in the CRM hierarchy. This method is only - supported for resident custom modules. - - Returns: - Callable[[~.DeleteSecurityHealthAnalyticsCustomModuleRequest], - ~.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_security_health_analytics_custom_module' not in self._stubs: - self._stubs['delete_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_security_health_analytics_custom_module'] - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - simulation.Simulation]: - r"""Return a callable for the get simulation method over gRPC. - - Get the simulation by name or the latest simulation - for the given organization. - - Returns: - Callable[[~.GetSimulationRequest], - ~.Simulation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_simulation' not in self._stubs: - self._stubs['get_simulation'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSimulation', - request_serializer=securitycenter_service.GetSimulationRequest.serialize, - response_deserializer=simulation.Simulation.deserialize, - ) - return self._stubs['get_simulation'] - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - valued_resource.ValuedResource]: - r"""Return a callable for the get valued resource method over gRPC. - - Get the valued resource by name - - Returns: - Callable[[~.GetValuedResourceRequest], - ~.ValuedResource]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_valued_resource' not in self._stubs: - self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetValuedResource', - request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, - response_deserializer=valued_resource.ValuedResource.deserialize, - ) - return self._stubs['get_valued_resource'] - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - bigquery_export.BigQueryExport]: - r"""Return a callable for the get big query export method over gRPC. - - Gets a BigQuery export. - - Returns: - Callable[[~.GetBigQueryExportRequest], - ~.BigQueryExport]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_big_query_export' not in self._stubs: - self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetBigQueryExport', - request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['get_big_query_export'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - mute_config.MuteConfig]: - r"""Return a callable for the get mute config method over gRPC. - - Gets a mute config. - - Returns: - Callable[[~.GetMuteConfigRequest], - ~.MuteConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_mute_config' not in self._stubs: - self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetMuteConfig', - request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, - response_deserializer=mute_config.MuteConfig.deserialize, - ) - return self._stubs['get_mute_config'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_effective_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: - r"""Return a callable for the get effective security health - analytics custom module method over gRPC. - - Retrieves an - EffectiveSecurityHealthAnalyticsCustomModule. - - Returns: - Callable[[~.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], - ~.EffectiveSecurityHealthAnalyticsCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_effective_security_health_analytics_custom_module' not in self._stubs: - self._stubs['get_effective_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['get_effective_security_health_analytics_custom_module'] - - @property - def get_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - r"""Return a callable for the get security health analytics - custom module method over gRPC. - - Retrieves a SecurityHealthAnalyticsCustomModule. - - Returns: - Callable[[~.GetSecurityHealthAnalyticsCustomModuleRequest], - ~.SecurityHealthAnalyticsCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_security_health_analytics_custom_module' not in self._stubs: - self._stubs['get_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['get_security_health_analytics_custom_module'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - ~.GroupAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: - r"""Return a callable for the list descendant security - health analytics custom modules method over gRPC. - - Returns a list of all resident - SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent’s CRM descendants. - - Returns: - Callable[[~.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], - ~.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_descendant_security_health_analytics_custom_modules' not in self._stubs: - self._stubs['list_descendant_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantSecurityHealthAnalyticsCustomModules', - request_serializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.deserialize, - ) - return self._stubs['list_descendant_security_health_analytics_custom_modules'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - 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.securitycenter.v1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - securitycenter_service.ListMuteConfigsResponse]: - r"""Return a callable for the list mute configs method over gRPC. - - Lists mute configs. - - Returns: - Callable[[~.ListMuteConfigsRequest], - ~.ListMuteConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_mute_configs' not in self._stubs: - self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListMuteConfigs', - request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, - ) - return self._stubs['list_mute_configs'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - ~.ListNotificationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_effective_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: - r"""Return a callable for the list effective security health - analytics custom modules method over gRPC. - - Returns a list of all - EffectiveSecurityHealthAnalyticsCustomModules for the - given parent. This includes resident modules defined at - the scope of the parent, and inherited modules, - inherited from CRM ancestors. - - Returns: - Callable[[~.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], - ~.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_effective_security_health_analytics_custom_modules' not in self._stubs: - self._stubs['list_effective_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveSecurityHealthAnalyticsCustomModules', - request_serializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.deserialize, - ) - return self._stubs['list_effective_security_health_analytics_custom_modules'] - - @property - def list_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: - r"""Return a callable for the list security health analytics - custom modules method over gRPC. - - Returns a list of all - SecurityHealthAnalyticsCustomModules for the given - parent. This includes resident modules defined at the - scope of the parent, and inherited modules, inherited - from CRM ancestors. - - Returns: - Callable[[~.ListSecurityHealthAnalyticsCustomModulesRequest], - ~.ListSecurityHealthAnalyticsCustomModulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_security_health_analytics_custom_modules' not in self._stubs: - self._stubs['list_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListSecurityHealthAnalyticsCustomModules', - request_serializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.deserialize, - ) - return self._stubs['list_security_health_analytics_custom_modules'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - operations_pb2.Operation]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - ~.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 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - ~.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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - finding.Finding]: - r"""Return a callable for the set mute method over gRPC. - - Updates the mute state of a finding. - - Returns: - Callable[[~.SetMuteRequest], - ~.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 'set_mute' not in self._stubs: - self._stubs['set_mute'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SetMute', - request_serializer=securitycenter_service.SetMuteRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_mute'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def simulate_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse]: - r"""Return a callable for the simulate security health - analytics custom module method over gRPC. - - Simulates a given SecurityHealthAnalyticsCustomModule - and Resource. - - Returns: - Callable[[~.SimulateSecurityHealthAnalyticsCustomModuleRequest], - ~.SimulateSecurityHealthAnalyticsCustomModuleResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'simulate_security_health_analytics_custom_module' not in self._stubs: - self._stubs['simulate_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SimulateSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.deserialize, - ) - return self._stubs['simulate_security_health_analytics_custom_module'] - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - gcs_external_system.ExternalSystem]: - r"""Return a callable for the update external system method over gRPC. - - Updates external system. This is for a given finding. - - Returns: - Callable[[~.UpdateExternalSystemRequest], - ~.ExternalSystem]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_external_system' not in self._stubs: - self._stubs['update_external_system'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateExternalSystem', - request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, - response_deserializer=gcs_external_system.ExternalSystem.deserialize, - ) - return self._stubs['update_external_system'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - r"""Return a callable for the update mute config method over gRPC. - - Updates a mute config. - - Returns: - Callable[[~.UpdateMuteConfigRequest], - ~.MuteConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateMuteConfig', - request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['update_mute_config'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], - gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - r"""Return a callable for the update security health - analytics custom module method over gRPC. - - Updates the SecurityHealthAnalyticsCustomModule under - the given name based on the given update mask. Updating - the enablement state is supported on both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name and custom config of a module is supported - on resident modules only. - - Returns: - Callable[[~.UpdateSecurityHealthAnalyticsCustomModuleRequest], - ~.SecurityHealthAnalyticsCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: - self._stubs['update_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['update_security_health_analytics_custom_module'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - r"""Return a callable for the create big query export method over gRPC. - - Creates a BigQuery export. - - Returns: - Callable[[~.CreateBigQueryExportRequest], - ~.BigQueryExport]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateBigQueryExport', - request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['create_big_query_export'] - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete big query export method over gRPC. - - Deletes an existing BigQuery export. - - Returns: - Callable[[~.DeleteBigQueryExportRequest], - ~.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_big_query_export' not in self._stubs: - self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteBigQueryExport', - request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_big_query_export'] - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - r"""Return a callable for the update big query export method over gRPC. - - Updates a BigQuery export. - - Returns: - Callable[[~.UpdateBigQueryExportRequest], - ~.BigQueryExport]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateBigQueryExport', - request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['update_big_query_export'] - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - securitycenter_service.ListBigQueryExportsResponse]: - r"""Return a callable for the list big query exports method over gRPC. - - Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are returned. - - Returns: - Callable[[~.ListBigQueryExportsRequest], - ~.ListBigQueryExportsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_big_query_exports' not in self._stubs: - self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListBigQueryExports', - request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, - response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, - ) - return self._stubs['list_big_query_exports'] - - @property - def create_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], - gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - r"""Return a callable for the create event threat detection - custom module method over gRPC. - - Creates a resident Event Threat Detection custom - module at the scope of the given Resource Manager - parent, and also creates inherited custom modules for - all descendants of the given parent. These modules are - enabled by default. - - Returns: - Callable[[~.CreateEventThreatDetectionCustomModuleRequest], - ~.EventThreatDetectionCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['create_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['create_event_threat_detection_custom_module'] - - @property - def delete_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete event threat detection - custom module method over gRPC. - - Deletes the specified Event Threat Detection custom - module and all of its descendants in the Resource - Manager hierarchy. This method is only supported for - resident custom modules. - - Returns: - Callable[[~.DeleteEventThreatDetectionCustomModuleRequest], - ~.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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['delete_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_event_threat_detection_custom_module'] - - @property - def get_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], - event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - r"""Return a callable for the get event threat detection - custom module method over gRPC. - - Gets an Event Threat Detection custom module. - - Returns: - Callable[[~.GetEventThreatDetectionCustomModuleRequest], - ~.EventThreatDetectionCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_event_threat_detection_custom_module' not in self._stubs: - self._stubs['get_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.GetEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['get_event_threat_detection_custom_module'] - - @property - def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: - r"""Return a callable for the list descendant event threat - detection custom modules method over gRPC. - - Lists all resident Event Threat Detection custom - modules under the given Resource Manager parent and its - descendants. - - Returns: - Callable[[~.ListDescendantEventThreatDetectionCustomModulesRequest], - ~.ListDescendantEventThreatDetectionCustomModulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_descendant_event_threat_detection_custom_modules' not in self._stubs: - self._stubs['list_descendant_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantEventThreatDetectionCustomModules', - request_serializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.deserialize, - ) - return self._stubs['list_descendant_event_threat_detection_custom_modules'] - - @property - def list_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], - securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: - r"""Return a callable for the list event threat detection - custom modules method over gRPC. - - Lists all Event Threat Detection custom modules for - the given Resource Manager parent. This includes - resident modules defined at the scope of the parent - along with modules inherited from ancestors. - - Returns: - Callable[[~.ListEventThreatDetectionCustomModulesRequest], - ~.ListEventThreatDetectionCustomModulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_event_threat_detection_custom_modules' not in self._stubs: - self._stubs['list_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListEventThreatDetectionCustomModules', - request_serializer=securitycenter_service.ListEventThreatDetectionCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListEventThreatDetectionCustomModulesResponse.deserialize, - ) - return self._stubs['list_event_threat_detection_custom_modules'] - - @property - def update_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], - gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - r"""Return a callable for the update event threat detection - custom module method over gRPC. - - Updates the Event Threat Detection custom module with - the given name based on the given update mask. Updating - the enablement state is supported for both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name or configuration of a module is supported - for resident modules only. The type of a module cannot - be changed. - - Returns: - Callable[[~.UpdateEventThreatDetectionCustomModuleRequest], - ~.EventThreatDetectionCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['update_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['update_event_threat_detection_custom_module'] - - @property - def validate_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], - securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse]: - r"""Return a callable for the validate event threat - detection custom module method over gRPC. - - Validates the given Event Threat Detection custom - module. - - Returns: - Callable[[~.ValidateEventThreatDetectionCustomModuleRequest], - ~.ValidateEventThreatDetectionCustomModuleResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['validate_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ValidateEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.deserialize, - ) - return self._stubs['validate_event_threat_detection_custom_module'] - - @property - def get_effective_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: - r"""Return a callable for the get effective event threat - detection custom module method over gRPC. - - Gets an effective Event Threat Detection custom - module at the given level. - - Returns: - Callable[[~.GetEffectiveEventThreatDetectionCustomModuleRequest], - ~.EffectiveEventThreatDetectionCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_effective_event_threat_detection_custom_module' not in self._stubs: - self._stubs['get_effective_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['get_effective_event_threat_detection_custom_module'] - - @property - def list_effective_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: - r"""Return a callable for the list effective event threat - detection custom modules method over gRPC. - - Lists all effective Event Threat Detection custom - modules for the given parent. This includes resident - modules defined at the scope of the parent along with - modules inherited from its ancestors. - - Returns: - Callable[[~.ListEffectiveEventThreatDetectionCustomModulesRequest], - ~.ListEffectiveEventThreatDetectionCustomModulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_effective_event_threat_detection_custom_modules' not in self._stubs: - self._stubs['list_effective_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveEventThreatDetectionCustomModules', - request_serializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.deserialize, - ) - return self._stubs['list_effective_event_threat_detection_custom_modules'] - - @property - def batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - securitycenter_service.BatchCreateResourceValueConfigsResponse]: - r"""Return a callable for the batch create resource value - configs method over gRPC. - - Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - Returns: - Callable[[~.BatchCreateResourceValueConfigsRequest], - ~.BatchCreateResourceValueConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: - self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/BatchCreateResourceValueConfigs', - request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, - ) - return self._stubs['batch_create_resource_value_configs'] - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete resource value config method over gRPC. - - Deletes a ResourceValueConfig. - - Returns: - Callable[[~.DeleteResourceValueConfigRequest], - ~.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_resource_value_config' not in self._stubs: - self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteResourceValueConfig', - request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_resource_value_config'] - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - resource_value_config.ResourceValueConfig]: - r"""Return a callable for the get resource value config method over gRPC. - - Gets a ResourceValueConfig. - - Returns: - Callable[[~.GetResourceValueConfigRequest], - ~.ResourceValueConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_resource_value_config' not in self._stubs: - self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetResourceValueConfig', - request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, - response_deserializer=resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['get_resource_value_config'] - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - securitycenter_service.ListResourceValueConfigsResponse]: - r"""Return a callable for the list resource value configs method over gRPC. - - Lists all ResourceValueConfigs. - - Returns: - Callable[[~.ListResourceValueConfigsRequest], - ~.ListResourceValueConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_resource_value_configs' not in self._stubs: - self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListResourceValueConfigs', - request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, - ) - return self._stubs['list_resource_value_configs'] - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - gcs_resource_value_config.ResourceValueConfig]: - r"""Return a callable for the update resource value config method over gRPC. - - Updates an existing ResourceValueConfigs with new - rules. - - Returns: - Callable[[~.UpdateResourceValueConfigRequest], - ~.ResourceValueConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: - self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateResourceValueConfig', - request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, - response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['update_resource_value_config'] - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - securitycenter_service.ListValuedResourcesResponse]: - r"""Return a callable for the list valued resources method over gRPC. - - Lists the valued resources for a set of simulation - results and filter. - - Returns: - Callable[[~.ListValuedResourcesRequest], - ~.ListValuedResourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_valued_resources' not in self._stubs: - self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListValuedResources', - request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, - response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, - ) - return self._stubs['list_valued_resources'] - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - securitycenter_service.ListAttackPathsResponse]: - r"""Return a callable for the list attack paths method over gRPC. - - Lists the attack paths for a set of simulation - results or valued resources and filter. - - Returns: - Callable[[~.ListAttackPathsRequest], - ~.ListAttackPathsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_attack_paths' not in self._stubs: - self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListAttackPaths', - request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, - response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, - ) - return self._stubs['list_attack_paths'] - - 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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SecurityCenterGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index 9e0a84336159..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,2583 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import valued_resource -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 empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V1 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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._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 bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the bulk mute findings method over gRPC. - - Kicks off an LRO to bulk mute findings for a parent - based on a filter. The parent can be either an - organization, folder or project. The findings matched by - the filter will be muted after the LRO is done. - - Returns: - Callable[[~.BulkMuteFindingsRequest], - 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 'bulk_mute_findings' not in self._stubs: - self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/BulkMuteFindings', - request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['bulk_mute_findings'] - - @property - def create_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]]: - r"""Return a callable for the create security health - analytics custom module method over gRPC. - - Creates a resident - SecurityHealthAnalyticsCustomModule at the scope of the - given CRM parent, and also creates inherited - SecurityHealthAnalyticsCustomModules for all CRM - descendants of the given parent. These modules are - enabled by default. - - Returns: - Callable[[~.CreateSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[~.SecurityHealthAnalyticsCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: - self._stubs['create_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['create_security_health_analytics_custom_module'] - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - 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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - Awaitable[gcs_mute_config.MuteConfig]]: - r"""Return a callable for the create mute config method over gRPC. - - Creates a mute config. - - Returns: - Callable[[~.CreateMuteConfigRequest], - Awaitable[~.MuteConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateMuteConfig', - request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['create_mute_config'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete mute config method over gRPC. - - Deletes an existing mute config. - - Returns: - Callable[[~.DeleteMuteConfigRequest], - 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_mute_config' not in self._stubs: - self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteMuteConfig', - request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_mute_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - 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_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @property - def delete_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete security health - analytics custom module method over gRPC. - - Deletes the specified - SecurityHealthAnalyticsCustomModule and all of its - descendants in the CRM hierarchy. This method is only - supported for resident custom modules. - - Returns: - Callable[[~.DeleteSecurityHealthAnalyticsCustomModuleRequest], - 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_security_health_analytics_custom_module' not in self._stubs: - self._stubs['delete_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_security_health_analytics_custom_module'] - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - Awaitable[simulation.Simulation]]: - r"""Return a callable for the get simulation method over gRPC. - - Get the simulation by name or the latest simulation - for the given organization. - - Returns: - Callable[[~.GetSimulationRequest], - Awaitable[~.Simulation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_simulation' not in self._stubs: - self._stubs['get_simulation'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSimulation', - request_serializer=securitycenter_service.GetSimulationRequest.serialize, - response_deserializer=simulation.Simulation.deserialize, - ) - return self._stubs['get_simulation'] - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - Awaitable[valued_resource.ValuedResource]]: - r"""Return a callable for the get valued resource method over gRPC. - - Get the valued resource by name - - Returns: - Callable[[~.GetValuedResourceRequest], - Awaitable[~.ValuedResource]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_valued_resource' not in self._stubs: - self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetValuedResource', - request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, - response_deserializer=valued_resource.ValuedResource.deserialize, - ) - return self._stubs['get_valued_resource'] - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - Awaitable[bigquery_export.BigQueryExport]]: - r"""Return a callable for the get big query export method over gRPC. - - Gets a BigQuery export. - - Returns: - Callable[[~.GetBigQueryExportRequest], - Awaitable[~.BigQueryExport]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_big_query_export' not in self._stubs: - self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetBigQueryExport', - request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['get_big_query_export'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - Awaitable[mute_config.MuteConfig]]: - r"""Return a callable for the get mute config method over gRPC. - - Gets a mute config. - - Returns: - Callable[[~.GetMuteConfigRequest], - Awaitable[~.MuteConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_mute_config' not in self._stubs: - self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetMuteConfig', - request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, - response_deserializer=mute_config.MuteConfig.deserialize, - ) - return self._stubs['get_mute_config'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Awaitable[notification_config.NotificationConfig]]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Awaitable[organization_settings.OrganizationSettings]]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_effective_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]]: - r"""Return a callable for the get effective security health - analytics custom module method over gRPC. - - Retrieves an - EffectiveSecurityHealthAnalyticsCustomModule. - - Returns: - Callable[[~.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[~.EffectiveSecurityHealthAnalyticsCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_effective_security_health_analytics_custom_module' not in self._stubs: - self._stubs['get_effective_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['get_effective_security_health_analytics_custom_module'] - - @property - def get_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]]: - r"""Return a callable for the get security health analytics - custom module method over gRPC. - - Retrieves a SecurityHealthAnalyticsCustomModule. - - Returns: - Callable[[~.GetSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[~.SecurityHealthAnalyticsCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_security_health_analytics_custom_module' not in self._stubs: - self._stubs['get_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['get_security_health_analytics_custom_module'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Awaitable[securitycenter_service.GroupAssetsResponse]]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - Awaitable[~.GroupAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse]]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Awaitable[securitycenter_service.ListAssetsResponse]]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], - Awaitable[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]]: - r"""Return a callable for the list descendant security - health analytics custom modules method over gRPC. - - Returns a list of all resident - SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent’s CRM descendants. - - Returns: - Callable[[~.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], - Awaitable[~.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_descendant_security_health_analytics_custom_modules' not in self._stubs: - self._stubs['list_descendant_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantSecurityHealthAnalyticsCustomModules', - request_serializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.deserialize, - ) - return self._stubs['list_descendant_security_health_analytics_custom_modules'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - 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.securitycenter.v1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - Awaitable[securitycenter_service.ListMuteConfigsResponse]]: - r"""Return a callable for the list mute configs method over gRPC. - - Lists mute configs. - - Returns: - Callable[[~.ListMuteConfigsRequest], - Awaitable[~.ListMuteConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_mute_configs' not in self._stubs: - self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListMuteConfigs', - request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, - ) - return self._stubs['list_mute_configs'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - Awaitable[~.ListNotificationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_effective_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], - Awaitable[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]]: - r"""Return a callable for the list effective security health - analytics custom modules method over gRPC. - - Returns a list of all - EffectiveSecurityHealthAnalyticsCustomModules for the - given parent. This includes resident modules defined at - the scope of the parent, and inherited modules, - inherited from CRM ancestors. - - Returns: - Callable[[~.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], - Awaitable[~.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_effective_security_health_analytics_custom_modules' not in self._stubs: - self._stubs['list_effective_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveSecurityHealthAnalyticsCustomModules', - request_serializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.deserialize, - ) - return self._stubs['list_effective_security_health_analytics_custom_modules'] - - @property - def list_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], - Awaitable[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]]: - r"""Return a callable for the list security health analytics - custom modules method over gRPC. - - Returns a list of all - SecurityHealthAnalyticsCustomModules for the given - parent. This includes resident modules defined at the - scope of the parent, and inherited modules, inherited - from CRM ancestors. - - Returns: - Callable[[~.ListSecurityHealthAnalyticsCustomModulesRequest], - Awaitable[~.ListSecurityHealthAnalyticsCustomModulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_security_health_analytics_custom_modules' not in self._stubs: - self._stubs['list_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListSecurityHealthAnalyticsCustomModules', - request_serializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.deserialize, - ) - return self._stubs['list_security_health_analytics_custom_modules'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse]]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - 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 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - 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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set mute method over gRPC. - - Updates the mute state of a finding. - - Returns: - Callable[[~.SetMuteRequest], - 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 'set_mute' not in self._stubs: - self._stubs['set_mute'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SetMute', - request_serializer=securitycenter_service.SetMuteRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_mute'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.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.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def simulate_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse]]: - r"""Return a callable for the simulate security health - analytics custom module method over gRPC. - - Simulates a given SecurityHealthAnalyticsCustomModule - and Resource. - - Returns: - Callable[[~.SimulateSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[~.SimulateSecurityHealthAnalyticsCustomModuleResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'simulate_security_health_analytics_custom_module' not in self._stubs: - self._stubs['simulate_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SimulateSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.deserialize, - ) - return self._stubs['simulate_security_health_analytics_custom_module'] - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - Awaitable[gcs_external_system.ExternalSystem]]: - r"""Return a callable for the update external system method over gRPC. - - Updates external system. This is for a given finding. - - Returns: - Callable[[~.UpdateExternalSystemRequest], - Awaitable[~.ExternalSystem]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_external_system' not in self._stubs: - self._stubs['update_external_system'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateExternalSystem', - request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, - response_deserializer=gcs_external_system.ExternalSystem.deserialize, - ) - return self._stubs['update_external_system'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - 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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - Awaitable[gcs_mute_config.MuteConfig]]: - r"""Return a callable for the update mute config method over gRPC. - - Updates a mute config. - - Returns: - Callable[[~.UpdateMuteConfigRequest], - Awaitable[~.MuteConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateMuteConfig', - request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['update_mute_config'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Awaitable[gcs_organization_settings.OrganizationSettings]]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]]: - r"""Return a callable for the update security health - analytics custom module method over gRPC. - - Updates the SecurityHealthAnalyticsCustomModule under - the given name based on the given update mask. Updating - the enablement state is supported on both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name and custom config of a module is supported - on resident modules only. - - Returns: - Callable[[~.UpdateSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[~.SecurityHealthAnalyticsCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: - self._stubs['update_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['update_security_health_analytics_custom_module'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks]]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - Awaitable[bigquery_export.BigQueryExport]]: - r"""Return a callable for the create big query export method over gRPC. - - Creates a BigQuery export. - - Returns: - Callable[[~.CreateBigQueryExportRequest], - Awaitable[~.BigQueryExport]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateBigQueryExport', - request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['create_big_query_export'] - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete big query export method over gRPC. - - Deletes an existing BigQuery export. - - Returns: - Callable[[~.DeleteBigQueryExportRequest], - 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_big_query_export' not in self._stubs: - self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteBigQueryExport', - request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_big_query_export'] - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - Awaitable[bigquery_export.BigQueryExport]]: - r"""Return a callable for the update big query export method over gRPC. - - Updates a BigQuery export. - - Returns: - Callable[[~.UpdateBigQueryExportRequest], - Awaitable[~.BigQueryExport]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateBigQueryExport', - request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['update_big_query_export'] - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - Awaitable[securitycenter_service.ListBigQueryExportsResponse]]: - r"""Return a callable for the list big query exports method over gRPC. - - Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are returned. - - Returns: - Callable[[~.ListBigQueryExportsRequest], - Awaitable[~.ListBigQueryExportsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_big_query_exports' not in self._stubs: - self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListBigQueryExports', - request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, - response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, - ) - return self._stubs['list_big_query_exports'] - - @property - def create_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], - Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]]: - r"""Return a callable for the create event threat detection - custom module method over gRPC. - - Creates a resident Event Threat Detection custom - module at the scope of the given Resource Manager - parent, and also creates inherited custom modules for - all descendants of the given parent. These modules are - enabled by default. - - Returns: - Callable[[~.CreateEventThreatDetectionCustomModuleRequest], - Awaitable[~.EventThreatDetectionCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['create_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['create_event_threat_detection_custom_module'] - - @property - def delete_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete event threat detection - custom module method over gRPC. - - Deletes the specified Event Threat Detection custom - module and all of its descendants in the Resource - Manager hierarchy. This method is only supported for - resident custom modules. - - Returns: - Callable[[~.DeleteEventThreatDetectionCustomModuleRequest], - 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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['delete_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_event_threat_detection_custom_module'] - - @property - def get_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], - Awaitable[event_threat_detection_custom_module.EventThreatDetectionCustomModule]]: - r"""Return a callable for the get event threat detection - custom module method over gRPC. - - Gets an Event Threat Detection custom module. - - Returns: - Callable[[~.GetEventThreatDetectionCustomModuleRequest], - Awaitable[~.EventThreatDetectionCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_event_threat_detection_custom_module' not in self._stubs: - self._stubs['get_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.GetEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['get_event_threat_detection_custom_module'] - - @property - def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], - Awaitable[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]]: - r"""Return a callable for the list descendant event threat - detection custom modules method over gRPC. - - Lists all resident Event Threat Detection custom - modules under the given Resource Manager parent and its - descendants. - - Returns: - Callable[[~.ListDescendantEventThreatDetectionCustomModulesRequest], - Awaitable[~.ListDescendantEventThreatDetectionCustomModulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_descendant_event_threat_detection_custom_modules' not in self._stubs: - self._stubs['list_descendant_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantEventThreatDetectionCustomModules', - request_serializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.deserialize, - ) - return self._stubs['list_descendant_event_threat_detection_custom_modules'] - - @property - def list_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], - Awaitable[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]]: - r"""Return a callable for the list event threat detection - custom modules method over gRPC. - - Lists all Event Threat Detection custom modules for - the given Resource Manager parent. This includes - resident modules defined at the scope of the parent - along with modules inherited from ancestors. - - Returns: - Callable[[~.ListEventThreatDetectionCustomModulesRequest], - Awaitable[~.ListEventThreatDetectionCustomModulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_event_threat_detection_custom_modules' not in self._stubs: - self._stubs['list_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListEventThreatDetectionCustomModules', - request_serializer=securitycenter_service.ListEventThreatDetectionCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListEventThreatDetectionCustomModulesResponse.deserialize, - ) - return self._stubs['list_event_threat_detection_custom_modules'] - - @property - def update_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], - Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]]: - r"""Return a callable for the update event threat detection - custom module method over gRPC. - - Updates the Event Threat Detection custom module with - the given name based on the given update mask. Updating - the enablement state is supported for both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name or configuration of a module is supported - for resident modules only. The type of a module cannot - be changed. - - Returns: - Callable[[~.UpdateEventThreatDetectionCustomModuleRequest], - Awaitable[~.EventThreatDetectionCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['update_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['update_event_threat_detection_custom_module'] - - @property - def validate_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], - Awaitable[securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse]]: - r"""Return a callable for the validate event threat - detection custom module method over gRPC. - - Validates the given Event Threat Detection custom - module. - - Returns: - Callable[[~.ValidateEventThreatDetectionCustomModuleRequest], - Awaitable[~.ValidateEventThreatDetectionCustomModuleResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['validate_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ValidateEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.deserialize, - ) - return self._stubs['validate_event_threat_detection_custom_module'] - - @property - def get_effective_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], - Awaitable[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]]: - r"""Return a callable for the get effective event threat - detection custom module method over gRPC. - - Gets an effective Event Threat Detection custom - module at the given level. - - Returns: - Callable[[~.GetEffectiveEventThreatDetectionCustomModuleRequest], - Awaitable[~.EffectiveEventThreatDetectionCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_effective_event_threat_detection_custom_module' not in self._stubs: - self._stubs['get_effective_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['get_effective_event_threat_detection_custom_module'] - - @property - def list_effective_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], - Awaitable[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]]: - r"""Return a callable for the list effective event threat - detection custom modules method over gRPC. - - Lists all effective Event Threat Detection custom - modules for the given parent. This includes resident - modules defined at the scope of the parent along with - modules inherited from its ancestors. - - Returns: - Callable[[~.ListEffectiveEventThreatDetectionCustomModulesRequest], - Awaitable[~.ListEffectiveEventThreatDetectionCustomModulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_effective_event_threat_detection_custom_modules' not in self._stubs: - self._stubs['list_effective_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveEventThreatDetectionCustomModules', - request_serializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.deserialize, - ) - return self._stubs['list_effective_event_threat_detection_custom_modules'] - - @property - def batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse]]: - r"""Return a callable for the batch create resource value - configs method over gRPC. - - Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - Returns: - Callable[[~.BatchCreateResourceValueConfigsRequest], - Awaitable[~.BatchCreateResourceValueConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: - self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/BatchCreateResourceValueConfigs', - request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, - ) - return self._stubs['batch_create_resource_value_configs'] - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete resource value config method over gRPC. - - Deletes a ResourceValueConfig. - - Returns: - Callable[[~.DeleteResourceValueConfigRequest], - 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_resource_value_config' not in self._stubs: - self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteResourceValueConfig', - request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_resource_value_config'] - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - Awaitable[resource_value_config.ResourceValueConfig]]: - r"""Return a callable for the get resource value config method over gRPC. - - Gets a ResourceValueConfig. - - Returns: - Callable[[~.GetResourceValueConfigRequest], - Awaitable[~.ResourceValueConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_resource_value_config' not in self._stubs: - self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetResourceValueConfig', - request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, - response_deserializer=resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['get_resource_value_config'] - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - Awaitable[securitycenter_service.ListResourceValueConfigsResponse]]: - r"""Return a callable for the list resource value configs method over gRPC. - - Lists all ResourceValueConfigs. - - Returns: - Callable[[~.ListResourceValueConfigsRequest], - Awaitable[~.ListResourceValueConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_resource_value_configs' not in self._stubs: - self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListResourceValueConfigs', - request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, - ) - return self._stubs['list_resource_value_configs'] - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - Awaitable[gcs_resource_value_config.ResourceValueConfig]]: - r"""Return a callable for the update resource value config method over gRPC. - - Updates an existing ResourceValueConfigs with new - rules. - - Returns: - Callable[[~.UpdateResourceValueConfigRequest], - Awaitable[~.ResourceValueConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: - self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateResourceValueConfig', - request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, - response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['update_resource_value_config'] - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - Awaitable[securitycenter_service.ListValuedResourcesResponse]]: - r"""Return a callable for the list valued resources method over gRPC. - - Lists the valued resources for a set of simulation - results and filter. - - Returns: - Callable[[~.ListValuedResourcesRequest], - Awaitable[~.ListValuedResourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_valued_resources' not in self._stubs: - self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListValuedResources', - request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, - response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, - ) - return self._stubs['list_valued_resources'] - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - Awaitable[securitycenter_service.ListAttackPathsResponse]]: - r"""Return a callable for the list attack paths method over gRPC. - - Lists the attack paths for a set of simulation - results or valued resources and filter. - - Returns: - Callable[[~.ListAttackPathsRequest], - Awaitable[~.ListAttackPathsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_attack_paths' not in self._stubs: - self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListAttackPaths', - request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, - response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, - ) - return self._stubs['list_attack_paths'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.bulk_mute_findings: gapic_v1.method_async.wrap_method( - self.bulk_mute_findings, - default_timeout=None, - client_info=client_info, - ), - self.create_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( - self.create_security_health_analytics_custom_module, - default_timeout=60.0, - client_info=client_info, - ), - self.create_source: gapic_v1.method_async.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method_async.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.create_mute_config: gapic_v1.method_async.wrap_method( - self.create_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method_async.wrap_method( - self.create_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_mute_config: gapic_v1.method_async.wrap_method( - self.delete_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method_async.wrap_method( - self.delete_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( - self.delete_security_health_analytics_custom_module, - default_timeout=60.0, - client_info=client_info, - ), - self.get_simulation: gapic_v1.method_async.wrap_method( - self.get_simulation, - default_timeout=None, - client_info=client_info, - ), - self.get_valued_resource: gapic_v1.method_async.wrap_method( - self.get_valued_resource, - default_timeout=None, - client_info=client_info, - ), - self.get_big_query_export: gapic_v1.method_async.wrap_method( - self.get_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( - self.get_iam_policy, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_mute_config: gapic_v1.method_async.wrap_method( - self.get_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.get_notification_config: gapic_v1.method_async.wrap_method( - self.get_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_organization_settings: gapic_v1.method_async.wrap_method( - self.get_organization_settings, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_effective_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( - self.get_effective_security_health_analytics_custom_module, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( - self.get_security_health_analytics_custom_module, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_source: gapic_v1.method_async.wrap_method( - self.get_source, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.group_assets: gapic_v1.method_async.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method_async.wrap_method( - self.group_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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method_async.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_descendant_security_health_analytics_custom_modules: gapic_v1.method_async.wrap_method( - self.list_descendant_security_health_analytics_custom_modules, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method_async.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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_mute_configs: gapic_v1.method_async.wrap_method( - self.list_mute_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method_async.wrap_method( - self.list_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_effective_security_health_analytics_custom_modules: gapic_v1.method_async.wrap_method( - self.list_effective_security_health_analytics_custom_modules, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_security_health_analytics_custom_modules: gapic_v1.method_async.wrap_method( - self.list_security_health_analytics_custom_modules, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_sources: gapic_v1.method_async.wrap_method( - self.list_sources, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.run_asset_discovery: gapic_v1.method_async.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method_async.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_mute: gapic_v1.method_async.wrap_method( - self.set_mute, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( - self.test_iam_permissions, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.simulate_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( - self.simulate_security_health_analytics_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.update_external_system: gapic_v1.method_async.wrap_method( - self.update_external_system, - default_timeout=None, - client_info=client_info, - ), - self.update_finding: gapic_v1.method_async.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_mute_config: gapic_v1.method_async.wrap_method( - self.update_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method_async.wrap_method( - self.update_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method_async.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( - self.update_security_health_analytics_custom_module, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method_async.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method_async.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=client_info, - ), - self.create_big_query_export: gapic_v1.method_async.wrap_method( - self.create_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.delete_big_query_export: gapic_v1.method_async.wrap_method( - self.delete_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.update_big_query_export: gapic_v1.method_async.wrap_method( - self.update_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.list_big_query_exports: gapic_v1.method_async.wrap_method( - self.list_big_query_exports, - default_timeout=None, - client_info=client_info, - ), - self.create_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( - self.create_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.delete_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( - self.delete_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.get_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( - self.get_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.list_descendant_event_threat_detection_custom_modules: gapic_v1.method_async.wrap_method( - self.list_descendant_event_threat_detection_custom_modules, - default_timeout=None, - client_info=client_info, - ), - self.list_event_threat_detection_custom_modules: gapic_v1.method_async.wrap_method( - self.list_event_threat_detection_custom_modules, - default_timeout=None, - client_info=client_info, - ), - self.update_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( - self.update_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.validate_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( - self.validate_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.get_effective_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( - self.get_effective_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.list_effective_event_threat_detection_custom_modules: gapic_v1.method_async.wrap_method( - self.list_effective_event_threat_detection_custom_modules, - default_timeout=None, - client_info=client_info, - ), - self.batch_create_resource_value_configs: gapic_v1.method_async.wrap_method( - self.batch_create_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.delete_resource_value_config: gapic_v1.method_async.wrap_method( - self.delete_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.get_resource_value_config: gapic_v1.method_async.wrap_method( - self.get_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.list_resource_value_configs: gapic_v1.method_async.wrap_method( - self.list_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.update_resource_value_config: gapic_v1.method_async.wrap_method( - self.update_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.list_valued_resources: gapic_v1.method_async.wrap_method( - self.list_valued_resources, - default_timeout=None, - client_info=client_info, - ), - self.list_attack_paths: gapic_v1.method_async.wrap_method( - self.list_attack_paths, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - return 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"] - - -__all__ = ( - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py deleted file mode 100644 index cafbd10f6efa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py +++ /dev/null @@ -1,8529 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # 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 path_template -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 -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -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.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import valued_resource -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SecurityCenterRestInterceptor: - """Interceptor for SecurityCenter. - - 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 SecurityCenterRestTransport. - - .. code-block:: python - class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): - def pre_batch_create_resource_value_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_create_resource_value_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_bulk_mute_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_bulk_mute_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_big_query_export(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_event_threat_detection_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_event_threat_detection_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_mute_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_security_health_analytics_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_security_health_analytics_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_event_threat_detection_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_resource_value_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_security_health_analytics_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_big_query_export(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_effective_event_threat_detection_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_effective_event_threat_detection_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_effective_security_health_analytics_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_effective_security_health_analytics_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_event_threat_detection_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_event_threat_detection_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_mute_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_organization_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_organization_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_resource_value_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_resource_value_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_security_health_analytics_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_security_health_analytics_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_simulation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_simulation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_valued_resource(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_valued_resource(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_assets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_assets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_attack_paths(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_attack_paths(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_big_query_exports(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_big_query_exports(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_descendant_event_threat_detection_custom_modules(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_descendant_event_threat_detection_custom_modules(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_descendant_security_health_analytics_custom_modules(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_descendant_security_health_analytics_custom_modules(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_effective_event_threat_detection_custom_modules(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_effective_event_threat_detection_custom_modules(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_effective_security_health_analytics_custom_modules(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_effective_security_health_analytics_custom_modules(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_event_threat_detection_custom_modules(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_event_threat_detection_custom_modules(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_mute_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_mute_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_notification_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_notification_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_resource_value_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_resource_value_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_security_health_analytics_custom_modules(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_security_health_analytics_custom_modules(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_sources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_sources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_valued_resources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_valued_resources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_run_asset_discovery(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_run_asset_discovery(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_finding_state(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_finding_state(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_mute(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_mute(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_simulate_security_health_analytics_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_simulate_security_health_analytics_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_big_query_export(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_event_threat_detection_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_event_threat_detection_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_external_system(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_external_system(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_mute_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_organization_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_organization_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_resource_value_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_resource_value_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_security_health_analytics_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_security_health_analytics_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_security_marks(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_security_marks(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_validate_event_threat_detection_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_validate_event_threat_detection_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) - client = SecurityCenterClient(transport=transport) - - - """ - def pre_batch_create_resource_value_configs(self, request: securitycenter_service.BatchCreateResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BatchCreateResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_create_resource_value_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_batch_create_resource_value_configs(self, response: securitycenter_service.BatchCreateResourceValueConfigsResponse) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - """Post-rpc interceptor for batch_create_resource_value_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_bulk_mute_findings(self, request: securitycenter_service.BulkMuteFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BulkMuteFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for bulk_mute_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_bulk_mute_findings(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for bulk_mute_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_big_query_export(self, request: securitycenter_service.CreateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: - """Post-rpc interceptor for create_big_query_export - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_event_threat_detection_custom_module(self, request: securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_event_threat_detection_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_event_threat_detection_custom_module(self, response: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - """Post-rpc interceptor for create_event_threat_detection_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for create_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_mute_config(self, request: securitycenter_service.CreateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: - """Post-rpc interceptor for create_mute_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_notification_config(self, request: securitycenter_service.CreateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: - """Post-rpc interceptor for create_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_security_health_analytics_custom_module(self, request: securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_security_health_analytics_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_security_health_analytics_custom_module(self, response: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - """Post-rpc interceptor for create_security_health_analytics_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for create_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_delete_big_query_export(self, request: securitycenter_service.DeleteBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_event_threat_detection_custom_module(self, request: securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_event_threat_detection_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_mute_config(self, request: securitycenter_service.DeleteMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_notification_config(self, request: securitycenter_service.DeleteNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_resource_value_config(self, request: securitycenter_service.DeleteResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteResourceValueConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_resource_value_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_security_health_analytics_custom_module(self, request: securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_security_health_analytics_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_get_big_query_export(self, request: securitycenter_service.GetBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: - """Post-rpc interceptor for get_big_query_export - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_effective_event_threat_detection_custom_module(self, request: securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_effective_event_threat_detection_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_effective_event_threat_detection_custom_module(self, response: effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: - """Post-rpc interceptor for get_effective_event_threat_detection_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_effective_security_health_analytics_custom_module(self, request: securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_effective_security_health_analytics_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_effective_security_health_analytics_custom_module(self, response: effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: - """Post-rpc interceptor for get_effective_security_health_analytics_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_event_threat_detection_custom_module(self, request: securitycenter_service.GetEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_event_threat_detection_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_event_threat_detection_custom_module(self, response: event_threat_detection_custom_module.EventThreatDetectionCustomModule) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: - """Post-rpc interceptor for get_event_threat_detection_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_mute_config(self, request: securitycenter_service.GetMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_mute_config(self, response: mute_config.MuteConfig) -> mute_config.MuteConfig: - """Post-rpc interceptor for get_mute_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_notification_config(self, request: securitycenter_service.GetNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_notification_config(self, response: notification_config.NotificationConfig) -> notification_config.NotificationConfig: - """Post-rpc interceptor for get_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_organization_settings(self, request: securitycenter_service.GetOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_organization_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_organization_settings(self, response: organization_settings.OrganizationSettings) -> organization_settings.OrganizationSettings: - """Post-rpc interceptor for get_organization_settings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_resource_value_config(self, request: securitycenter_service.GetResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetResourceValueConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_resource_value_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_resource_value_config(self, response: resource_value_config.ResourceValueConfig) -> resource_value_config.ResourceValueConfig: - """Post-rpc interceptor for get_resource_value_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_security_health_analytics_custom_module(self, request: securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_security_health_analytics_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_security_health_analytics_custom_module(self, response: security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - """Post-rpc interceptor for get_security_health_analytics_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_simulation(self, request: securitycenter_service.GetSimulationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSimulationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_simulation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_simulation(self, response: simulation.Simulation) -> simulation.Simulation: - """Post-rpc interceptor for get_simulation - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_source(self, response: source.Source) -> source.Source: - """Post-rpc interceptor for get_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_valued_resource(self, request: securitycenter_service.GetValuedResourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetValuedResourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_valued_resource - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_valued_resource(self, response: valued_resource.ValuedResource) -> valued_resource.ValuedResource: - """Post-rpc interceptor for get_valued_resource - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_assets(self, request: securitycenter_service.GroupAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_assets(self, response: securitycenter_service.GroupAssetsResponse) -> securitycenter_service.GroupAssetsResponse: - """Post-rpc interceptor for group_assets - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: - """Post-rpc interceptor for group_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_assets(self, request: securitycenter_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_assets(self, response: securitycenter_service.ListAssetsResponse) -> securitycenter_service.ListAssetsResponse: - """Post-rpc interceptor for list_assets - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_attack_paths(self, request: securitycenter_service.ListAttackPathsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAttackPathsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_attack_paths - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_attack_paths(self, response: securitycenter_service.ListAttackPathsResponse) -> securitycenter_service.ListAttackPathsResponse: - """Post-rpc interceptor for list_attack_paths - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_big_query_exports(self, request: securitycenter_service.ListBigQueryExportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListBigQueryExportsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_big_query_exports - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_big_query_exports(self, response: securitycenter_service.ListBigQueryExportsResponse) -> securitycenter_service.ListBigQueryExportsResponse: - """Post-rpc interceptor for list_big_query_exports - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_descendant_event_threat_detection_custom_modules(self, request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_descendant_event_threat_detection_custom_modules - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_descendant_event_threat_detection_custom_modules(self, response: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse) -> securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse: - """Post-rpc interceptor for list_descendant_event_threat_detection_custom_modules - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_descendant_security_health_analytics_custom_modules(self, request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_descendant_security_health_analytics_custom_modules - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_descendant_security_health_analytics_custom_modules(self, response: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse) -> securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse: - """Post-rpc interceptor for list_descendant_security_health_analytics_custom_modules - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_effective_event_threat_detection_custom_modules(self, request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_effective_event_threat_detection_custom_modules - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_effective_event_threat_detection_custom_modules(self, response: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse) -> securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse: - """Post-rpc interceptor for list_effective_event_threat_detection_custom_modules - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_effective_security_health_analytics_custom_modules(self, request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_effective_security_health_analytics_custom_modules - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_effective_security_health_analytics_custom_modules(self, response: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse) -> securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse: - """Post-rpc interceptor for list_effective_security_health_analytics_custom_modules - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_event_threat_detection_custom_modules(self, request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListEventThreatDetectionCustomModulesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_event_threat_detection_custom_modules - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_event_threat_detection_custom_modules(self, response: securitycenter_service.ListEventThreatDetectionCustomModulesResponse) -> securitycenter_service.ListEventThreatDetectionCustomModulesResponse: - """Post-rpc interceptor for list_event_threat_detection_custom_modules - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. - """ - return request, metadata - - def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: - """Post-rpc interceptor for list_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_mute_configs(self, request: securitycenter_service.ListMuteConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListMuteConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_mute_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_mute_configs(self, response: securitycenter_service.ListMuteConfigsResponse) -> securitycenter_service.ListMuteConfigsResponse: - """Post-rpc interceptor for list_mute_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_notification_configs(self, request: securitycenter_service.ListNotificationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListNotificationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_notification_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_notification_configs(self, response: securitycenter_service.ListNotificationConfigsResponse) -> securitycenter_service.ListNotificationConfigsResponse: - """Post-rpc interceptor for list_notification_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_resource_value_configs(self, request: securitycenter_service.ListResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_resource_value_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_resource_value_configs(self, response: securitycenter_service.ListResourceValueConfigsResponse) -> securitycenter_service.ListResourceValueConfigsResponse: - """Post-rpc interceptor for list_resource_value_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_security_health_analytics_custom_modules(self, request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_security_health_analytics_custom_modules - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_security_health_analytics_custom_modules(self, response: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse) -> securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse: - """Post-rpc interceptor for list_security_health_analytics_custom_modules - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_sources - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: - """Post-rpc interceptor for list_sources - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_valued_resources(self, request: securitycenter_service.ListValuedResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListValuedResourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_valued_resources - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_valued_resources(self, response: securitycenter_service.ListValuedResourcesResponse) -> securitycenter_service.ListValuedResourcesResponse: - """Post-rpc interceptor for list_valued_resources - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_run_asset_discovery(self, request: securitycenter_service.RunAssetDiscoveryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.RunAssetDiscoveryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for run_asset_discovery - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_run_asset_discovery(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for run_asset_discovery - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_set_mute(self, request: securitycenter_service.SetMuteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetMuteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_mute - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_set_mute(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for set_mute - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_simulate_security_health_analytics_custom_module(self, request: securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for simulate_security_health_analytics_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_simulate_security_health_analytics_custom_module(self, response: securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: - """Post-rpc interceptor for simulate_security_health_analytics_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_big_query_export(self, request: securitycenter_service.UpdateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: - """Post-rpc interceptor for update_big_query_export - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_event_threat_detection_custom_module(self, request: securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_event_threat_detection_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_event_threat_detection_custom_module(self, response: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - """Post-rpc interceptor for update_event_threat_detection_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_external_system(self, request: securitycenter_service.UpdateExternalSystemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateExternalSystemRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_external_system - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_external_system(self, response: gcs_external_system.ExternalSystem) -> gcs_external_system.ExternalSystem: - """Post-rpc interceptor for update_external_system - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for update_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_mute_config(self, request: securitycenter_service.UpdateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: - """Post-rpc interceptor for update_mute_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_notification_config(self, request: securitycenter_service.UpdateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: - """Post-rpc interceptor for update_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_organization_settings(self, request: securitycenter_service.UpdateOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_organization_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_organization_settings(self, response: gcs_organization_settings.OrganizationSettings) -> gcs_organization_settings.OrganizationSettings: - """Post-rpc interceptor for update_organization_settings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_resource_value_config(self, request: securitycenter_service.UpdateResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateResourceValueConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_resource_value_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_resource_value_config(self, response: gcs_resource_value_config.ResourceValueConfig) -> gcs_resource_value_config.ResourceValueConfig: - """Post-rpc interceptor for update_resource_value_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_security_health_analytics_custom_module(self, request: securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_security_health_analytics_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_security_health_analytics_custom_module(self, response: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - """Post-rpc interceptor for update_security_health_analytics_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: - """Post-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for update_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_validate_event_threat_detection_custom_module(self, request: securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for validate_event_threat_detection_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_validate_event_threat_detection_custom_module(self, response: securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: - """Post-rpc interceptor for validate_event_threat_detection_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SecurityCenterRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SecurityCenterRestInterceptor - - -class SecurityCenterRestTransport(SecurityCenterTransport): - """REST backend transport for SecurityCenter. - - V1 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SecurityCenterRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 - 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 - ) - 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 SecurityCenterRestInterceptor() - 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=organizations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/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 _BatchCreateResourceValueConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("BatchCreateResourceValueConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.BatchCreateResourceValueConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - r"""Call the batch create resource - value configs method over HTTP. - - Args: - request (~.securitycenter_service.BatchCreateResourceValueConfigsRequest): - The request object. Request message to create multiple - resource value configs - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.BatchCreateResourceValueConfigsResponse: - Response message for - BatchCreateResourceValueConfigs - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/resourceValueConfigs:batchCreate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_create_resource_value_configs(request, metadata) - pb_request = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.BatchCreateResourceValueConfigsResponse() - pb_resp = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_create_resource_value_configs(resp) - return resp - - class _BulkMuteFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("BulkMuteFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.BulkMuteFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the bulk mute findings method over HTTP. - - Args: - request (~.securitycenter_service.BulkMuteFindingsRequest): - The request object. Request message for bulk findings - update. - Note: - - 1. If multiple bulk update requests - match the same resource, the order - in which they get executed is not - defined. - 2. Once a bulk operation is started, - there is no way to stop it. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/findings:bulkMute', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_bulk_mute_findings(request, metadata) - pb_request = securitycenter_service.BulkMuteFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_bulk_mute_findings(resp) - return resp - - class _CreateBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "bigQueryExportId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> bigquery_export.BigQueryExport: - r"""Call the create big query export method over HTTP. - - Args: - request (~.securitycenter_service.CreateBigQueryExportRequest): - The request object. Request message for creating a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.bigquery_export.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/bigQueryExports', - 'body': 'big_query_export', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*}/bigQueryExports', - 'body': 'big_query_export', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/bigQueryExports', - 'body': 'big_query_export', - }, - ] - request, metadata = self._interceptor.pre_create_big_query_export(request, metadata) - pb_request = securitycenter_service.CreateBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = bigquery_export.BigQueryExport() - pb_resp = bigquery_export.BigQueryExport.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_big_query_export(resp) - return resp - - class _CreateEventThreatDetectionCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateEventThreatDetectionCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Call the create event threat - detection custom module method over HTTP. - - Args: - request (~.securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): - The request object. Request to create an Event Threat - Detection custom module. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/customModules', - 'body': 'event_threat_detection_custom_module', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/customModules', - 'body': 'event_threat_detection_custom_module', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/customModules', - 'body': 'event_threat_detection_custom_module', - }, - ] - request, metadata = self._interceptor.pre_create_event_threat_detection_custom_module(request, metadata) - pb_request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - pb_resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_event_threat_detection_custom_module(resp) - return resp - - class _CreateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "findingId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the create finding method over HTTP. - - Args: - request (~.securitycenter_service.CreateFindingRequest): - The request object. Request message for creating a - finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/sources/*}/findings', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_create_finding(request, metadata) - pb_request = securitycenter_service.CreateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_finding(resp) - return resp - - class _CreateMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "muteConfigId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_mute_config.MuteConfig: - r"""Call the create mute config method over HTTP. - - Args: - request (~.securitycenter_service.CreateMuteConfigRequest): - The request object. Request message for creating a mute - config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_mute_config.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/locations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*/locations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/muteConfigs', - 'body': 'mute_config', - }, - ] - request, metadata = self._interceptor.pre_create_mute_config(request, metadata) - pb_request = securitycenter_service.CreateMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_mute_config.MuteConfig() - pb_resp = gcs_mute_config.MuteConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_mute_config(resp) - return resp - - class _CreateNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "configId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_notification_config.NotificationConfig: - r"""Call the create notification - config method over HTTP. - - Args: - request (~.securitycenter_service.CreateNotificationConfigRequest): - The request object. Request message for creating a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/notificationConfigs', - 'body': 'notification_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*}/notificationConfigs', - 'body': 'notification_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/notificationConfigs', - 'body': 'notification_config', - }, - ] - request, metadata = self._interceptor.pre_create_notification_config(request, metadata) - pb_request = securitycenter_service.CreateNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_notification_config.NotificationConfig() - pb_resp = gcs_notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_notification_config(resp) - return resp - - class _CreateSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateSecurityHealthAnalyticsCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Call the create security health - analytics custom module method over HTTP. - - Args: - request (~.securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): - The request object. Request message for creating Security - Health Analytics custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules', - 'body': 'security_health_analytics_custom_module', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules', - 'body': 'security_health_analytics_custom_module', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules', - 'body': 'security_health_analytics_custom_module', - }, - ] - request, metadata = self._interceptor.pre_create_security_health_analytics_custom_module(request, metadata) - pb_request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - pb_resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_security_health_analytics_custom_module(resp) - return resp - - class _CreateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the create source method over HTTP. - - Args: - request (~.securitycenter_service.CreateSourceRequest): - The request object. Request message for creating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/sources', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_create_source(request, metadata) - pb_request = securitycenter_service.CreateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_source(resp) - return resp - - class _DeleteBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete big query export method over HTTP. - - Args: - request (~.securitycenter_service.DeleteBigQueryExportRequest): - The request object. Request message for deleting a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/bigQueryExports/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=folders/*/bigQueryExports/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/bigQueryExports/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_big_query_export(request, metadata) - pb_request = securitycenter_service.DeleteBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteEventThreatDetectionCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteEventThreatDetectionCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete event threat - detection custom module method over HTTP. - - Args: - request (~.securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): - The request object. Request to delete an Event Threat - Detection custom module. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/eventThreatDetectionSettings/customModules/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=folders/*/eventThreatDetectionSettings/customModules/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/eventThreatDetectionSettings/customModules/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_event_threat_detection_custom_module(request, metadata) - pb_request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete mute config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteMuteConfigRequest): - The request object. Request message for deleting a mute - config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=folders/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=folders/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/muteConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_mute_config(request, metadata) - pb_request = securitycenter_service.DeleteMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete notification - config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteNotificationConfigRequest): - The request object. Request message for deleting a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/notificationConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=folders/*/notificationConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/notificationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_notification_config(request, metadata) - pb_request = securitycenter_service.DeleteNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteResourceValueConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteResourceValueConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteResourceValueConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete resource value - config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteResourceValueConfigRequest): - The request object. Request message to delete resource - value config - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/resourceValueConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_resource_value_config(request, metadata) - pb_request = securitycenter_service.DeleteResourceValueConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteSecurityHealthAnalyticsCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete security health - analytics custom module method over HTTP. - - Args: - request (~.securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): - The request object. Request message for deleting Security - Health Analytics custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/securityHealthAnalyticsSettings/customModules/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=folders/*/securityHealthAnalyticsSettings/customModules/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/securityHealthAnalyticsSettings/customModules/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_security_health_analytics_custom_module(request, metadata) - pb_request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _GetBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("GetBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> bigquery_export.BigQueryExport: - r"""Call the get big query export method over HTTP. - - Args: - request (~.securitycenter_service.GetBigQueryExportRequest): - The request object. Request message for retrieving a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.bigquery_export.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/bigQueryExports/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/bigQueryExports/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/bigQueryExports/*}', - }, - ] - request, metadata = self._interceptor.pre_get_big_query_export(request, metadata) - pb_request = securitycenter_service.GetBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = bigquery_export.BigQueryExport() - pb_resp = bigquery_export.BigQueryExport.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_big_query_export(resp) - return resp - - class _GetEffectiveEventThreatDetectionCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("GetEffectiveEventThreatDetectionCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: - r"""Call the get effective event - threat detection custom module method over HTTP. - - Args: - request (~.securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): - The request object. Request to get an - EffectiveEventThreatDetectionCustomModule. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: - An EffectiveEventThreatDetectionCustomModule is the - representation of an Event Threat Detection custom - module at a specified level of the resource hierarchy: - organization, folder, or project. If a custom module is - inherited from a parent organization or folder, the - value of the ``enablement_state`` property in - EffectiveEventThreatDetectionCustomModule is set to the - value that is effective in the parent, instead of - ``INHERITED``. For example, if the module is enabled in - a parent organization or folder, the effective - ``enablement_state`` for the module in all child folders - or projects is also ``enabled``. - EffectiveEventThreatDetectionCustomModule is read-only. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/eventThreatDetectionSettings/effectiveCustomModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/eventThreatDetectionSettings/effectiveCustomModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/eventThreatDetectionSettings/effectiveCustomModules/*}', - }, - ] - request, metadata = self._interceptor.pre_get_effective_event_threat_detection_custom_module(request, metadata) - pb_request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - pb_resp = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_effective_event_threat_detection_custom_module(resp) - return resp - - class _GetEffectiveSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("GetEffectiveSecurityHealthAnalyticsCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: - r"""Call the get effective security - health analytics custom module method over HTTP. - - Args: - request (~.securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): - The request object. Request message for getting effective - Security Health Analytics custom - modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: - An EffectiveSecurityHealthAnalyticsCustomModule is the - representation of a Security Health Analytics custom - module at a specified level of the resource hierarchy: - organization, folder, or project. If a custom module is - inherited from a parent organization or folder, the - value of the ``enablementState`` property in - EffectiveSecurityHealthAnalyticsCustomModule is set to - the value that is effective in the parent, instead of - ``INHERITED``. For example, if the module is enabled in - a parent organization or folder, the effective - enablement_state for the module in all child folders or - projects is also ``enabled``. - EffectiveSecurityHealthAnalyticsCustomModule is - read-only. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}', - }, - ] - request, metadata = self._interceptor.pre_get_effective_security_health_analytics_custom_module(request, metadata) - pb_request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - pb_resp = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_effective_security_health_analytics_custom_module(resp) - return resp - - class _GetEventThreatDetectionCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("GetEventThreatDetectionCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetEventThreatDetectionCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Call the get event threat - detection custom module method over HTTP. - - Args: - request (~.securitycenter_service.GetEventThreatDetectionCustomModuleRequest): - The request object. Request to get an Event Threat - Detection custom module. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.event_threat_detection_custom_module.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/eventThreatDetectionSettings/customModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/eventThreatDetectionSettings/customModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/eventThreatDetectionSettings/customModules/*}', - }, - ] - request, metadata = self._interceptor.pre_get_event_threat_detection_custom_module(request, metadata) - pb_request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - pb_resp = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_event_threat_detection_custom_module(resp) - return resp - - class _GetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=organizations/*/sources/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _GetMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> mute_config.MuteConfig: - r"""Call the get mute config method over HTTP. - - Args: - request (~.securitycenter_service.GetMuteConfigRequest): - The request object. Request message for retrieving a mute - config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.mute_config.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/muteConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_mute_config(request, metadata) - pb_request = securitycenter_service.GetMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = mute_config.MuteConfig() - pb_resp = mute_config.MuteConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_mute_config(resp) - return resp - - class _GetNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> notification_config.NotificationConfig: - r"""Call the get notification config method over HTTP. - - Args: - request (~.securitycenter_service.GetNotificationConfigRequest): - The request object. Request message for getting a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/notificationConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/notificationConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/notificationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_notification_config(request, metadata) - pb_request = securitycenter_service.GetNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = notification_config.NotificationConfig() - pb_resp = notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_notification_config(resp) - return resp - - class _GetOrganizationSettings(SecurityCenterRestStub): - def __hash__(self): - return hash("GetOrganizationSettings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetOrganizationSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> organization_settings.OrganizationSettings: - r"""Call the get organization settings method over HTTP. - - Args: - request (~.securitycenter_service.GetOrganizationSettingsRequest): - The request object. Request message for getting - organization 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: - ~.organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/organizationSettings}', - }, - ] - request, metadata = self._interceptor.pre_get_organization_settings(request, metadata) - pb_request = securitycenter_service.GetOrganizationSettingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = organization_settings.OrganizationSettings() - pb_resp = organization_settings.OrganizationSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_organization_settings(resp) - return resp - - class _GetResourceValueConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetResourceValueConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetResourceValueConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resource_value_config.ResourceValueConfig: - r"""Call the get resource value config method over HTTP. - - Args: - request (~.securitycenter_service.GetResourceValueConfigRequest): - The request object. Request message to get resource value - config - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resource_value_config.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/resourceValueConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_resource_value_config(request, metadata) - pb_request = securitycenter_service.GetResourceValueConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resource_value_config.ResourceValueConfig() - pb_resp = resource_value_config.ResourceValueConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_resource_value_config(resp) - return resp - - class _GetSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSecurityHealthAnalyticsCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Call the get security health - analytics custom module method over HTTP. - - Args: - request (~.securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): - The request object. Request message for getting Security - Health Analytics custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/securityHealthAnalyticsSettings/customModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/securityHealthAnalyticsSettings/customModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/securityHealthAnalyticsSettings/customModules/*}', - }, - ] - request, metadata = self._interceptor.pre_get_security_health_analytics_custom_module(request, metadata) - pb_request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - pb_resp = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_security_health_analytics_custom_module(resp) - return resp - - class _GetSimulation(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSimulation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSimulationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> simulation.Simulation: - r"""Call the get simulation method over HTTP. - - Args: - request (~.securitycenter_service.GetSimulationRequest): - The request object. Request message for getting - simulation. Simulation name can include - "latest" to retrieve the latest - simulation For example, - "organizations/123/simulations/latest". - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.simulation.Simulation: - Attack path simulation - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/simulations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_simulation(request, metadata) - pb_request = securitycenter_service.GetSimulationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = simulation.Simulation() - pb_resp = simulation.Simulation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_simulation(resp) - return resp - - class _GetSource(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> source.Source: - r"""Call the get source method over HTTP. - - Args: - request (~.securitycenter_service.GetSourceRequest): - The request object. Request message for getting a source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/sources/*}', - }, - ] - request, metadata = self._interceptor.pre_get_source(request, metadata) - pb_request = securitycenter_service.GetSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = source.Source() - pb_resp = source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_source(resp) - return resp - - class _GetValuedResource(SecurityCenterRestStub): - def __hash__(self): - return hash("GetValuedResource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetValuedResourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> valued_resource.ValuedResource: - r"""Call the get valued resource method over HTTP. - - Args: - request (~.securitycenter_service.GetValuedResourceRequest): - The request object. Request message for getting a valued - resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.valued_resource.ValuedResource: - A resource that is determined to have - value to a user's system - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/simulations/*/valuedResources/*}', - }, - ] - request, metadata = self._interceptor.pre_get_valued_resource(request, metadata) - pb_request = securitycenter_service.GetValuedResourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = valued_resource.ValuedResource() - pb_resp = valued_resource.ValuedResource.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_valued_resource(resp) - return resp - - class _GroupAssets(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupAssets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupAssetsResponse: - r"""Call the group assets method over HTTP. - - Args: - request (~.securitycenter_service.GroupAssetsRequest): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupAssetsResponse: - Response message for grouping by - assets. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/assets:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*}/assets:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/assets:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_assets(request, metadata) - pb_request = securitycenter_service.GroupAssetsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupAssetsResponse() - pb_resp = securitycenter_service.GroupAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_assets(resp) - return resp - - class _GroupFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupFindingsResponse: - r"""Call the group findings method over HTTP. - - Args: - request (~.securitycenter_service.GroupFindingsRequest): - The request object. Request message for grouping by - findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupFindingsResponse: - Response message for group by - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/sources/*}/findings:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_findings(request, metadata) - pb_request = securitycenter_service.GroupFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupFindingsResponse() - pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_findings(resp) - return resp - - class _ListAssets(SecurityCenterRestStub): - def __hash__(self): - return hash("ListAssets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListAssetsResponse: - r"""Call the list assets method over HTTP. - - Args: - request (~.securitycenter_service.ListAssetsRequest): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListAssetsResponse: - Response message for listing assets. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*}/assets', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*}/assets', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*}/assets', - }, - ] - request, metadata = self._interceptor.pre_list_assets(request, metadata) - pb_request = securitycenter_service.ListAssetsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListAssetsResponse() - pb_resp = securitycenter_service.ListAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_assets(resp) - return resp - - class _ListAttackPaths(SecurityCenterRestStub): - def __hash__(self): - return hash("ListAttackPaths") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListAttackPathsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListAttackPathsResponse: - r"""Call the list attack paths method over HTTP. - - Args: - request (~.securitycenter_service.ListAttackPathsRequest): - The request object. Request message for listing the - attack paths for a given simulation or - valued resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListAttackPathsResponse: - Response message for listing the - attack paths for a given simulation or - valued resource. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/simulations/*}/attackPaths', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/simulations/*/valuedResources/*}/attackPaths', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/simulations/*/attackExposureResults/*}/attackPaths', - }, - ] - request, metadata = self._interceptor.pre_list_attack_paths(request, metadata) - pb_request = securitycenter_service.ListAttackPathsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListAttackPathsResponse() - pb_resp = securitycenter_service.ListAttackPathsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_attack_paths(resp) - return resp - - class _ListBigQueryExports(SecurityCenterRestStub): - def __hash__(self): - return hash("ListBigQueryExports") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListBigQueryExportsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListBigQueryExportsResponse: - r"""Call the list big query exports method over HTTP. - - Args: - request (~.securitycenter_service.ListBigQueryExportsRequest): - The request object. Request message for listing BigQuery - exports at a given scope e.g. - organization, folder or 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: - ~.securitycenter_service.ListBigQueryExportsResponse: - Response message for listing BigQuery - exports. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*}/bigQueryExports', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*}/bigQueryExports', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*}/bigQueryExports', - }, - ] - request, metadata = self._interceptor.pre_list_big_query_exports(request, metadata) - pb_request = securitycenter_service.ListBigQueryExportsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListBigQueryExportsResponse() - pb_resp = securitycenter_service.ListBigQueryExportsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_big_query_exports(resp) - return resp - - class _ListDescendantEventThreatDetectionCustomModules(SecurityCenterRestStub): - def __hash__(self): - return hash("ListDescendantEventThreatDetectionCustomModules") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse: - r"""Call the list descendant event - threat detection custom modules method over HTTP. - - Args: - request (~.securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): - The request object. Request to list current and - descendant resident Event Threat - Detection custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse: - Response for listing current and - descendant resident Event Threat - Detection custom modules. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/customModules:listDescendant', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/customModules:listDescendant', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/customModules:listDescendant', - }, - ] - request, metadata = self._interceptor.pre_list_descendant_event_threat_detection_custom_modules(request, metadata) - pb_request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - pb_resp = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_descendant_event_threat_detection_custom_modules(resp) - return resp - - class _ListDescendantSecurityHealthAnalyticsCustomModules(SecurityCenterRestStub): - def __hash__(self): - return hash("ListDescendantSecurityHealthAnalyticsCustomModules") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse: - r"""Call the list descendant security - health analytics custom modules method over HTTP. - - Args: - request (~.securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - The request object. Request message for listing - descendant Security Health Analytics - custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse: - Response message for listing - descendant Security Health Analytics - custom modules. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules:listDescendant', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules:listDescendant', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules:listDescendant', - }, - ] - request, metadata = self._interceptor.pre_list_descendant_security_health_analytics_custom_modules(request, metadata) - pb_request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - pb_resp = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_descendant_security_health_analytics_custom_modules(resp) - return resp - - class _ListEffectiveEventThreatDetectionCustomModules(SecurityCenterRestStub): - def __hash__(self): - return hash("ListEffectiveEventThreatDetectionCustomModules") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse: - r"""Call the list effective event - threat detection custom modules method over HTTP. - - Args: - request (~.securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): - The request object. Request to list effective Event - Threat Detection custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse: - Response for listing - EffectiveEventThreatDetectionCustomModules. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/effectiveCustomModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/effectiveCustomModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/effectiveCustomModules', - }, - ] - request, metadata = self._interceptor.pre_list_effective_event_threat_detection_custom_modules(request, metadata) - pb_request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - pb_resp = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_effective_event_threat_detection_custom_modules(resp) - return resp - - class _ListEffectiveSecurityHealthAnalyticsCustomModules(SecurityCenterRestStub): - def __hash__(self): - return hash("ListEffectiveSecurityHealthAnalyticsCustomModules") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse: - r"""Call the list effective security - health analytics custom modules method over HTTP. - - Args: - request (~.securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - The request object. Request message for listing effective - Security Health Analytics custom - modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse: - Response message for listing - effective Security Health Analytics - custom modules. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/effectiveCustomModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/effectiveCustomModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/effectiveCustomModules', - }, - ] - request, metadata = self._interceptor.pre_list_effective_security_health_analytics_custom_modules(request, metadata) - pb_request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - pb_resp = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_effective_security_health_analytics_custom_modules(resp) - return resp - - class _ListEventThreatDetectionCustomModules(SecurityCenterRestStub): - def __hash__(self): - return hash("ListEventThreatDetectionCustomModules") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListEventThreatDetectionCustomModulesResponse: - r"""Call the list event threat - detection custom modules method over HTTP. - - Args: - request (~.securitycenter_service.ListEventThreatDetectionCustomModulesRequest): - The request object. Request to list Event Threat - Detection custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListEventThreatDetectionCustomModulesResponse: - Response for listing Event Threat - Detection custom modules. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/customModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/customModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/customModules', - }, - ] - request, metadata = self._interceptor.pre_list_event_threat_detection_custom_modules(request, metadata) - pb_request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - pb_resp = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_event_threat_detection_custom_modules(resp) - return resp - - class _ListFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("ListFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListFindingsResponse: - r"""Call the list findings method over HTTP. - - Args: - request (~.securitycenter_service.ListFindingsRequest): - The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListFindingsResponse: - Response message for listing - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/sources/*}/findings', - }, - ] - request, metadata = self._interceptor.pre_list_findings(request, metadata) - pb_request = securitycenter_service.ListFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListFindingsResponse() - pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_findings(resp) - return resp - - class _ListMuteConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListMuteConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListMuteConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListMuteConfigsResponse: - r"""Call the list mute configs method over HTTP. - - Args: - request (~.securitycenter_service.ListMuteConfigsRequest): - The request object. Request message for listing mute - configs at a given scope e.g. - organization, folder or 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: - ~.securitycenter_service.ListMuteConfigsResponse: - Response message for listing mute - configs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/locations/*/muteConfigs}', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/locations/*/muteConfigs}', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/muteConfigs}', - }, - ] - request, metadata = self._interceptor.pre_list_mute_configs(request, metadata) - pb_request = securitycenter_service.ListMuteConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListMuteConfigsResponse() - pb_resp = securitycenter_service.ListMuteConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_mute_configs(resp) - return resp - - class _ListNotificationConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListNotificationConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListNotificationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListNotificationConfigsResponse: - r"""Call the list notification configs method over HTTP. - - Args: - request (~.securitycenter_service.ListNotificationConfigsRequest): - The request object. Request message for listing - notification configs. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListNotificationConfigsResponse: - Response message for listing - notification configs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*}/notificationConfigs', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*}/notificationConfigs', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*}/notificationConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_notification_configs(request, metadata) - pb_request = securitycenter_service.ListNotificationConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListNotificationConfigsResponse() - pb_resp = securitycenter_service.ListNotificationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_notification_configs(resp) - return resp - - class _ListResourceValueConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListResourceValueConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListResourceValueConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListResourceValueConfigsResponse: - r"""Call the list resource value - configs method over HTTP. - - Args: - request (~.securitycenter_service.ListResourceValueConfigsRequest): - The request object. Request message to list resource - value configs of a parent - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListResourceValueConfigsResponse: - Response message to list resource - value configs - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*}/resourceValueConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_resource_value_configs(request, metadata) - pb_request = securitycenter_service.ListResourceValueConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListResourceValueConfigsResponse() - pb_resp = securitycenter_service.ListResourceValueConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_resource_value_configs(resp) - return resp - - class _ListSecurityHealthAnalyticsCustomModules(SecurityCenterRestStub): - def __hash__(self): - return hash("ListSecurityHealthAnalyticsCustomModules") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse: - r"""Call the list security health - analytics custom modules method over HTTP. - - Args: - request (~.securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): - The request object. Request message for listing Security - Health Analytics custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse: - Response message for listing Security - Health Analytics custom modules. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules', - }, - ] - request, metadata = self._interceptor.pre_list_security_health_analytics_custom_modules(request, metadata) - pb_request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - pb_resp = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_security_health_analytics_custom_modules(resp) - return resp - - class _ListSources(SecurityCenterRestStub): - def __hash__(self): - return hash("ListSources") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListSourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListSourcesResponse: - r"""Call the list sources method over HTTP. - - Args: - request (~.securitycenter_service.ListSourcesRequest): - The request object. Request message for listing sources. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListSourcesResponse: - Response message for listing sources. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*}/sources', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*}/sources', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*}/sources', - }, - ] - request, metadata = self._interceptor.pre_list_sources(request, metadata) - pb_request = securitycenter_service.ListSourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListSourcesResponse() - pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_sources(resp) - return resp - - class _ListValuedResources(SecurityCenterRestStub): - def __hash__(self): - return hash("ListValuedResources") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListValuedResourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListValuedResourcesResponse: - r"""Call the list valued resources method over HTTP. - - Args: - request (~.securitycenter_service.ListValuedResourcesRequest): - The request object. Request message for listing the - valued resources for a given simulation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListValuedResourcesResponse: - Response message for listing the - valued resources for a given simulation. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/simulations/*}/valuedResources', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/simulations/*/attackExposureResults/*}/valuedResources', - }, - ] - request, metadata = self._interceptor.pre_list_valued_resources(request, metadata) - pb_request = securitycenter_service.ListValuedResourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListValuedResourcesResponse() - pb_resp = securitycenter_service.ListValuedResourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_valued_resources(resp) - return resp - - class _RunAssetDiscovery(SecurityCenterRestStub): - def __hash__(self): - return hash("RunAssetDiscovery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.RunAssetDiscoveryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the run asset discovery method over HTTP. - - Args: - request (~.securitycenter_service.RunAssetDiscoveryRequest): - The request object. Request message for running asset - discovery for an organization. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/assets:runDiscovery', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_run_asset_discovery(request, metadata) - pb_request = securitycenter_service.RunAssetDiscoveryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_run_asset_discovery(resp) - return resp - - class _SetFindingState(SecurityCenterRestStub): - def __hash__(self): - return hash("SetFindingState") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SetFindingStateRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the set finding state method over HTTP. - - Args: - request (~.securitycenter_service.SetFindingStateRequest): - The request object. Request message for updating a - finding's state. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=organizations/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=folders/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/sources/*/findings/*}:setState', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_finding_state(request, metadata) - pb_request = securitycenter_service.SetFindingStateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_set_finding_state(resp) - return resp - - class _SetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=organizations/*/sources/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _SetMute(SecurityCenterRestStub): - def __hash__(self): - return hash("SetMute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SetMuteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the set mute method over HTTP. - - Args: - request (~.securitycenter_service.SetMuteRequest): - The request object. Request message for updating a - finding's mute status. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=organizations/*/sources/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=folders/*/sources/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/sources/*/findings/*}:setMute', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_mute(request, metadata) - pb_request = securitycenter_service.SetMuteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_set_mute(resp) - return resp - - class _SimulateSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("SimulateSecurityHealthAnalyticsCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: - r"""Call the simulate security health - analytics custom module method over HTTP. - - Args: - request (~.securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): - The request object. Request message to simulate a - CustomConfig against a given test - resource. Maximum size of the request is - 4 MB by default. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: - Response message for simulating a - ``SecurityHealthAnalyticsCustomModule`` against a given - resource. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules:simulate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules:simulate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules:simulate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_simulate_security_health_analytics_custom_module(request, metadata) - pb_request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - pb_resp = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_simulate_security_health_analytics_custom_module(resp) - return resp - - class _TestIamPermissions(SecurityCenterRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=organizations/*/sources/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UpdateBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> bigquery_export.BigQueryExport: - r"""Call the update big query export method over HTTP. - - Args: - request (~.securitycenter_service.UpdateBigQueryExportRequest): - The request object. Request message for updating a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.bigquery_export.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{big_query_export.name=organizations/*/bigQueryExports/*}', - 'body': 'big_query_export', - }, -{ - 'method': 'patch', - 'uri': '/v1/{big_query_export.name=folders/*/bigQueryExports/*}', - 'body': 'big_query_export', - }, -{ - 'method': 'patch', - 'uri': '/v1/{big_query_export.name=projects/*/bigQueryExports/*}', - 'body': 'big_query_export', - }, - ] - request, metadata = self._interceptor.pre_update_big_query_export(request, metadata) - pb_request = securitycenter_service.UpdateBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = bigquery_export.BigQueryExport() - pb_resp = bigquery_export.BigQueryExport.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_big_query_export(resp) - return resp - - class _UpdateEventThreatDetectionCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateEventThreatDetectionCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Call the update event threat - detection custom module method over HTTP. - - Args: - request (~.securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): - The request object. Request to update an Event Threat - Detection custom module. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{event_threat_detection_custom_module.name=organizations/*/eventThreatDetectionSettings/customModules/*}', - 'body': 'event_threat_detection_custom_module', - }, -{ - 'method': 'patch', - 'uri': '/v1/{event_threat_detection_custom_module.name=folders/*/eventThreatDetectionSettings/customModules/*}', - 'body': 'event_threat_detection_custom_module', - }, -{ - 'method': 'patch', - 'uri': '/v1/{event_threat_detection_custom_module.name=projects/*/eventThreatDetectionSettings/customModules/*}', - 'body': 'event_threat_detection_custom_module', - }, - ] - request, metadata = self._interceptor.pre_update_event_threat_detection_custom_module(request, metadata) - pb_request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - pb_resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_event_threat_detection_custom_module(resp) - return resp - - class _UpdateExternalSystem(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateExternalSystem") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateExternalSystemRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_external_system.ExternalSystem: - r"""Call the update external system method over HTTP. - - Args: - request (~.securitycenter_service.UpdateExternalSystemRequest): - The request object. Request message for updating a - ExternalSystem resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_external_system.ExternalSystem: - Representation of third party - SIEM/SOAR fields within SCC. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v1/{external_system.name=folders/*/sources/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v1/{external_system.name=projects/*/sources/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, - ] - request, metadata = self._interceptor.pre_update_external_system(request, metadata) - pb_request = securitycenter_service.UpdateExternalSystemRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_external_system.ExternalSystem() - pb_resp = gcs_external_system.ExternalSystem.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_external_system(resp) - return resp - - class _UpdateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the update finding method over HTTP. - - Args: - request (~.securitycenter_service.UpdateFindingRequest): - The request object. Request message for updating or - creating a finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{finding.name=organizations/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v1/{finding.name=folders/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v1/{finding.name=projects/*/sources/*/findings/*}', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_update_finding(request, metadata) - pb_request = securitycenter_service.UpdateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_finding(resp) - return resp - - class _UpdateMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_mute_config.MuteConfig: - r"""Call the update mute config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateMuteConfigRequest): - The request object. Request message for updating a mute - config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_mute_config.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{mute_config.name=organizations/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{mute_config.name=folders/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{mute_config.name=projects/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{mute_config.name=organizations/*/locations/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{mute_config.name=folders/*/locations/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{mute_config.name=projects/*/locations/*/muteConfigs/*}', - 'body': 'mute_config', - }, - ] - request, metadata = self._interceptor.pre_update_mute_config(request, metadata) - pb_request = securitycenter_service.UpdateMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_mute_config.MuteConfig() - pb_resp = gcs_mute_config.MuteConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_mute_config(resp) - return resp - - class _UpdateNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_notification_config.NotificationConfig: - r"""Call the update notification - config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateNotificationConfigRequest): - The request object. Request message for updating a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{notification_config.name=organizations/*/notificationConfigs/*}', - 'body': 'notification_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{notification_config.name=folders/*/notificationConfigs/*}', - 'body': 'notification_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{notification_config.name=projects/*/notificationConfigs/*}', - 'body': 'notification_config', - }, - ] - request, metadata = self._interceptor.pre_update_notification_config(request, metadata) - pb_request = securitycenter_service.UpdateNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_notification_config.NotificationConfig() - pb_resp = gcs_notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_notification_config(resp) - return resp - - class _UpdateOrganizationSettings(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateOrganizationSettings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateOrganizationSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Call the update organization - settings method over HTTP. - - Args: - request (~.securitycenter_service.UpdateOrganizationSettingsRequest): - The request object. Request message for updating an - organization's 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: - ~.gcs_organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{organization_settings.name=organizations/*/organizationSettings}', - 'body': 'organization_settings', - }, - ] - request, metadata = self._interceptor.pre_update_organization_settings(request, metadata) - pb_request = securitycenter_service.UpdateOrganizationSettingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_organization_settings.OrganizationSettings() - pb_resp = gcs_organization_settings.OrganizationSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_organization_settings(resp) - return resp - - class _UpdateResourceValueConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateResourceValueConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateResourceValueConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_resource_value_config.ResourceValueConfig: - r"""Call the update resource value - config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateResourceValueConfigRequest): - The request object. Request message to update resource - value config - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_resource_value_config.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{resource_value_config.name=organizations/*/resourceValueConfigs/*}', - 'body': 'resource_value_config', - }, - ] - request, metadata = self._interceptor.pre_update_resource_value_config(request, metadata) - pb_request = securitycenter_service.UpdateResourceValueConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_resource_value_config.ResourceValueConfig() - pb_resp = gcs_resource_value_config.ResourceValueConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_resource_value_config(resp) - return resp - - class _UpdateSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSecurityHealthAnalyticsCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Call the update security health - analytics custom module method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): - The request object. Request message for updating Security - Health Analytics custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{security_health_analytics_custom_module.name=organizations/*/securityHealthAnalyticsSettings/customModules/*}', - 'body': 'security_health_analytics_custom_module', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_health_analytics_custom_module.name=folders/*/securityHealthAnalyticsSettings/customModules/*}', - 'body': 'security_health_analytics_custom_module', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_health_analytics_custom_module.name=projects/*/securityHealthAnalyticsSettings/customModules/*}', - 'body': 'security_health_analytics_custom_module', - }, - ] - request, metadata = self._interceptor.pre_update_security_health_analytics_custom_module(request, metadata) - pb_request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - pb_resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_security_health_analytics_custom_module(resp) - return resp - - class _UpdateSecurityMarks(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSecurityMarks") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSecurityMarksRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_security_marks.SecurityMarks: - r"""Call the update security marks method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSecurityMarksRequest): - The request object. Request message for updating a - SecurityMarks resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{security_marks.name=organizations/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_marks.name=folders/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_marks.name=projects/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, - ] - request, metadata = self._interceptor.pre_update_security_marks(request, metadata) - pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_security_marks.SecurityMarks() - pb_resp = gcs_security_marks.SecurityMarks.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_security_marks(resp) - return resp - - class _UpdateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the update source method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSourceRequest): - The request object. Request message for updating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{source.name=organizations/*/sources/*}', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_update_source(request, metadata) - pb_request = securitycenter_service.UpdateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_source(resp) - return resp - - class _ValidateEventThreatDetectionCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("ValidateEventThreatDetectionCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: - r"""Call the validate event threat - detection custom module method over HTTP. - - Args: - request (~.securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): - The request object. Request to validate an Event Threat - Detection custom module. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: - Response to validating an Event - Threat Detection custom module. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}:validateCustomModule', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}:validateCustomModule', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}:validateCustomModule', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_validate_event_threat_detection_custom_module(request, metadata) - pb_request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() - pb_resp = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_validate_event_threat_detection_custom_module(resp) - return resp - - @property - def batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - securitycenter_service.BatchCreateResourceValueConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchCreateResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - 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._BulkMuteFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], - gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], - gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - 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._DeleteBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], - 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._DeleteEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - 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._DeleteMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - 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._DeleteNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - 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._DeleteResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], - 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._DeleteSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - bigquery_export.BigQueryExport]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_effective_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEffectiveEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_effective_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEffectiveSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], - event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - mute_config.MuteConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - resource_value_config.ResourceValueConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - simulation.Simulation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSimulation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - valued_resource.ValuedResource]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetValuedResource(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - securitycenter_service.ListAttackPathsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListAttackPaths(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - securitycenter_service.ListBigQueryExportsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListBigQueryExports(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDescendantEventThreatDetectionCustomModules(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDescendantSecurityHealthAnalyticsCustomModules(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_effective_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEffectiveEventThreatDetectionCustomModules(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_effective_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEffectiveSecurityHealthAnalyticsCustomModules(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], - securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEventThreatDetectionCustomModules(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.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_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - securitycenter_service.ListMuteConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListMuteConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListNotificationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - securitycenter_service.ListResourceValueConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSecurityHealthAnalyticsCustomModules(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSources(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - securitycenter_service.ListValuedResourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListValuedResources(self._session, self._host, self._interceptor) # type: ignore - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - 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._RunAssetDiscovery(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - 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._SetMute(self._session, self._host, self._interceptor) # type: ignore - - @property - def simulate_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SimulateSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], - gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - gcs_external_system.ExternalSystem]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateExternalSystem(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - gcs_resource_value_config.ResourceValueConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], - gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def validate_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], - securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ValidateEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=organizations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In 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(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In 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(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), 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(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/operations}', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SecurityCenterRestTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py deleted file mode 100644 index fae209c726d0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py +++ /dev/null @@ -1,440 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .access import ( - Access, - Geolocation, - ServiceAccountDelegationInfo, -) -from .application import ( - Application, -) -from .asset import ( - Asset, -) -from .attack_exposure import ( - AttackExposure, -) -from .attack_path import ( - AttackPath, -) -from .backup_disaster_recovery import ( - BackupDisasterRecovery, -) -from .bigquery_export import ( - BigQueryExport, -) -from .cloud_armor import ( - AdaptiveProtection, - Attack, - CloudArmor, - Requests, - SecurityPolicy, -) -from .cloud_dlp_data_profile import ( - CloudDlpDataProfile, -) -from .cloud_dlp_inspection import ( - CloudDlpInspection, -) -from .compliance import ( - Compliance, -) -from .connection import ( - Connection, -) -from .contact_details import ( - Contact, - ContactDetails, -) -from .container import ( - Container, -) -from .database import ( - Database, -) -from .effective_event_threat_detection_custom_module import ( - EffectiveEventThreatDetectionCustomModule, -) -from .effective_security_health_analytics_custom_module import ( - EffectiveSecurityHealthAnalyticsCustomModule, -) -from .event_threat_detection_custom_module import ( - EventThreatDetectionCustomModule, -) -from .event_threat_detection_custom_module_validation_errors import ( - CustomModuleValidationError, - CustomModuleValidationErrors, - Position, -) -from .exfiltration import ( - ExfilResource, - Exfiltration, -) -from .external_system import ( - ExternalSystem, -) -from .file import ( - File, -) -from .finding import ( - Finding, -) -from .folder import ( - Folder, -) -from .group_membership import ( - GroupMembership, -) -from .iam_binding import ( - IamBinding, -) -from .indicator import ( - Indicator, -) -from .kernel_rootkit import ( - KernelRootkit, -) -from .kubernetes import ( - Kubernetes, -) -from .label import ( - Label, -) -from .load_balancer import ( - LoadBalancer, -) -from .log_entry import ( - CloudLoggingEntry, - LogEntry, -) -from .mitre_attack import ( - MitreAttack, -) -from .mute_config import ( - MuteConfig, -) -from .notebook import ( - Notebook, -) -from .notification_config import ( - NotificationConfig, -) -from .notification_message import ( - NotificationMessage, -) -from .org_policy import ( - OrgPolicy, -) -from .organization_settings import ( - OrganizationSettings, -) -from .process import ( - EnvironmentVariable, - Process, -) -from .resource import ( - AwsMetadata, - AzureMetadata, - Resource, - ResourcePath, - CloudProvider, -) -from .resource_value_config import ( - ResourceValueConfig, - ResourceValue, -) -from .run_asset_discovery_response import ( - RunAssetDiscoveryResponse, -) -from .security_health_analytics_custom_config import ( - CustomConfig, -) -from .security_health_analytics_custom_module import ( - SecurityHealthAnalyticsCustomModule, -) -from .security_marks import ( - SecurityMarks, -) -from .security_posture import ( - SecurityPosture, -) -from .securitycenter_service import ( - BatchCreateResourceValueConfigsRequest, - BatchCreateResourceValueConfigsResponse, - BulkMuteFindingsRequest, - BulkMuteFindingsResponse, - CreateBigQueryExportRequest, - CreateEventThreatDetectionCustomModuleRequest, - CreateFindingRequest, - CreateMuteConfigRequest, - CreateNotificationConfigRequest, - CreateResourceValueConfigRequest, - CreateSecurityHealthAnalyticsCustomModuleRequest, - CreateSourceRequest, - DeleteBigQueryExportRequest, - DeleteEventThreatDetectionCustomModuleRequest, - DeleteMuteConfigRequest, - DeleteNotificationConfigRequest, - DeleteResourceValueConfigRequest, - DeleteSecurityHealthAnalyticsCustomModuleRequest, - GetBigQueryExportRequest, - GetEffectiveEventThreatDetectionCustomModuleRequest, - GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, - GetEventThreatDetectionCustomModuleRequest, - GetMuteConfigRequest, - GetNotificationConfigRequest, - GetOrganizationSettingsRequest, - GetResourceValueConfigRequest, - GetSecurityHealthAnalyticsCustomModuleRequest, - GetSimulationRequest, - GetSourceRequest, - GetValuedResourceRequest, - GroupAssetsRequest, - GroupAssetsResponse, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListAssetsRequest, - ListAssetsResponse, - ListAttackPathsRequest, - ListAttackPathsResponse, - ListBigQueryExportsRequest, - ListBigQueryExportsResponse, - ListDescendantEventThreatDetectionCustomModulesRequest, - ListDescendantEventThreatDetectionCustomModulesResponse, - ListDescendantSecurityHealthAnalyticsCustomModulesRequest, - ListDescendantSecurityHealthAnalyticsCustomModulesResponse, - ListEffectiveEventThreatDetectionCustomModulesRequest, - ListEffectiveEventThreatDetectionCustomModulesResponse, - ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, - ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, - ListEventThreatDetectionCustomModulesRequest, - ListEventThreatDetectionCustomModulesResponse, - ListFindingsRequest, - ListFindingsResponse, - ListMuteConfigsRequest, - ListMuteConfigsResponse, - ListNotificationConfigsRequest, - ListNotificationConfigsResponse, - ListResourceValueConfigsRequest, - ListResourceValueConfigsResponse, - ListSecurityHealthAnalyticsCustomModulesRequest, - ListSecurityHealthAnalyticsCustomModulesResponse, - ListSourcesRequest, - ListSourcesResponse, - ListValuedResourcesRequest, - ListValuedResourcesResponse, - RunAssetDiscoveryRequest, - SetFindingStateRequest, - SetMuteRequest, - SimulateSecurityHealthAnalyticsCustomModuleRequest, - SimulateSecurityHealthAnalyticsCustomModuleResponse, - UpdateBigQueryExportRequest, - UpdateEventThreatDetectionCustomModuleRequest, - UpdateExternalSystemRequest, - UpdateFindingRequest, - UpdateMuteConfigRequest, - UpdateNotificationConfigRequest, - UpdateOrganizationSettingsRequest, - UpdateResourceValueConfigRequest, - UpdateSecurityHealthAnalyticsCustomModuleRequest, - UpdateSecurityMarksRequest, - UpdateSourceRequest, - ValidateEventThreatDetectionCustomModuleRequest, - ValidateEventThreatDetectionCustomModuleResponse, -) -from .simulation import ( - Simulation, -) -from .source import ( - Source, -) -from .toxic_combination import ( - ToxicCombination, -) -from .valued_resource import ( - ResourceValueConfigMetadata, - ValuedResource, -) -from .vulnerability import ( - Cve, - Cvssv3, - Package, - Reference, - SecurityBulletin, - Vulnerability, -) - -__all__ = ( - 'Access', - 'Geolocation', - 'ServiceAccountDelegationInfo', - 'Application', - 'Asset', - 'AttackExposure', - 'AttackPath', - 'BackupDisasterRecovery', - 'BigQueryExport', - 'AdaptiveProtection', - 'Attack', - 'CloudArmor', - 'Requests', - 'SecurityPolicy', - 'CloudDlpDataProfile', - 'CloudDlpInspection', - 'Compliance', - 'Connection', - 'Contact', - 'ContactDetails', - 'Container', - 'Database', - 'EffectiveEventThreatDetectionCustomModule', - 'EffectiveSecurityHealthAnalyticsCustomModule', - 'EventThreatDetectionCustomModule', - 'CustomModuleValidationError', - 'CustomModuleValidationErrors', - 'Position', - 'ExfilResource', - 'Exfiltration', - 'ExternalSystem', - 'File', - 'Finding', - 'Folder', - 'GroupMembership', - 'IamBinding', - 'Indicator', - 'KernelRootkit', - 'Kubernetes', - 'Label', - 'LoadBalancer', - 'CloudLoggingEntry', - 'LogEntry', - 'MitreAttack', - 'MuteConfig', - 'Notebook', - 'NotificationConfig', - 'NotificationMessage', - 'OrgPolicy', - 'OrganizationSettings', - 'EnvironmentVariable', - 'Process', - 'AwsMetadata', - 'AzureMetadata', - 'Resource', - 'ResourcePath', - 'CloudProvider', - 'ResourceValueConfig', - 'ResourceValue', - 'RunAssetDiscoveryResponse', - 'CustomConfig', - 'SecurityHealthAnalyticsCustomModule', - 'SecurityMarks', - 'SecurityPosture', - 'BatchCreateResourceValueConfigsRequest', - 'BatchCreateResourceValueConfigsResponse', - 'BulkMuteFindingsRequest', - 'BulkMuteFindingsResponse', - 'CreateBigQueryExportRequest', - 'CreateEventThreatDetectionCustomModuleRequest', - 'CreateFindingRequest', - 'CreateMuteConfigRequest', - 'CreateNotificationConfigRequest', - 'CreateResourceValueConfigRequest', - 'CreateSecurityHealthAnalyticsCustomModuleRequest', - 'CreateSourceRequest', - 'DeleteBigQueryExportRequest', - 'DeleteEventThreatDetectionCustomModuleRequest', - 'DeleteMuteConfigRequest', - 'DeleteNotificationConfigRequest', - 'DeleteResourceValueConfigRequest', - 'DeleteSecurityHealthAnalyticsCustomModuleRequest', - 'GetBigQueryExportRequest', - 'GetEffectiveEventThreatDetectionCustomModuleRequest', - 'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', - 'GetEventThreatDetectionCustomModuleRequest', - 'GetMuteConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetResourceValueConfigRequest', - 'GetSecurityHealthAnalyticsCustomModuleRequest', - 'GetSimulationRequest', - 'GetSourceRequest', - 'GetValuedResourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListAttackPathsRequest', - 'ListAttackPathsResponse', - 'ListBigQueryExportsRequest', - 'ListBigQueryExportsResponse', - 'ListDescendantEventThreatDetectionCustomModulesRequest', - 'ListDescendantEventThreatDetectionCustomModulesResponse', - 'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', - 'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', - 'ListEffectiveEventThreatDetectionCustomModulesRequest', - 'ListEffectiveEventThreatDetectionCustomModulesResponse', - 'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', - 'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', - 'ListEventThreatDetectionCustomModulesRequest', - 'ListEventThreatDetectionCustomModulesResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListMuteConfigsRequest', - 'ListMuteConfigsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListResourceValueConfigsRequest', - 'ListResourceValueConfigsResponse', - 'ListSecurityHealthAnalyticsCustomModulesRequest', - 'ListSecurityHealthAnalyticsCustomModulesResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListValuedResourcesRequest', - 'ListValuedResourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'SetMuteRequest', - 'SimulateSecurityHealthAnalyticsCustomModuleRequest', - 'SimulateSecurityHealthAnalyticsCustomModuleResponse', - 'UpdateBigQueryExportRequest', - 'UpdateEventThreatDetectionCustomModuleRequest', - 'UpdateExternalSystemRequest', - 'UpdateFindingRequest', - 'UpdateMuteConfigRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateResourceValueConfigRequest', - 'UpdateSecurityHealthAnalyticsCustomModuleRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'ValidateEventThreatDetectionCustomModuleRequest', - 'ValidateEventThreatDetectionCustomModuleResponse', - 'Simulation', - 'Source', - 'ToxicCombination', - 'ResourceValueConfigMetadata', - 'ValuedResource', - 'Cve', - 'Cvssv3', - 'Package', - 'Reference', - 'SecurityBulletin', - 'Vulnerability', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py deleted file mode 100644 index 46f1bc1e8a57..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py +++ /dev/null @@ -1,193 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v1', - manifest={ - 'Access', - 'ServiceAccountDelegationInfo', - 'Geolocation', - }, -) - - -class Access(proto.Message): - r"""Represents an access event. - - Attributes: - principal_email (str): - Associated email, such as "foo@google.com". - - The email address of the authenticated user or a service - account acting on behalf of a third party principal making - the request. For third party identity callers, the - ``principal_subject`` field is populated instead of this - field. For privacy reasons, the principal email address is - sometimes redacted. For more information, see `Caller - identities in audit - logs `__. - caller_ip (str): - Caller's IP address, such as "1.1.1.1". - caller_ip_geo (google.cloud.securitycenter_v1.types.Geolocation): - The caller IP's geolocation, which identifies - where the call came from. - user_agent_family (str): - Type of user agent associated with the - finding. For example, an operating system shell - or an embedded or standalone application. - user_agent (str): - The caller's user agent string associated - with the finding. - service_name (str): - This is the API service that the service - account made a call to, e.g. - "iam.googleapis.com". - method_name (str): - The method that the service account called, - e.g. "SetIamPolicy". - principal_subject (str): - A string that represents the principal_subject that is - associated with the identity. Unlike ``principal_email``, - ``principal_subject`` supports principals that aren't - associated with email addresses, such as third party - principals. For most identities, the format is - ``principal://iam.googleapis.com/{identity pool name}/subject/{subject}``. - Some GKE identities, such as GKE_WORKLOAD, FREEFORM, and - GKE_HUB_WORKLOAD, still use the legacy format - ``serviceAccount:{identity pool name}[{subject}]``. - service_account_key_name (str): - The name of the service account key that was used to create - or exchange credentials when authenticating the service - account that made the request. This is a scheme-less URI - full resource name. For example: - - "//iam.googleapis.com/projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}". - service_account_delegation_info (MutableSequence[google.cloud.securitycenter_v1.types.ServiceAccountDelegationInfo]): - The identity delegation history of an authenticated service - account that made the request. The - ``serviceAccountDelegationInfo[]`` object contains - information about the real authorities that try to access - Google Cloud resources by delegating on a service account. - When multiple authorities are present, they are guaranteed - to be sorted based on the original ordering of the identity - delegation events. - user_name (str): - A string that represents a username. The - username provided depends on the type of the - finding and is likely not an IAM principal. For - example, this can be a system username if the - finding is related to a virtual machine, or it - can be an application login username. - """ - - principal_email: str = proto.Field( - proto.STRING, - number=1, - ) - caller_ip: str = proto.Field( - proto.STRING, - number=2, - ) - caller_ip_geo: 'Geolocation' = proto.Field( - proto.MESSAGE, - number=3, - message='Geolocation', - ) - user_agent_family: str = proto.Field( - proto.STRING, - number=4, - ) - user_agent: str = proto.Field( - proto.STRING, - number=12, - ) - service_name: str = proto.Field( - proto.STRING, - number=5, - ) - method_name: str = proto.Field( - proto.STRING, - number=6, - ) - principal_subject: str = proto.Field( - proto.STRING, - number=7, - ) - service_account_key_name: str = proto.Field( - proto.STRING, - number=8, - ) - service_account_delegation_info: MutableSequence['ServiceAccountDelegationInfo'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='ServiceAccountDelegationInfo', - ) - user_name: str = proto.Field( - proto.STRING, - number=11, - ) - - -class ServiceAccountDelegationInfo(proto.Message): - r"""Identity delegation history of an authenticated service - account. - - Attributes: - principal_email (str): - The email address of a Google account. - principal_subject (str): - A string representing the principal_subject associated with - the identity. As compared to ``principal_email``, supports - principals that aren't associated with email addresses, such - as third party principals. For most identities, the format - will be - ``principal://iam.googleapis.com/{identity pool name}/subjects/{subject}`` - except for some GKE identities (GKE_WORKLOAD, FREEFORM, - GKE_HUB_WORKLOAD) that are still in the legacy format - ``serviceAccount:{identity pool name}[{subject}]`` - """ - - principal_email: str = proto.Field( - proto.STRING, - number=1, - ) - principal_subject: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Geolocation(proto.Message): - r"""Represents a geographical location for a given access. - - Attributes: - region_code (str): - A CLDR. - """ - - region_code: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.py deleted file mode 100644 index 96e0a3cd61dc..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Application', - }, -) - - -class Application(proto.Message): - r"""Represents an application associated with a finding. - - Attributes: - base_uri (str): - The base URI that identifies the network location of the - application in which the vulnerability was detected. For - example, ``http://example.com``. - full_uri (str): - The full URI with payload that can be used to reproduce the - vulnerability. For example, - ``http://example.com?p=aMmYgI6H``. - """ - - base_uri: str = proto.Field( - proto.STRING, - number=1, - ) - full_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py deleted file mode 100644 index 5c4a957c4d1e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py +++ /dev/null @@ -1,227 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1.types import folder -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Asset', - }, -) - - -class Asset(proto.Message): - r"""Security Command Center representation of a Google Cloud - resource. - - The Asset is a Security Command Center resource that captures - information about a single Google Cloud resource. All - modifications to an Asset are only within the context of - Security Command Center and don't affect the referenced Google - Cloud resource. - - Attributes: - name (str): - The relative resource name of this asset. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (google.cloud.securitycenter_v1.types.Asset.SecurityCenterProperties): - Security Command Center managed properties. - These properties are managed by Security Command - Center and cannot be modified by the user. - resource_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Resource managed properties. These properties - are managed and defined by the Google Cloud - resource and cannot be modified by the user. - security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): - User specified security marks. These marks - are entirely managed by the user and come from - the SecurityMarks resource that belongs to the - asset. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was created in - Security Command Center. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was last updated - or added in Cloud SCC. - iam_policy (google.cloud.securitycenter_v1.types.Asset.IamPolicy): - Cloud IAM Policy information associated with - the Google Cloud resource described by the - Security Command Center asset. This information - is managed and defined by the Google Cloud - resource and cannot be modified by the user. - canonical_name (str): - The canonical name of the resource. It's either - "organizations/{organization_id}/assets/{asset_id}", - "folders/{folder_id}/assets/{asset_id}" or - "projects/{project_number}/assets/{asset_id}", depending on - the closest CRM ancestor of the resource. - """ - - class SecurityCenterProperties(proto.Message): - r"""Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified by - the user. - - Attributes: - resource_name (str): - The full resource name of the Google Cloud resource this - asset represents. This field is immutable after create time. - See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_type (str): - The type of the Google Cloud resource. - Examples include: APPLICATION, PROJECT, and - ORGANIZATION. This is a case insensitive field - defined by Security Command Center and/or the - producer of the resource and is immutable after - create time. - resource_parent (str): - The full resource name of the immediate parent of the - resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_project (str): - The full resource name of the project the resource belongs - to. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_owners (MutableSequence[str]): - Owners of the Google Cloud resource. - resource_display_name (str): - The user defined display name for this - resource. - resource_parent_display_name (str): - The user defined display name for the parent - of this resource. - resource_project_display_name (str): - The user defined display name for the project - of this resource. - folders (MutableSequence[google.cloud.securitycenter_v1.types.Folder]): - Contains a Folder message for each folder in - the assets ancestry. The first folder is the - deepest nested folder, and the last folder is - the folder directly under the Organization. - """ - - resource_name: str = proto.Field( - proto.STRING, - number=1, - ) - resource_type: str = proto.Field( - proto.STRING, - number=2, - ) - resource_parent: str = proto.Field( - proto.STRING, - number=3, - ) - resource_project: str = proto.Field( - proto.STRING, - number=4, - ) - resource_owners: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - resource_display_name: str = proto.Field( - proto.STRING, - number=6, - ) - resource_parent_display_name: str = proto.Field( - proto.STRING, - number=7, - ) - resource_project_display_name: str = proto.Field( - proto.STRING, - number=8, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=folder.Folder, - ) - - class IamPolicy(proto.Message): - r"""Cloud IAM Policy information associated with the Google Cloud - resource described by the Security Command Center asset. This - information is managed and defined by the Google Cloud resource - and cannot be modified by the user. - - Attributes: - policy_blob (str): - The JSON representation of the Policy - associated with the asset. See - https://cloud.google.com/iam/reference/rest/v1/Policy - for format details. - """ - - policy_blob: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - security_center_properties: SecurityCenterProperties = proto.Field( - proto.MESSAGE, - number=2, - message=SecurityCenterProperties, - ) - resource_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - iam_policy: IamPolicy = proto.Field( - proto.MESSAGE, - number=11, - message=IamPolicy, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=13, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.py deleted file mode 100644 index 71c641c4f226..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'AttackExposure', - }, -) - - -class AttackExposure(proto.Message): - r"""An attack exposure contains the results of an attack path - simulation run. - - Attributes: - score (float): - A number between 0 (inclusive) and infinity - that represents how important this finding is to - remediate. The higher the score, the more - important it is to remediate. - latest_calculation_time (google.protobuf.timestamp_pb2.Timestamp): - The most recent time the attack exposure was - updated on this finding. - attack_exposure_result (str): - The resource name of the attack path simulation result that - contains the details regarding this attack exposure score. - Example: - ``organizations/123/simulations/456/attackExposureResults/789`` - state (google.cloud.securitycenter_v1.types.AttackExposure.State): - What state this AttackExposure is in. This - captures whether or not an attack exposure has - been calculated or not. - exposed_high_value_resources_count (int): - The number of high value resources that are - exposed as a result of this finding. - exposed_medium_value_resources_count (int): - The number of medium value resources that are - exposed as a result of this finding. - exposed_low_value_resources_count (int): - The number of high value resources that are - exposed as a result of this finding. - """ - class State(proto.Enum): - r"""This enum defines the various states an AttackExposure can be - in. - - Values: - STATE_UNSPECIFIED (0): - The state is not specified. - CALCULATED (1): - The attack exposure has been calculated. - NOT_CALCULATED (2): - The attack exposure has not been calculated. - """ - STATE_UNSPECIFIED = 0 - CALCULATED = 1 - NOT_CALCULATED = 2 - - score: float = proto.Field( - proto.DOUBLE, - number=1, - ) - latest_calculation_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - attack_exposure_result: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - exposed_high_value_resources_count: int = proto.Field( - proto.INT32, - number=5, - ) - exposed_medium_value_resources_count: int = proto.Field( - proto.INT32, - number=6, - ) - exposed_low_value_resources_count: int = proto.Field( - proto.INT32, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py deleted file mode 100644 index d298b28f7407..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v1', - manifest={ - 'AttackPath', - }, -) - - -class AttackPath(proto.Message): - r"""A path that an attacker could take to reach an exposed - resource. - - Attributes: - name (str): - The attack path name, for example, - ``organizations/12/simulation/34/valuedResources/56/attackPaths/78`` - path_nodes (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode]): - A list of nodes that exist in this attack - path. - edges (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathEdge]): - A list of the edges between nodes in this - attack path. - """ - - class AttackPathNode(proto.Message): - r"""Represents one point that an attacker passes through in this - attack path. - - Attributes: - resource (str): - The name of the resource at this point in the attack path. - The format of the name follows the Cloud Asset Inventory - `resource name - format `__ - resource_type (str): - The `supported resource - type `__ - display_name (str): - Human-readable name of this resource. - associated_findings (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode.PathNodeAssociatedFinding]): - The findings associated with this node in the - attack path. - uuid (str): - Unique id of the attack path node. - attack_steps (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode.AttackStepNode]): - A list of attack step nodes that exist in - this attack path node. - """ - class NodeType(proto.Enum): - r"""The type of the incoming attack step node. - - Values: - NODE_TYPE_UNSPECIFIED (0): - Type not specified - NODE_TYPE_AND (1): - Incoming edge joined with AND - NODE_TYPE_OR (2): - Incoming edge joined with OR - NODE_TYPE_DEFENSE (3): - Incoming edge is defense - NODE_TYPE_ATTACKER (4): - Incoming edge is attacker - """ - NODE_TYPE_UNSPECIFIED = 0 - NODE_TYPE_AND = 1 - NODE_TYPE_OR = 2 - NODE_TYPE_DEFENSE = 3 - NODE_TYPE_ATTACKER = 4 - - class PathNodeAssociatedFinding(proto.Message): - r"""A finding that is associated with this node in the attack - path. - - Attributes: - canonical_finding (str): - Canonical name of the associated findings. Example: - ``organizations/123/sources/456/findings/789`` - finding_category (str): - The additional taxonomy group within findings - from a given source. - name (str): - Full resource name of the finding. - """ - - canonical_finding: str = proto.Field( - proto.STRING, - number=1, - ) - finding_category: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - class AttackStepNode(proto.Message): - r"""Detailed steps the attack can take between path nodes. - - Attributes: - uuid (str): - Unique ID for one Node - type_ (google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode.NodeType): - Attack step type. Can be either AND, OR or - DEFENSE - display_name (str): - User friendly name of the attack step - labels (MutableMapping[str, str]): - Attack step labels for metadata - description (str): - Attack step description - """ - - uuid: str = proto.Field( - proto.STRING, - number=1, - ) - type_: 'AttackPath.AttackPathNode.NodeType' = proto.Field( - proto.ENUM, - number=2, - enum='AttackPath.AttackPathNode.NodeType', - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - description: str = proto.Field( - proto.STRING, - number=5, - ) - - resource: str = proto.Field( - proto.STRING, - number=1, - ) - resource_type: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - associated_findings: MutableSequence['AttackPath.AttackPathNode.PathNodeAssociatedFinding'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='AttackPath.AttackPathNode.PathNodeAssociatedFinding', - ) - uuid: str = proto.Field( - proto.STRING, - number=5, - ) - attack_steps: MutableSequence['AttackPath.AttackPathNode.AttackStepNode'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='AttackPath.AttackPathNode.AttackStepNode', - ) - - class AttackPathEdge(proto.Message): - r"""Represents a connection between a source node and a - destination node in this attack path. - - Attributes: - source (str): - The attack node uuid of the source node. - destination (str): - The attack node uuid of the destination node. - """ - - source: str = proto.Field( - proto.STRING, - number=1, - ) - destination: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - path_nodes: MutableSequence[AttackPathNode] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=AttackPathNode, - ) - edges: MutableSequence[AttackPathEdge] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=AttackPathEdge, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py deleted file mode 100644 index 2497cff8afd8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py +++ /dev/null @@ -1,137 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v1', - manifest={ - 'BackupDisasterRecovery', - }, -) - - -class BackupDisasterRecovery(proto.Message): - r"""Information related to Google Cloud Backup and DR Service - findings. - - Attributes: - backup_template (str): - The name of a Backup and DR template which comprises one or - more backup policies. See the `Backup and DR - documentation `__ - for more information. For example, ``snap-ov``. - policies (MutableSequence[str]): - The names of Backup and DR policies that are associated with - a template and that define when to run a backup, how - frequently to run a backup, and how long to retain the - backup image. For example, ``onvaults``. - host (str): - The name of a Backup and DR host, which is managed by the - backup and recovery appliance and known to the management - console. The host can be of type Generic (for example, - Compute Engine, SQL Server, Oracle DB, SMB file system, - etc.), vCenter, or an ESX server. See the `Backup and DR - documentation on - hosts `__ - for more information. For example, ``centos7-01``. - applications (MutableSequence[str]): - The names of Backup and DR applications. An application is a - VM, database, or file system on a managed host monitored by - a backup and recovery appliance. For example, - ``centos7-01-vol00``, ``centos7-01-vol01``, - ``centos7-01-vol02``. - storage_pool (str): - The name of the Backup and DR storage pool that the backup - and recovery appliance is storing data in. The storage pool - could be of type Cloud, Primary, Snapshot, or OnVault. See - the `Backup and DR documentation on storage - pools `__. - For example, ``DiskPoolOne``. - policy_options (MutableSequence[str]): - The names of Backup and DR advanced policy options of a - policy applying to an application. See the `Backup and DR - documentation on policy - options `__. - For example, ``skipofflineappsincongrp, nounmap``. - profile (str): - The name of the Backup and DR resource profile that - specifies the storage media for backups of application and - VM data. See the `Backup and DR documentation on - profiles `__. - For example, ``GCP``. - appliance (str): - The name of the Backup and DR appliance that captures, - moves, and manages the lifecycle of backup data. For - example, ``backup-server-57137``. - backup_type (str): - The backup type of the Backup and DR image. For example, - ``Snapshot``, ``Remote Snapshot``, ``OnVault``. - backup_create_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp at which the Backup and DR - backup was created. - """ - - backup_template: str = proto.Field( - proto.STRING, - number=1, - ) - policies: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - host: str = proto.Field( - proto.STRING, - number=3, - ) - applications: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - storage_pool: str = proto.Field( - proto.STRING, - number=5, - ) - policy_options: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - profile: str = proto.Field( - proto.STRING, - number=7, - ) - appliance: str = proto.Field( - proto.STRING, - number=8, - ) - backup_type: str = proto.Field( - proto.STRING, - number=9, - ) - backup_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py deleted file mode 100644 index 9e8288f7fd7b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py +++ /dev/null @@ -1,135 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v1', - manifest={ - 'BigQueryExport', - }, -) - - -class BigQueryExport(proto.Message): - r"""Configures how to deliver Findings to BigQuery Instance. - - Attributes: - name (str): - The relative resource name of this export. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name. - Example format: - "organizations/{organization_id}/bigQueryExports/{export_id}" - Example format: - "folders/{folder_id}/bigQueryExports/{export_id}" Example - format: "projects/{project_id}/bigQueryExports/{export_id}" - This field is provided in responses, and is ignored when - provided in create requests. - description (str): - The description of the export (max of 1024 - characters). - filter (str): - Expression that defines the filter to apply across - create/update events of findings. The expression is a list - of zero or more restrictions combined via logical operators - ``AND`` and ``OR``. Parentheses are supported, and ``OR`` - has higher precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - dataset (str): - The dataset to write findings' updates to. Its format is - "projects/[project_id]/datasets/[bigquery_dataset_id]". - BigQuery Dataset unique ID must contain only letters (a-z, - A-Z), numbers (0-9), or underscores (_). - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the BigQuery - export was created. This field is set by the - server and will be ignored if provided on export - on creation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The most recent time at which - the BigQuery export was updated. This field is - set by the server and will be ignored if - provided on export creation or update. - most_recent_editor (str): - Output only. Email address of the user who - last edited the BigQuery export. This field is - set by the server and will be ignored if - provided on export creation or update. - principal (str): - Output only. The service account that needs - permission to create table and upload data to - the BigQuery dataset. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - filter: str = proto.Field( - proto.STRING, - number=3, - ) - dataset: 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, - ) - most_recent_editor: str = proto.Field( - proto.STRING, - number=7, - ) - principal: str = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.py deleted file mode 100644 index 45b7e2fb7d51..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.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.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'CloudArmor', - 'SecurityPolicy', - 'Requests', - 'AdaptiveProtection', - 'Attack', - }, -) - - -class CloudArmor(proto.Message): - r"""Fields related to Google Cloud Armor findings. - - Attributes: - security_policy (google.cloud.securitycenter_v1.types.SecurityPolicy): - Information about the `Google Cloud Armor security - policy `__ - relevant to the finding. - requests (google.cloud.securitycenter_v1.types.Requests): - Information about incoming requests evaluated by `Google - Cloud Armor security - policies `__. - adaptive_protection (google.cloud.securitycenter_v1.types.AdaptiveProtection): - Information about potential Layer 7 DDoS attacks identified - by `Google Cloud Armor Adaptive - Protection `__. - attack (google.cloud.securitycenter_v1.types.Attack): - Information about DDoS attack volume and - classification. - threat_vector (str): - Distinguish between volumetric & protocol DDoS attack and - application layer attacks. For example, "L3_4" for Layer 3 - and Layer 4 DDoS attacks, or "L_7" for Layer 7 DDoS attacks. - duration (google.protobuf.duration_pb2.Duration): - Duration of attack from the start until the - current moment (updated every 5 minutes). - """ - - security_policy: 'SecurityPolicy' = proto.Field( - proto.MESSAGE, - number=1, - message='SecurityPolicy', - ) - requests: 'Requests' = proto.Field( - proto.MESSAGE, - number=2, - message='Requests', - ) - adaptive_protection: 'AdaptiveProtection' = proto.Field( - proto.MESSAGE, - number=3, - message='AdaptiveProtection', - ) - attack: 'Attack' = proto.Field( - proto.MESSAGE, - number=4, - message='Attack', - ) - threat_vector: str = proto.Field( - proto.STRING, - number=5, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - - -class SecurityPolicy(proto.Message): - r"""Information about the `Google Cloud Armor security - policy `__ - relevant to the finding. - - Attributes: - name (str): - The name of the Google Cloud Armor security - policy, for example, "my-security-policy". - type_ (str): - The type of Google Cloud Armor security - policy for example, 'backend security policy', - 'edge security policy', 'network edge security - policy', or 'always-on DDoS protection'. - preview (bool): - Whether or not the associated rule or policy - is in preview mode. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - preview: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class Requests(proto.Message): - r"""Information about the requests relevant to the finding. - - Attributes: - ratio (float): - For 'Increasing deny ratio', the ratio is the - denied traffic divided by the allowed traffic. - For 'Allowed traffic spike', the ratio is the - allowed traffic in the short term divided by - allowed traffic in the long term. - short_term_allowed (int): - Allowed RPS (requests per second) in the - short term. - long_term_allowed (int): - Allowed RPS (requests per second) over the - long term. - long_term_denied (int): - Denied RPS (requests per second) over the - long term. - """ - - ratio: float = proto.Field( - proto.DOUBLE, - number=1, - ) - short_term_allowed: int = proto.Field( - proto.INT32, - number=2, - ) - long_term_allowed: int = proto.Field( - proto.INT32, - number=3, - ) - long_term_denied: int = proto.Field( - proto.INT32, - number=4, - ) - - -class AdaptiveProtection(proto.Message): - r"""Information about `Google Cloud Armor Adaptive - Protection `__. - - Attributes: - confidence (float): - A score of 0 means that there is low confidence that the - detected event is an actual attack. A score of 1 means that - there is high confidence that the detected event is an - attack. See the `Adaptive Protection - documentation `__ - for further explanation. - """ - - confidence: float = proto.Field( - proto.DOUBLE, - number=1, - ) - - -class Attack(proto.Message): - r"""Information about DDoS attack volume and classification. - - Attributes: - volume_pps (int): - Total PPS (packets per second) volume of - attack. - volume_bps (int): - Total BPS (bytes per second) volume of - attack. - classification (str): - Type of attack, for example, 'SYN-flood', - 'NTP-udp', or 'CHARGEN-udp'. - """ - - volume_pps: int = proto.Field( - proto.INT32, - number=1, - ) - volume_bps: int = proto.Field( - proto.INT32, - number=2, - ) - classification: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.py deleted file mode 100644 index 52cece2651fc..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.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.cloud.securitycenter.v1', - manifest={ - 'CloudDlpDataProfile', - }, -) - - -class CloudDlpDataProfile(proto.Message): - r"""The `data - profile `__ - associated with the finding. - - Attributes: - data_profile (str): - Name of the data profile, for example, - ``projects/123/locations/europe/tableProfiles/8383929``. - parent_type (google.cloud.securitycenter_v1.types.CloudDlpDataProfile.ParentType): - The resource hierarchy level at which the - data profile was generated. - """ - class ParentType(proto.Enum): - r"""Parents for configurations that produce data profile - findings. - - Values: - PARENT_TYPE_UNSPECIFIED (0): - Unspecified parent type. - ORGANIZATION (1): - Organization-level configurations. - PROJECT (2): - Project-level configurations. - """ - PARENT_TYPE_UNSPECIFIED = 0 - ORGANIZATION = 1 - PROJECT = 2 - - data_profile: str = proto.Field( - proto.STRING, - number=1, - ) - parent_type: ParentType = proto.Field( - proto.ENUM, - number=2, - enum=ParentType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.py deleted file mode 100644 index 46b9848965a8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'CloudDlpInspection', - }, -) - - -class CloudDlpInspection(proto.Message): - r"""Details about the Cloud Data Loss Prevention (Cloud DLP) `inspection - job `__ - that produced the finding. - - Attributes: - inspect_job (str): - Name of the inspection job, for example, - ``projects/123/locations/europe/dlpJobs/i-8383929``. - info_type (str): - The type of information (or - `infoType `__) - found, for example, ``EMAIL_ADDRESS`` or ``STREET_ADDRESS``. - info_type_count (int): - The number of times Cloud DLP found this - infoType within this job and resource. - full_scan (bool): - Whether Cloud DLP scanned the complete - resource or a sampled subset. - """ - - inspect_job: str = proto.Field( - proto.STRING, - number=1, - ) - info_type: str = proto.Field( - proto.STRING, - number=2, - ) - info_type_count: int = proto.Field( - proto.INT64, - number=3, - ) - full_scan: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.py deleted file mode 100644 index 432ca7841d82..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Compliance', - }, -) - - -class Compliance(proto.Message): - r"""Contains compliance information about a security standard - indicating unmet recommendations. - - Attributes: - standard (str): - Industry-wide compliance standards or - benchmarks, such as CIS, PCI, and OWASP. - version (str): - Version of the standard or benchmark, for - example, 1.1 - ids (MutableSequence[str]): - Policies within the standard or benchmark, - for example, A.12.4.1 - """ - - standard: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.py deleted file mode 100644 index 0f36fbdfd761..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.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.cloud.securitycenter.v1', - manifest={ - 'Connection', - }, -) - - -class Connection(proto.Message): - r"""Contains information about the IP connection associated with - the finding. - - Attributes: - destination_ip (str): - Destination IP address. Not present for - sockets that are listening and not connected. - destination_port (int): - Destination port. Not present for sockets - that are listening and not connected. - source_ip (str): - Source IP address. - source_port (int): - Source port. - protocol (google.cloud.securitycenter_v1.types.Connection.Protocol): - IANA Internet Protocol Number such as TCP(6) - and UDP(17). - """ - class Protocol(proto.Enum): - r"""IANA Internet Protocol Number such as TCP(6) and UDP(17). - - Values: - PROTOCOL_UNSPECIFIED (0): - Unspecified protocol (not HOPOPT). - ICMP (1): - Internet Control Message Protocol. - TCP (6): - Transmission Control Protocol. - UDP (17): - User Datagram Protocol. - GRE (47): - Generic Routing Encapsulation. - ESP (50): - Encap Security Payload. - """ - PROTOCOL_UNSPECIFIED = 0 - ICMP = 1 - TCP = 6 - UDP = 17 - GRE = 47 - ESP = 50 - - destination_ip: str = proto.Field( - proto.STRING, - number=1, - ) - destination_port: int = proto.Field( - proto.INT32, - number=2, - ) - source_ip: str = proto.Field( - proto.STRING, - number=3, - ) - source_port: int = proto.Field( - proto.INT32, - number=4, - ) - protocol: Protocol = proto.Field( - proto.ENUM, - number=5, - enum=Protocol, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.py deleted file mode 100644 index 7fdd88c15c7e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'ContactDetails', - 'Contact', - }, -) - - -class ContactDetails(proto.Message): - r"""Details about specific contacts - - Attributes: - contacts (MutableSequence[google.cloud.securitycenter_v1.types.Contact]): - A list of contacts - """ - - contacts: MutableSequence['Contact'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Contact', - ) - - -class Contact(proto.Message): - r"""The email address of a contact. - - Attributes: - email (str): - An email address. For example, "``person123@company.com``". - """ - - email: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.py deleted file mode 100644 index d953244d3583..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v1.types import label -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Container', - }, -) - - -class Container(proto.Message): - r"""Container associated with the finding. - - Attributes: - name (str): - Name of the container. - uri (str): - Container image URI provided when configuring - a pod or container. This string can identify a - container image version using mutable tags. - image_id (str): - Optional container image ID, if provided by - the container runtime. Uniquely identifies the - container image launched using a container image - digest. - labels (MutableSequence[google.cloud.securitycenter_v1.types.Label]): - Container labels, as provided by the - container runtime. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the container was created. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - image_id: str = proto.Field( - proto.STRING, - number=3, - ) - labels: MutableSequence[label.Label] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=label.Label, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.py deleted file mode 100644 index 3372ba324532..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Database', - }, -) - - -class Database(proto.Message): - r"""Represents database access information, such as queries. A database - may be a sub-resource of an instance (as in the case of Cloud SQL - instances or Cloud Spanner instances), or the database instance - itself. Some database resources might not have the `full resource - name `__ populated - because these resource types, such as Cloud SQL databases, are not - yet supported by Cloud Asset Inventory. In these cases only the - display name is provided. - - Attributes: - name (str): - Some database resources may not have the `full resource - name `__ - populated because these resource types are not yet supported - by Cloud Asset Inventory (e.g. Cloud SQL databases). In - these cases only the display name will be provided. The - `full resource - name `__ of - the database that the user connected to, if it is supported - by Cloud Asset Inventory. - display_name (str): - The human-readable name of the database that - the user connected to. - user_name (str): - The username used to connect to the database. - The username might not be an IAM principal and - does not have a set format. - query (str): - The SQL statement that is associated with the - database access. - grantees (MutableSequence[str]): - The target usernames, roles, or groups of an - SQL privilege grant, which is not an IAM policy - change. - version (str): - The version of the database, for example, POSTGRES_14. See - `the complete - list `__. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - user_name: str = proto.Field( - proto.STRING, - number=3, - ) - query: str = proto.Field( - proto.STRING, - number=4, - ) - grantees: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - version: str = proto.Field( - proto.STRING, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.py deleted file mode 100644 index ba51ed0b1ec6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.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.cloud.securitycenter.v1', - manifest={ - 'EffectiveEventThreatDetectionCustomModule', - }, -) - - -class EffectiveEventThreatDetectionCustomModule(proto.Message): - r"""An EffectiveEventThreatDetectionCustomModule is the representation - of an Event Threat Detection custom module at a specified level of - the resource hierarchy: organization, folder, or project. If a - custom module is inherited from a parent organization or folder, the - value of the ``enablement_state`` property in - EffectiveEventThreatDetectionCustomModule is set to the value that - is effective in the parent, instead of ``INHERITED``. For example, - if the module is enabled in a parent organization or folder, the - effective ``enablement_state`` for the module in all child folders - or projects is also ``enabled``. - EffectiveEventThreatDetectionCustomModule is read-only. - - Attributes: - name (str): - Output only. The resource name of the effective ETD custom - module. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - config (google.protobuf.struct_pb2.Struct): - Output only. Config for the effective module. - enablement_state (google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule.EnablementState): - Output only. The effective state of - enablement for the module at the given level of - the hierarchy. - type_ (str): - Output only. Type for the module. e.g. CONFIGURABLE_BAD_IP. - display_name (str): - Output only. The human readable name to be - displayed for the module. - description (str): - Output only. The description for the module. - """ - class EnablementState(proto.Enum): - r"""The enablement state of the module. - - Values: - ENABLEMENT_STATE_UNSPECIFIED (0): - Unspecified enablement state. - ENABLED (1): - The module is enabled at the given level. - DISABLED (2): - The module is disabled at the given level. - """ - ENABLEMENT_STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - config: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - enablement_state: EnablementState = proto.Field( - proto.ENUM, - number=3, - enum=EnablementState, - ) - type_: str = proto.Field( - proto.STRING, - number=4, - ) - display_name: str = proto.Field( - proto.STRING, - number=5, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.py deleted file mode 100644 index 2396c38d1aaf..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'EffectiveSecurityHealthAnalyticsCustomModule', - }, -) - - -class EffectiveSecurityHealthAnalyticsCustomModule(proto.Message): - r"""An EffectiveSecurityHealthAnalyticsCustomModule is the - representation of a Security Health Analytics custom module at a - specified level of the resource hierarchy: organization, folder, or - project. If a custom module is inherited from a parent organization - or folder, the value of the ``enablementState`` property in - EffectiveSecurityHealthAnalyticsCustomModule is set to the value - that is effective in the parent, instead of ``INHERITED``. For - example, if the module is enabled in a parent organization or - folder, the effective enablement_state for the module in all child - folders or projects is also ``enabled``. - EffectiveSecurityHealthAnalyticsCustomModule is read-only. - - Attributes: - name (str): - Output only. The resource name of the custom - module. Its format is - "organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}", - or - "folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}", - or - "projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}". - custom_config (google.cloud.securitycenter_v1.types.CustomConfig): - Output only. The user-specified configuration - for the module. - enablement_state (google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState): - Output only. The effective state of - enablement for the module at the given level of - the hierarchy. - display_name (str): - Output only. The display name for the custom - module. The name must be between 1 and 128 - characters, start with a lowercase letter, and - contain alphanumeric characters or underscores - only. - """ - class EnablementState(proto.Enum): - r"""The enablement state of the module. - - Values: - ENABLEMENT_STATE_UNSPECIFIED (0): - Unspecified enablement state. - ENABLED (1): - The module is enabled at the given level. - DISABLED (2): - The module is disabled at the given level. - """ - ENABLEMENT_STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - custom_config: security_health_analytics_custom_config.CustomConfig = proto.Field( - proto.MESSAGE, - number=2, - message=security_health_analytics_custom_config.CustomConfig, - ) - enablement_state: EnablementState = proto.Field( - proto.ENUM, - number=3, - enum=EnablementState, - ) - display_name: str = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.py deleted file mode 100644 index 6b6e83626bb9..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'EventThreatDetectionCustomModule', - }, -) - - -class EventThreatDetectionCustomModule(proto.Message): - r"""Represents an instance of an Event Threat Detection custom - module, including its full module name, display name, enablement - state, and last updated time. You can create a custom module at - the organization, folder, or project level. Custom modules that - you create at the organization or folder level are inherited by - child folders and projects. - - Attributes: - name (str): - Immutable. The resource name of the Event Threat Detection - custom module. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. - config (google.protobuf.struct_pb2.Struct): - Config for the module. For the resident - module, its config value is defined at this - level. For the inherited module, its config - value is inherited from the ancestor module. - ancestor_module (str): - Output only. The closest ancestor module that - this module inherits the enablement state from. - The format is the same as the - EventThreatDetectionCustomModule resource name. - enablement_state (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule.EnablementState): - The state of enablement for the module at the - given level of the hierarchy. - type_ (str): - Type for the module. e.g. CONFIGURABLE_BAD_IP. - display_name (str): - The human readable name to be displayed for - the module. - description (str): - The description for the module. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the module was last - updated. - last_editor (str): - Output only. The editor the module was last - updated by. - """ - class EnablementState(proto.Enum): - r"""The enablement state of the module. - - Values: - ENABLEMENT_STATE_UNSPECIFIED (0): - Unspecified enablement state. - ENABLED (1): - The module is enabled at the given level. - DISABLED (2): - The module is disabled at the given level. - INHERITED (3): - When the enablement state is inherited. - """ - ENABLEMENT_STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - INHERITED = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - config: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - ancestor_module: str = proto.Field( - proto.STRING, - number=3, - ) - enablement_state: EnablementState = proto.Field( - proto.ENUM, - number=4, - enum=EnablementState, - ) - type_: str = proto.Field( - proto.STRING, - number=5, - ) - display_name: str = proto.Field( - proto.STRING, - number=6, - ) - description: str = proto.Field( - proto.STRING, - number=7, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - last_editor: str = proto.Field( - proto.STRING, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.py deleted file mode 100644 index 12b7e815de3f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'CustomModuleValidationErrors', - 'CustomModuleValidationError', - 'Position', - }, -) - - -class CustomModuleValidationErrors(proto.Message): - r"""A list of zero or more errors encountered while validating - the uploaded configuration of an Event Threat Detection Custom - Module. - - Attributes: - errors (MutableSequence[google.cloud.securitycenter_v1.types.CustomModuleValidationError]): - - """ - - errors: MutableSequence['CustomModuleValidationError'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='CustomModuleValidationError', - ) - - -class CustomModuleValidationError(proto.Message): - r"""An error encountered while validating the uploaded - configuration of an Event Threat Detection Custom Module. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - description (str): - A description of the error, suitable for - human consumption. Required. - field_path (str): - The path, in RFC 8901 JSON Pointer format, to - the field that failed validation. This may be - left empty if no specific field is affected. - start (google.cloud.securitycenter_v1.types.Position): - The initial position of the error in the - uploaded text version of the module. This field - may be omitted if no specific position applies, - or if one could not be computed. - - This field is a member of `oneof`_ ``_start``. - end (google.cloud.securitycenter_v1.types.Position): - The end position of the error in the uploaded - text version of the module. This field may be - omitted if no specific position applies, or if - one could not be computed.. - - This field is a member of `oneof`_ ``_end``. - """ - - description: str = proto.Field( - proto.STRING, - number=1, - ) - field_path: str = proto.Field( - proto.STRING, - number=2, - ) - start: 'Position' = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message='Position', - ) - end: 'Position' = proto.Field( - proto.MESSAGE, - number=4, - optional=True, - message='Position', - ) - - -class Position(proto.Message): - r"""A position in the uploaded text version of a module. - - Attributes: - line_number (int): - - column_number (int): - - """ - - line_number: int = proto.Field( - proto.INT32, - number=1, - ) - column_number: int = proto.Field( - proto.INT32, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.py deleted file mode 100644 index 68a2b9fd7d98..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Exfiltration', - 'ExfilResource', - }, -) - - -class Exfiltration(proto.Message): - r"""Exfiltration represents a data exfiltration attempt from one or more - sources to one or more targets. The ``sources`` attribute lists the - sources of the exfiltrated data. The ``targets`` attribute lists the - destinations the data was copied to. - - Attributes: - sources (MutableSequence[google.cloud.securitycenter_v1.types.ExfilResource]): - If there are multiple sources, then the data - is considered "joined" between them. For - instance, BigQuery can join multiple tables, and - each table would be considered a source. - targets (MutableSequence[google.cloud.securitycenter_v1.types.ExfilResource]): - If there are multiple targets, each target - would get a complete copy of the "joined" source - data. - total_exfiltrated_bytes (int): - Total exfiltrated bytes processed for the - entire job. - """ - - sources: MutableSequence['ExfilResource'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ExfilResource', - ) - targets: MutableSequence['ExfilResource'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ExfilResource', - ) - total_exfiltrated_bytes: int = proto.Field( - proto.INT64, - number=3, - ) - - -class ExfilResource(proto.Message): - r"""Resource where data was exfiltrated from or exfiltrated to. - - Attributes: - name (str): - The resource's `full resource - name `__. - components (MutableSequence[str]): - Subcomponents of the asset that was - exfiltrated, like URIs used during exfiltration, - table names, databases, and filenames. For - example, multiple tables might have been - exfiltrated from the same Cloud SQL instance, or - multiple files might have been exfiltrated from - the same Cloud Storage bucket. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - components: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py deleted file mode 100644 index 50a7a7e921f6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v1', - manifest={ - 'ExternalSystem', - }, -) - - -class ExternalSystem(proto.Message): - r"""Representation of third party SIEM/SOAR fields within SCC. - - Attributes: - name (str): - Full resource name of the external system, - for example: - "organizations/1234/sources/5678/findings/123456/externalSystems/jira", - "folders/1234/sources/5678/findings/123456/externalSystems/jira", - "projects/1234/sources/5678/findings/123456/externalSystems/jira". - assignees (MutableSequence[str]): - References primary/secondary etc assignees in - the external system. - external_uid (str): - The identifier that's used to track the - finding's corresponding case in the external - system. - status (str): - The most recent status of the finding's - corresponding case, as reported by the external - system. - external_system_update_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the case was last updated, as - reported by the external system. - case_uri (str): - The link to the finding's corresponding case - in the external system. - case_priority (str): - The priority of the finding's corresponding - case in the external system. - case_sla (google.protobuf.timestamp_pb2.Timestamp): - The SLA of the finding's corresponding case - in the external system. - case_create_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the case was created, as - reported by the external system. - case_close_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the case was closed, as - reported by the external system. - ticket_info (google.cloud.securitycenter_v1.types.ExternalSystem.TicketInfo): - Information about the ticket, if any, that is - being used to track the resolution of the issue - that is identified by this finding. - """ - - class TicketInfo(proto.Message): - r"""Information about the ticket, if any, that is being used to - track the resolution of the issue that is identified by this - finding. - - Attributes: - id (str): - The identifier of the ticket in the ticket - system. - assignee (str): - The assignee of the ticket in the ticket - system. - description (str): - The description of the ticket in the ticket - system. - uri (str): - The link to the ticket in the ticket system. - status (str): - The latest status of the ticket, as reported - by the ticket system. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the ticket was last updated, as - reported by the ticket system. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - assignee: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - uri: str = proto.Field( - proto.STRING, - number=4, - ) - status: str = proto.Field( - proto.STRING, - number=5, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - assignees: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - external_uid: str = proto.Field( - proto.STRING, - number=3, - ) - status: str = proto.Field( - proto.STRING, - number=4, - ) - external_system_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - case_uri: str = proto.Field( - proto.STRING, - number=6, - ) - case_priority: str = proto.Field( - proto.STRING, - number=7, - ) - case_sla: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - case_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - case_close_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - ticket_info: TicketInfo = proto.Field( - proto.MESSAGE, - number=8, - message=TicketInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.py deleted file mode 100644 index 017abee53151..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'File', - }, -) - - -class File(proto.Message): - r"""File information about the related binary/library used by an - executable, or the script used by a script interpreter - - Attributes: - path (str): - Absolute path of the file as a JSON encoded - string. - size (int): - Size of the file in bytes. - sha256 (str): - SHA256 hash of the first hashed_size bytes of the file - encoded as a hex string. If hashed_size == size, sha256 - represents the SHA256 hash of the entire file. - hashed_size (int): - The length in bytes of the file prefix that was hashed. If - hashed_size == size, any hashes reported represent the - entire file. - partially_hashed (bool): - True when the hash covers only a prefix of - the file. - contents (str): - Prefix of the file contents as a JSON-encoded - string. - disk_path (google.cloud.securitycenter_v1.types.File.DiskPath): - Path of the file in terms of underlying - disk/partition identifiers. - """ - - class DiskPath(proto.Message): - r"""Path of the file in terms of underlying disk/partition - identifiers. - - Attributes: - partition_uuid (str): - UUID of the partition (format - https://wiki.archlinux.org/title/persistent_block_device_naming#by-uuid) - relative_path (str): - Relative path of the file in the partition as a JSON encoded - string. Example: /home/user1/executable_file.sh - """ - - partition_uuid: str = proto.Field( - proto.STRING, - number=1, - ) - relative_path: str = proto.Field( - proto.STRING, - number=2, - ) - - path: str = proto.Field( - proto.STRING, - number=1, - ) - size: int = proto.Field( - proto.INT64, - number=2, - ) - sha256: str = proto.Field( - proto.STRING, - number=3, - ) - hashed_size: int = proto.Field( - proto.INT64, - number=4, - ) - partially_hashed: bool = proto.Field( - proto.BOOL, - number=5, - ) - contents: str = proto.Field( - proto.STRING, - number=6, - ) - disk_path: DiskPath = proto.Field( - proto.MESSAGE, - number=7, - message=DiskPath, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py deleted file mode 100644 index 0d3897e0092f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v1.types import access as gcs_access -from google.cloud.securitycenter_v1.types import application as gcs_application -from google.cloud.securitycenter_v1.types import attack_exposure as gcs_attack_exposure -from google.cloud.securitycenter_v1.types import backup_disaster_recovery as gcs_backup_disaster_recovery -from google.cloud.securitycenter_v1.types import cloud_armor as gcs_cloud_armor -from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile as gcs_cloud_dlp_data_profile -from google.cloud.securitycenter_v1.types import cloud_dlp_inspection as gcs_cloud_dlp_inspection -from google.cloud.securitycenter_v1.types import compliance -from google.cloud.securitycenter_v1.types import connection -from google.cloud.securitycenter_v1.types import contact_details -from google.cloud.securitycenter_v1.types import container -from google.cloud.securitycenter_v1.types import database as gcs_database -from google.cloud.securitycenter_v1.types import exfiltration as gcs_exfiltration -from google.cloud.securitycenter_v1.types import external_system -from google.cloud.securitycenter_v1.types import file -from google.cloud.securitycenter_v1.types import group_membership -from google.cloud.securitycenter_v1.types import iam_binding -from google.cloud.securitycenter_v1.types import indicator as gcs_indicator -from google.cloud.securitycenter_v1.types import kernel_rootkit as gcs_kernel_rootkit -from google.cloud.securitycenter_v1.types import kubernetes as gcs_kubernetes -from google.cloud.securitycenter_v1.types import load_balancer -from google.cloud.securitycenter_v1.types import log_entry -from google.cloud.securitycenter_v1.types import mitre_attack as gcs_mitre_attack -from google.cloud.securitycenter_v1.types import notebook as gcs_notebook -from google.cloud.securitycenter_v1.types import org_policy -from google.cloud.securitycenter_v1.types import process -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import security_posture as gcs_security_posture -from google.cloud.securitycenter_v1.types import toxic_combination as gcs_toxic_combination -from google.cloud.securitycenter_v1.types import vulnerability as gcs_vulnerability -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - - A finding is a record of assessment data like security, risk, - health, or privacy, that is ingested into Security Command - Center for presentation, notification, analysis, policy testing, - and enforcement. For example, a cross-site scripting (XSS) - vulnerability in an App Engine application is a finding. - - Attributes: - name (str): - The `relative resource - name `__ - of the finding. Example: - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}", - "projects/{project_id}/sources/{source_id}/findings/{finding_id}". - parent (str): - The relative resource name of the source the finding belongs - to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. For example: - "organizations/{organization_id}/sources/{source_id}". - resource_name (str): - For findings on Google Cloud resources, the full resource - name of the Google Cloud resource this finding is for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - This field is immutable after creation time. - state (google.cloud.securitycenter_v1.types.Finding.State): - The state of the finding. - category (str): - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. - Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (google.protobuf.timestamp_pb2.Timestamp): - The time the finding was first detected. If - an existing finding is updated, then this is the - time the update occurred. For example, if the - finding represents an open firewall, this - property captures the time the detector believes - the firewall became open. The accuracy is - determined by the detector. If the finding is - later resolved, then this time reflects when the - finding was resolved. This must not be set to a - value greater than the current timestamp. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the finding was created in - Security Command Center. - severity (google.cloud.securitycenter_v1.types.Finding.Severity): - The severity of the finding. This field is - managed by the source that writes the finding. - canonical_name (str): - The canonical name of the finding. It's either - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" - or - "projects/{project_number}/sources/{source_id}/findings/{finding_id}", - depending on the closest CRM ancestor of the resource - associated with the finding. - mute (google.cloud.securitycenter_v1.types.Finding.Mute): - Indicates the mute state of a finding (either - muted, unmuted or undefined). Unlike other - attributes of a finding, a finding provider - shouldn't set the value of mute. - finding_class (google.cloud.securitycenter_v1.types.Finding.FindingClass): - The class of the finding. - indicator (google.cloud.securitycenter_v1.types.Indicator): - Represents what's commonly known as an *indicator of - compromise* (IoC) in computer forensics. This is an artifact - observed on a network or in an operating system that, with - high confidence, indicates a computer intrusion. For more - information, see `Indicator of - compromise `__. - vulnerability (google.cloud.securitycenter_v1.types.Vulnerability): - Represents vulnerability-specific fields like - CVE and CVSS scores. CVE stands for Common - Vulnerabilities and Exposures - (https://cve.mitre.org/about/) - mute_update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The most recent time this - finding was muted or unmuted. - external_systems (MutableMapping[str, google.cloud.securitycenter_v1.types.ExternalSystem]): - Output only. Third party SIEM/SOAR fields - within SCC, contains external system information - and external system finding fields. - mitre_attack (google.cloud.securitycenter_v1.types.MitreAttack): - MITRE ATT&CK tactics and techniques related - to this finding. See: https://attack.mitre.org - access (google.cloud.securitycenter_v1.types.Access): - Access details associated with the finding, - such as more information on the caller, which - method was accessed, and from where. - connections (MutableSequence[google.cloud.securitycenter_v1.types.Connection]): - Contains information about the IP connection - associated with the finding. - mute_initiator (str): - Records additional information about the mute operation, for - example, the `mute - configuration `__ - that muted the finding and the user who muted the finding. - processes (MutableSequence[google.cloud.securitycenter_v1.types.Process]): - Represents operating system processes - associated with the Finding. - contacts (MutableMapping[str, google.cloud.securitycenter_v1.types.ContactDetails]): - Output only. Map containing the points of contact for the - given finding. The key represents the type of contact, while - the value contains a list of all the contacts that pertain. - Please refer to: - https://cloud.google.com/resource-manager/docs/managing-notification-contacts#notification-categories - - :: - - { - "security": { - "contacts": [ - { - "email": "person1@company.com" - }, - { - "email": "person2@company.com" - } - ] - } - } - compliances (MutableSequence[google.cloud.securitycenter_v1.types.Compliance]): - Contains compliance information for security - standards associated to the finding. - parent_display_name (str): - Output only. The human readable display name - of the finding source such as "Event Threat - Detection" or "Security Health Analytics". - description (str): - Contains more details about the finding. - exfiltration (google.cloud.securitycenter_v1.types.Exfiltration): - Represents exfiltrations associated with the - finding. - iam_bindings (MutableSequence[google.cloud.securitycenter_v1.types.IamBinding]): - Represents IAM bindings associated with the - finding. - next_steps (str): - Steps to address the finding. - module_name (str): - Unique identifier of the module which - generated the finding. Example: - - folders/598186756061/securityHealthAnalyticsSettings/customModules/56799441161885 - containers (MutableSequence[google.cloud.securitycenter_v1.types.Container]): - Containers associated with the finding. This - field provides information for both Kubernetes - and non-Kubernetes containers. - kubernetes (google.cloud.securitycenter_v1.types.Kubernetes): - Kubernetes resources associated with the - finding. - database (google.cloud.securitycenter_v1.types.Database): - Database associated with the finding. - attack_exposure (google.cloud.securitycenter_v1.types.AttackExposure): - The results of an attack path simulation - relevant to this finding. - files (MutableSequence[google.cloud.securitycenter_v1.types.File]): - File associated with the finding. - cloud_dlp_inspection (google.cloud.securitycenter_v1.types.CloudDlpInspection): - Cloud Data Loss Prevention (Cloud DLP) - inspection results that are associated with the - finding. - cloud_dlp_data_profile (google.cloud.securitycenter_v1.types.CloudDlpDataProfile): - Cloud DLP data profile that is associated - with the finding. - kernel_rootkit (google.cloud.securitycenter_v1.types.KernelRootkit): - Signature of the kernel rootkit. - org_policies (MutableSequence[google.cloud.securitycenter_v1.types.OrgPolicy]): - Contains information about the org policies - associated with the finding. - application (google.cloud.securitycenter_v1.types.Application): - Represents an application associated with the - finding. - backup_disaster_recovery (google.cloud.securitycenter_v1.types.BackupDisasterRecovery): - Fields related to Backup and DR findings. - security_posture (google.cloud.securitycenter_v1.types.SecurityPosture): - The security posture associated with the - finding. - log_entries (MutableSequence[google.cloud.securitycenter_v1.types.LogEntry]): - Log entries that are relevant to the finding. - load_balancers (MutableSequence[google.cloud.securitycenter_v1.types.LoadBalancer]): - The load balancers associated with the - finding. - cloud_armor (google.cloud.securitycenter_v1.types.CloudArmor): - Fields related to Cloud Armor findings. - notebook (google.cloud.securitycenter_v1.types.Notebook): - Notebook associated with the finding. - toxic_combination (google.cloud.securitycenter_v1.types.ToxicCombination): - Contains details about a group of security - issues that, when the issues occur together, - represent a greater risk than when the issues - occur independently. A group of such issues is - referred to as a toxic combination. - This field cannot be updated. Its value is - ignored in all update requests. - group_memberships (MutableSequence[google.cloud.securitycenter_v1.types.GroupMembership]): - Contains details about groups of which this - finding is a member. A group is a collection of - findings that are related in some way. This - field cannot be updated. Its value is ignored in - all update requests. - """ - class State(proto.Enum): - r"""The state of the finding. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - ACTIVE (1): - The finding requires attention and has not - been addressed yet. - INACTIVE (2): - The finding has been fixed, triaged as a - non-issue or otherwise addressed and is no - longer active. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - class Severity(proto.Enum): - r"""The severity of the finding. - - Values: - SEVERITY_UNSPECIFIED (0): - This value is used for findings when a source - doesn't write a severity value. - CRITICAL (1): - Vulnerability: - - A critical vulnerability is easily discoverable - by an external actor, exploitable, and results - in the direct ability to execute arbitrary code, - exfiltrate data, and otherwise gain additional - access and privileges to cloud resources and - workloads. Examples include publicly accessible - unprotected user data and public SSH access with - weak or no passwords. - - Threat: - - Indicates a threat that is able to access, - modify, or delete data or execute unauthorized - code within existing resources. - HIGH (2): - Vulnerability: - - A high risk vulnerability can be easily - discovered and exploited in combination with - other vulnerabilities in order to gain direct - access and the ability to execute arbitrary - code, exfiltrate data, and otherwise gain - additional access and privileges to cloud - resources and workloads. An example is a - database with weak or no passwords that is only - accessible internally. This database could - easily be compromised by an actor that had - access to the internal network. - - Threat: - - Indicates a threat that is able to create new - computational resources in an environment but - not able to access data or execute code in - existing resources. - MEDIUM (3): - Vulnerability: - - A medium risk vulnerability could be used by an - actor to gain access to resources or privileges - that enable them to eventually (through multiple - steps or a complex exploit) gain access and the - ability to execute arbitrary code or exfiltrate - data. An example is a service account with - access to more projects than it should have. If - an actor gains access to the service account, - they could potentially use that access to - manipulate a project the service account was not - intended to. - - Threat: - - Indicates a threat that is able to cause - operational impact but may not access data or - execute unauthorized code. - LOW (4): - Vulnerability: - - A low risk vulnerability hampers a security - organization's ability to detect vulnerabilities - or active threats in their deployment, or - prevents the root cause investigation of - security issues. An example is monitoring and - logs being disabled for resource configurations - and access. - - Threat: - - Indicates a threat that has obtained minimal - access to an environment but is not able to - access data, execute code, or create resources. - """ - SEVERITY_UNSPECIFIED = 0 - CRITICAL = 1 - HIGH = 2 - MEDIUM = 3 - LOW = 4 - - class Mute(proto.Enum): - r"""Mute state a finding can be in. - - Values: - MUTE_UNSPECIFIED (0): - Unspecified. - MUTED (1): - Finding has been muted. - UNMUTED (2): - Finding has been unmuted. - UNDEFINED (4): - Finding has never been muted/unmuted. - """ - MUTE_UNSPECIFIED = 0 - MUTED = 1 - UNMUTED = 2 - UNDEFINED = 4 - - class FindingClass(proto.Enum): - r"""Represents what kind of Finding it is. - - Values: - FINDING_CLASS_UNSPECIFIED (0): - Unspecified finding class. - THREAT (1): - Describes unwanted or malicious activity. - VULNERABILITY (2): - Describes a potential weakness in software - that increases risk to Confidentiality & - Integrity & Availability. - MISCONFIGURATION (3): - Describes a potential weakness in cloud - resource/asset configuration that increases - risk. - OBSERVATION (4): - Describes a security observation that is for - informational purposes. - SCC_ERROR (5): - Describes an error that prevents some SCC - functionality. - POSTURE_VIOLATION (6): - Describes a potential security risk due to a - change in the security posture. - TOXIC_COMBINATION (7): - Describes a group of security issues that, - when the issues occur together, represent a - greater risk than when the issues occur - independently. A group of such issues is - referred to as a toxic combination. - """ - FINDING_CLASS_UNSPECIFIED = 0 - THREAT = 1 - VULNERABILITY = 2 - MISCONFIGURATION = 3 - OBSERVATION = 4 - SCC_ERROR = 5 - POSTURE_VIOLATION = 6 - TOXIC_COMBINATION = 7 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - resource_name: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - category: str = proto.Field( - proto.STRING, - number=5, - ) - external_uri: str = proto.Field( - proto.STRING, - number=6, - ) - source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - severity: Severity = proto.Field( - proto.ENUM, - number=12, - enum=Severity, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=14, - ) - mute: Mute = proto.Field( - proto.ENUM, - number=15, - enum=Mute, - ) - finding_class: FindingClass = proto.Field( - proto.ENUM, - number=17, - enum=FindingClass, - ) - indicator: gcs_indicator.Indicator = proto.Field( - proto.MESSAGE, - number=18, - message=gcs_indicator.Indicator, - ) - vulnerability: gcs_vulnerability.Vulnerability = proto.Field( - proto.MESSAGE, - number=20, - message=gcs_vulnerability.Vulnerability, - ) - mute_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=21, - message=timestamp_pb2.Timestamp, - ) - external_systems: MutableMapping[str, external_system.ExternalSystem] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=22, - message=external_system.ExternalSystem, - ) - mitre_attack: gcs_mitre_attack.MitreAttack = proto.Field( - proto.MESSAGE, - number=25, - message=gcs_mitre_attack.MitreAttack, - ) - access: gcs_access.Access = proto.Field( - proto.MESSAGE, - number=26, - message=gcs_access.Access, - ) - connections: MutableSequence[connection.Connection] = proto.RepeatedField( - proto.MESSAGE, - number=31, - message=connection.Connection, - ) - mute_initiator: str = proto.Field( - proto.STRING, - number=28, - ) - processes: MutableSequence[process.Process] = proto.RepeatedField( - proto.MESSAGE, - number=30, - message=process.Process, - ) - contacts: MutableMapping[str, contact_details.ContactDetails] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=33, - message=contact_details.ContactDetails, - ) - compliances: MutableSequence[compliance.Compliance] = proto.RepeatedField( - proto.MESSAGE, - number=34, - message=compliance.Compliance, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=36, - ) - description: str = proto.Field( - proto.STRING, - number=37, - ) - exfiltration: gcs_exfiltration.Exfiltration = proto.Field( - proto.MESSAGE, - number=38, - message=gcs_exfiltration.Exfiltration, - ) - iam_bindings: MutableSequence[iam_binding.IamBinding] = proto.RepeatedField( - proto.MESSAGE, - number=39, - message=iam_binding.IamBinding, - ) - next_steps: str = proto.Field( - proto.STRING, - number=40, - ) - module_name: str = proto.Field( - proto.STRING, - number=41, - ) - containers: MutableSequence[container.Container] = proto.RepeatedField( - proto.MESSAGE, - number=42, - message=container.Container, - ) - kubernetes: gcs_kubernetes.Kubernetes = proto.Field( - proto.MESSAGE, - number=43, - message=gcs_kubernetes.Kubernetes, - ) - database: gcs_database.Database = proto.Field( - proto.MESSAGE, - number=44, - message=gcs_database.Database, - ) - attack_exposure: gcs_attack_exposure.AttackExposure = proto.Field( - proto.MESSAGE, - number=45, - message=gcs_attack_exposure.AttackExposure, - ) - files: MutableSequence[file.File] = proto.RepeatedField( - proto.MESSAGE, - number=46, - message=file.File, - ) - cloud_dlp_inspection: gcs_cloud_dlp_inspection.CloudDlpInspection = proto.Field( - proto.MESSAGE, - number=48, - message=gcs_cloud_dlp_inspection.CloudDlpInspection, - ) - cloud_dlp_data_profile: gcs_cloud_dlp_data_profile.CloudDlpDataProfile = proto.Field( - proto.MESSAGE, - number=49, - message=gcs_cloud_dlp_data_profile.CloudDlpDataProfile, - ) - kernel_rootkit: gcs_kernel_rootkit.KernelRootkit = proto.Field( - proto.MESSAGE, - number=50, - message=gcs_kernel_rootkit.KernelRootkit, - ) - org_policies: MutableSequence[org_policy.OrgPolicy] = proto.RepeatedField( - proto.MESSAGE, - number=51, - message=org_policy.OrgPolicy, - ) - application: gcs_application.Application = proto.Field( - proto.MESSAGE, - number=53, - message=gcs_application.Application, - ) - backup_disaster_recovery: gcs_backup_disaster_recovery.BackupDisasterRecovery = proto.Field( - proto.MESSAGE, - number=55, - message=gcs_backup_disaster_recovery.BackupDisasterRecovery, - ) - security_posture: gcs_security_posture.SecurityPosture = proto.Field( - proto.MESSAGE, - number=56, - message=gcs_security_posture.SecurityPosture, - ) - log_entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( - proto.MESSAGE, - number=57, - message=log_entry.LogEntry, - ) - load_balancers: MutableSequence[load_balancer.LoadBalancer] = proto.RepeatedField( - proto.MESSAGE, - number=58, - message=load_balancer.LoadBalancer, - ) - cloud_armor: gcs_cloud_armor.CloudArmor = proto.Field( - proto.MESSAGE, - number=59, - message=gcs_cloud_armor.CloudArmor, - ) - notebook: gcs_notebook.Notebook = proto.Field( - proto.MESSAGE, - number=63, - message=gcs_notebook.Notebook, - ) - toxic_combination: gcs_toxic_combination.ToxicCombination = proto.Field( - proto.MESSAGE, - number=64, - message=gcs_toxic_combination.ToxicCombination, - ) - group_memberships: MutableSequence[group_membership.GroupMembership] = proto.RepeatedField( - proto.MESSAGE, - number=65, - message=group_membership.GroupMembership, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.py deleted file mode 100644 index 577452411641..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.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.securitycenter.v1', - manifest={ - 'Folder', - }, -) - - -class Folder(proto.Message): - r"""Message that contains the resource name and display name of a - folder resource. - - Attributes: - resource_folder (str): - Full resource name of this folder. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_folder_display_name (str): - The user defined display name for this - folder. - """ - - resource_folder: str = proto.Field( - proto.STRING, - number=1, - ) - resource_folder_display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.py deleted file mode 100644 index d95cb97ea0a4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.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.cloud.securitycenter.v1', - manifest={ - 'GroupMembership', - }, -) - - -class GroupMembership(proto.Message): - r"""Contains details about groups of which this finding is a - member. A group is a collection of findings that are related in - some way. - - Attributes: - group_type (google.cloud.securitycenter_v1.types.GroupMembership.GroupType): - Type of group. - group_id (str): - ID of the group. - """ - class GroupType(proto.Enum): - r"""Possible types of groups. - - Values: - GROUP_TYPE_UNSPECIFIED (0): - Default value. - GROUP_TYPE_TOXIC_COMBINATION (1): - Group represents a toxic combination. - """ - GROUP_TYPE_UNSPECIFIED = 0 - GROUP_TYPE_TOXIC_COMBINATION = 1 - - group_type: GroupType = proto.Field( - proto.ENUM, - number=1, - enum=GroupType, - ) - group_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py deleted file mode 100644 index cab59d31ec7c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py +++ /dev/null @@ -1,77 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v1', - manifest={ - 'IamBinding', - }, -) - - -class IamBinding(proto.Message): - r"""Represents a particular IAM binding, which captures a - member's role addition, removal, or state. - - Attributes: - action (google.cloud.securitycenter_v1.types.IamBinding.Action): - The action that was performed on a Binding. - role (str): - Role that is assigned to "members". - For example, "roles/viewer", "roles/editor", or - "roles/owner". - member (str): - A single identity requesting access for a - Cloud Platform resource, for example, - "foo@google.com". - """ - class Action(proto.Enum): - r"""The type of action performed on a Binding in a policy. - - Values: - ACTION_UNSPECIFIED (0): - Unspecified. - ADD (1): - Addition of a Binding. - REMOVE (2): - Removal of a Binding. - """ - ACTION_UNSPECIFIED = 0 - ADD = 1 - REMOVE = 2 - - action: Action = proto.Field( - proto.ENUM, - number=1, - enum=Action, - ) - role: str = proto.Field( - proto.STRING, - number=2, - ) - member: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py deleted file mode 100644 index f75bd00701dd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py +++ /dev/null @@ -1,186 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v1', - manifest={ - 'Indicator', - }, -) - - -class Indicator(proto.Message): - r"""Represents what's commonly known as an *indicator of compromise* - (IoC) in computer forensics. This is an artifact observed on a - network or in an operating system that, with high confidence, - indicates a computer intrusion. For more information, see `Indicator - of - compromise `__. - - Attributes: - ip_addresses (MutableSequence[str]): - The list of IP addresses that are associated - with the finding. - domains (MutableSequence[str]): - List of domains associated to the Finding. - signatures (MutableSequence[google.cloud.securitycenter_v1.types.Indicator.ProcessSignature]): - The list of matched signatures indicating - that the given process is present in the - environment. - uris (MutableSequence[str]): - The list of URIs associated to the Findings. - """ - - class ProcessSignature(proto.Message): - r"""Indicates what signature matched this process. - - 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: - memory_hash_signature (google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.MemoryHashSignature): - Signature indicating that a binary family was - matched. - - This field is a member of `oneof`_ ``signature``. - yara_rule_signature (google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.YaraRuleSignature): - Signature indicating that a YARA rule was - matched. - - This field is a member of `oneof`_ ``signature``. - signature_type (google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.SignatureType): - Describes the type of resource associated - with the signature. - """ - class SignatureType(proto.Enum): - r"""Possible resource types to be associated with a signature. - - Values: - SIGNATURE_TYPE_UNSPECIFIED (0): - The default signature type. - SIGNATURE_TYPE_PROCESS (1): - Used for signatures concerning processes. - SIGNATURE_TYPE_FILE (2): - Used for signatures concerning disks. - """ - SIGNATURE_TYPE_UNSPECIFIED = 0 - SIGNATURE_TYPE_PROCESS = 1 - SIGNATURE_TYPE_FILE = 2 - - class MemoryHashSignature(proto.Message): - r"""A signature corresponding to memory page hashes. - - Attributes: - binary_family (str): - The binary family. - detections (MutableSequence[google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.MemoryHashSignature.Detection]): - The list of memory hash detections - contributing to the binary family match. - """ - - class Detection(proto.Message): - r"""Memory hash detection contributing to the binary family - match. - - Attributes: - binary (str): - The name of the binary associated with the - memory hash signature detection. - percent_pages_matched (float): - The percentage of memory page hashes in the - signature that were matched. - """ - - binary: str = proto.Field( - proto.STRING, - number=2, - ) - percent_pages_matched: float = proto.Field( - proto.DOUBLE, - number=3, - ) - - binary_family: str = proto.Field( - proto.STRING, - number=1, - ) - detections: MutableSequence['Indicator.ProcessSignature.MemoryHashSignature.Detection'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Indicator.ProcessSignature.MemoryHashSignature.Detection', - ) - - class YaraRuleSignature(proto.Message): - r"""A signature corresponding to a YARA rule. - - Attributes: - yara_rule (str): - The name of the YARA rule. - """ - - yara_rule: str = proto.Field( - proto.STRING, - number=5, - ) - - memory_hash_signature: 'Indicator.ProcessSignature.MemoryHashSignature' = proto.Field( - proto.MESSAGE, - number=6, - oneof='signature', - message='Indicator.ProcessSignature.MemoryHashSignature', - ) - yara_rule_signature: 'Indicator.ProcessSignature.YaraRuleSignature' = proto.Field( - proto.MESSAGE, - number=7, - oneof='signature', - message='Indicator.ProcessSignature.YaraRuleSignature', - ) - signature_type: 'Indicator.ProcessSignature.SignatureType' = proto.Field( - proto.ENUM, - number=8, - enum='Indicator.ProcessSignature.SignatureType', - ) - - ip_addresses: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - domains: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - signatures: MutableSequence[ProcessSignature] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=ProcessSignature, - ) - uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.py deleted file mode 100644 index d9c18edeec46..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'KernelRootkit', - }, -) - - -class KernelRootkit(proto.Message): - r"""Kernel mode rootkit signatures. - - Attributes: - name (str): - Rootkit name, when available. - unexpected_code_modification (bool): - True if unexpected modifications of kernel - code memory are present. - unexpected_read_only_data_modification (bool): - True if unexpected modifications of kernel - read-only data memory are present. - unexpected_ftrace_handler (bool): - True if ``ftrace`` points are present with callbacks - pointing to regions that are not in the expected kernel or - module code range. - unexpected_kprobe_handler (bool): - True if ``kprobe`` points are present with callbacks - pointing to regions that are not in the expected kernel or - module code range. - unexpected_kernel_code_pages (bool): - True if kernel code pages that are not in the - expected kernel or module code regions are - present. - unexpected_system_call_handler (bool): - True if system call handlers that are are not - in the expected kernel or module code regions - are present. - unexpected_interrupt_handler (bool): - True if interrupt handlers that are are not - in the expected kernel or module code regions - are present. - unexpected_processes_in_runqueue (bool): - True if unexpected processes in the scheduler - run queue are present. Such processes are in the - run queue, but not in the process task list. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - unexpected_code_modification: bool = proto.Field( - proto.BOOL, - number=2, - ) - unexpected_read_only_data_modification: bool = proto.Field( - proto.BOOL, - number=3, - ) - unexpected_ftrace_handler: bool = proto.Field( - proto.BOOL, - number=4, - ) - unexpected_kprobe_handler: bool = proto.Field( - proto.BOOL, - number=5, - ) - unexpected_kernel_code_pages: bool = proto.Field( - proto.BOOL, - number=6, - ) - unexpected_system_call_handler: bool = proto.Field( - proto.BOOL, - number=7, - ) - unexpected_interrupt_handler: bool = proto.Field( - proto.BOOL, - number=8, - ) - unexpected_processes_in_runqueue: bool = proto.Field( - proto.BOOL, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.py deleted file mode 100644 index b91973ac449b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v1.types import container -from google.cloud.securitycenter_v1.types import label - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Kubernetes', - }, -) - - -class Kubernetes(proto.Message): - r"""Kubernetes-related attributes. - - Attributes: - pods (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Pod]): - Kubernetes - `Pods `__ - associated with the finding. This field contains Pod records - for each container that is owned by a Pod. - nodes (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Node]): - Provides Kubernetes - `node `__ - information. - node_pools (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.NodePool]): - GKE `node - pools `__ - associated with the finding. This field contains node pool - information for each node, when it is available. - roles (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Role]): - Provides Kubernetes role information for findings that - involve `Roles or - ClusterRoles `__. - bindings (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Binding]): - Provides Kubernetes role binding information for findings - that involve `RoleBindings or - ClusterRoleBindings `__. - access_reviews (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.AccessReview]): - Provides information on any Kubernetes access - reviews (privilege checks) relevant to the - finding. - objects (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Object]): - Kubernetes objects related to the finding. - """ - - class Pod(proto.Message): - r"""A Kubernetes Pod. - - Attributes: - ns (str): - Kubernetes Pod namespace. - name (str): - Kubernetes Pod name. - labels (MutableSequence[google.cloud.securitycenter_v1.types.Label]): - Pod labels. For Kubernetes containers, these - are applied to the container. - containers (MutableSequence[google.cloud.securitycenter_v1.types.Container]): - Pod containers associated with this finding, - if any. - """ - - ns: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - labels: MutableSequence[label.Label] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=label.Label, - ) - containers: MutableSequence[container.Container] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=container.Container, - ) - - class Node(proto.Message): - r"""Kubernetes nodes associated with the finding. - - Attributes: - name (str): - `Full resource - name `__ of - the Compute Engine VM running the cluster node. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - class NodePool(proto.Message): - r"""Provides GKE node pool information. - - Attributes: - name (str): - Kubernetes node pool name. - nodes (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Node]): - Nodes associated with the finding. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - nodes: MutableSequence['Kubernetes.Node'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Kubernetes.Node', - ) - - class Role(proto.Message): - r"""Kubernetes Role or ClusterRole. - - Attributes: - kind (google.cloud.securitycenter_v1.types.Kubernetes.Role.Kind): - Role type. - ns (str): - Role namespace. - name (str): - Role name. - """ - class Kind(proto.Enum): - r"""Types of Kubernetes roles. - - Values: - KIND_UNSPECIFIED (0): - Role type is not specified. - ROLE (1): - Kubernetes Role. - CLUSTER_ROLE (2): - Kubernetes ClusterRole. - """ - KIND_UNSPECIFIED = 0 - ROLE = 1 - CLUSTER_ROLE = 2 - - kind: 'Kubernetes.Role.Kind' = proto.Field( - proto.ENUM, - number=1, - enum='Kubernetes.Role.Kind', - ) - ns: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - class Binding(proto.Message): - r"""Represents a Kubernetes RoleBinding or ClusterRoleBinding. - - Attributes: - ns (str): - Namespace for the binding. - name (str): - Name for the binding. - role (google.cloud.securitycenter_v1.types.Kubernetes.Role): - The Role or ClusterRole referenced by the - binding. - subjects (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Subject]): - Represents one or more subjects that are - bound to the role. Not always available for - PATCH requests. - """ - - ns: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - role: 'Kubernetes.Role' = proto.Field( - proto.MESSAGE, - number=3, - message='Kubernetes.Role', - ) - subjects: MutableSequence['Kubernetes.Subject'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Kubernetes.Subject', - ) - - class Subject(proto.Message): - r"""Represents a Kubernetes subject. - - Attributes: - kind (google.cloud.securitycenter_v1.types.Kubernetes.Subject.AuthType): - Authentication type for the subject. - ns (str): - Namespace for the subject. - name (str): - Name for the subject. - """ - class AuthType(proto.Enum): - r"""Auth types that can be used for the subject's kind field. - - Values: - AUTH_TYPE_UNSPECIFIED (0): - Authentication is not specified. - USER (1): - User with valid certificate. - SERVICEACCOUNT (2): - Users managed by Kubernetes API with - credentials stored as secrets. - GROUP (3): - Collection of users. - """ - AUTH_TYPE_UNSPECIFIED = 0 - USER = 1 - SERVICEACCOUNT = 2 - GROUP = 3 - - kind: 'Kubernetes.Subject.AuthType' = proto.Field( - proto.ENUM, - number=1, - enum='Kubernetes.Subject.AuthType', - ) - ns: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - class AccessReview(proto.Message): - r"""Conveys information about a Kubernetes access review (such as one - returned by a - ```kubectl auth can-i`` `__ - command) that was involved in a finding. - - Attributes: - group (str): - The API group of the resource. "*" means all. - ns (str): - Namespace of the action being requested. - Currently, there is no distinction between no - namespace and all namespaces. Both are - represented by "" (empty). - name (str): - The name of the resource being requested. - Empty means all. - resource (str): - The optional resource type requested. "*" means all. - subresource (str): - The optional subresource type. - verb (str): - A Kubernetes resource API verb, like get, list, watch, - create, update, delete, proxy. "*" means all. - version (str): - The API version of the resource. "*" means all. - """ - - group: str = proto.Field( - proto.STRING, - number=1, - ) - ns: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - resource: str = proto.Field( - proto.STRING, - number=4, - ) - subresource: str = proto.Field( - proto.STRING, - number=5, - ) - verb: str = proto.Field( - proto.STRING, - number=6, - ) - version: str = proto.Field( - proto.STRING, - number=7, - ) - - class Object(proto.Message): - r"""Kubernetes object related to the finding, uniquely identified - by GKNN. Used if the object Kind is not one of Pod, Node, - NodePool, Binding, or AccessReview. - - Attributes: - group (str): - Kubernetes object group, such as - "policy.k8s.io/v1". - kind (str): - Kubernetes object kind, such as "Namespace". - ns (str): - Kubernetes object namespace. Must be a valid - DNS label. Named "ns" to avoid collision with - C++ namespace keyword. For details see - https://kubernetes.io/docs/tasks/administer-cluster/namespaces/. - name (str): - Kubernetes object name. For details see - https://kubernetes.io/docs/concepts/overview/working-with-objects/names/. - containers (MutableSequence[google.cloud.securitycenter_v1.types.Container]): - Pod containers associated with this finding, - if any. - """ - - group: str = proto.Field( - proto.STRING, - number=1, - ) - kind: str = proto.Field( - proto.STRING, - number=2, - ) - ns: str = proto.Field( - proto.STRING, - number=3, - ) - name: str = proto.Field( - proto.STRING, - number=4, - ) - containers: MutableSequence[container.Container] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=container.Container, - ) - - pods: MutableSequence[Pod] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Pod, - ) - nodes: MutableSequence[Node] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Node, - ) - node_pools: MutableSequence[NodePool] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=NodePool, - ) - roles: MutableSequence[Role] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=Role, - ) - bindings: MutableSequence[Binding] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Binding, - ) - access_reviews: MutableSequence[AccessReview] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=AccessReview, - ) - objects: MutableSequence[Object] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Object, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.py deleted file mode 100644 index 8ece19d81c07..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.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.securitycenter.v1', - manifest={ - 'Label', - }, -) - - -class Label(proto.Message): - r"""Represents a generic name-value label. A label has separate name and - value fields to support filtering with the ``contains()`` function. - For more information, see `Filtering on array-type - fields `__. - - Attributes: - name (str): - Name of the label. - value (str): - Value that corresponds to the label's name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.py deleted file mode 100644 index 050b3b0c6c9a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.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.cloud.securitycenter.v1', - manifest={ - 'LoadBalancer', - }, -) - - -class LoadBalancer(proto.Message): - r"""Contains information related to the load balancer associated - with the finding. - - Attributes: - name (str): - The name of the load balancer associated with - the finding. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.py deleted file mode 100644 index 6e4222745dd0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.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 __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.securitycenter.v1', - manifest={ - 'LogEntry', - 'CloudLoggingEntry', - }, -) - - -class LogEntry(proto.Message): - r"""An individual entry in a log. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - cloud_logging_entry (google.cloud.securitycenter_v1.types.CloudLoggingEntry): - An individual entry in a log stored in Cloud - Logging. - - This field is a member of `oneof`_ ``log_entry``. - """ - - cloud_logging_entry: 'CloudLoggingEntry' = proto.Field( - proto.MESSAGE, - number=1, - oneof='log_entry', - message='CloudLoggingEntry', - ) - - -class CloudLoggingEntry(proto.Message): - r"""Metadata taken from a `Cloud Logging - LogEntry `__ - - Attributes: - insert_id (str): - A unique identifier for the log entry. - log_id (str): - The type of the log (part of ``log_name``. ``log_name`` is - the resource name of the log to which this log entry - belongs). For example: - ``cloudresourcemanager.googleapis.com/activity``. Note that - this field is not URL-encoded, unlike the ``LOG_ID`` field - in ``LogEntry``. - resource_container (str): - The organization, folder, or project of the - monitored resource that produced this log entry. - timestamp (google.protobuf.timestamp_pb2.Timestamp): - The time the event described by the log entry - occurred. - """ - - insert_id: str = proto.Field( - proto.STRING, - number=1, - ) - log_id: str = proto.Field( - proto.STRING, - number=2, - ) - resource_container: str = proto.Field( - proto.STRING, - number=3, - ) - timestamp: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.py deleted file mode 100644 index fe3616643316..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'MitreAttack', - }, -) - - -class MitreAttack(proto.Message): - r"""MITRE ATT&CK tactics and techniques related to this finding. - See: https://attack.mitre.org - - Attributes: - primary_tactic (google.cloud.securitycenter_v1.types.MitreAttack.Tactic): - The MITRE ATT&CK tactic most closely - represented by this finding, if any. - primary_techniques (MutableSequence[google.cloud.securitycenter_v1.types.MitreAttack.Technique]): - The MITRE ATT&CK technique most closely represented by this - finding, if any. primary_techniques is a repeated field - because there are multiple levels of MITRE ATT&CK - techniques. If the technique most closely represented by - this finding is a sub-technique (e.g. - ``SCANNING_IP_BLOCKS``), both the sub-technique and its - parent technique(s) will be listed (e.g. - ``SCANNING_IP_BLOCKS``, ``ACTIVE_SCANNING``). - additional_tactics (MutableSequence[google.cloud.securitycenter_v1.types.MitreAttack.Tactic]): - Additional MITRE ATT&CK tactics related to - this finding, if any. - additional_techniques (MutableSequence[google.cloud.securitycenter_v1.types.MitreAttack.Technique]): - Additional MITRE ATT&CK techniques related to - this finding, if any, along with any of their - respective parent techniques. - version (str): - The MITRE ATT&CK version referenced by the - above fields. E.g. "8". - """ - class Tactic(proto.Enum): - r"""MITRE ATT&CK tactics that can be referenced by SCC findings. - See: https://attack.mitre.org/tactics/enterprise/ - - Values: - TACTIC_UNSPECIFIED (0): - Unspecified value. - RECONNAISSANCE (1): - TA0043 - RESOURCE_DEVELOPMENT (2): - TA0042 - INITIAL_ACCESS (5): - TA0001 - EXECUTION (3): - TA0002 - PERSISTENCE (6): - TA0003 - PRIVILEGE_ESCALATION (8): - TA0004 - DEFENSE_EVASION (7): - TA0005 - CREDENTIAL_ACCESS (9): - TA0006 - DISCOVERY (10): - TA0007 - LATERAL_MOVEMENT (11): - TA0008 - COLLECTION (12): - TA0009 - COMMAND_AND_CONTROL (4): - TA0011 - EXFILTRATION (13): - TA0010 - IMPACT (14): - TA0040 - """ - TACTIC_UNSPECIFIED = 0 - RECONNAISSANCE = 1 - RESOURCE_DEVELOPMENT = 2 - INITIAL_ACCESS = 5 - EXECUTION = 3 - PERSISTENCE = 6 - PRIVILEGE_ESCALATION = 8 - DEFENSE_EVASION = 7 - CREDENTIAL_ACCESS = 9 - DISCOVERY = 10 - LATERAL_MOVEMENT = 11 - COLLECTION = 12 - COMMAND_AND_CONTROL = 4 - EXFILTRATION = 13 - IMPACT = 14 - - class Technique(proto.Enum): - r"""MITRE ATT&CK techniques that can be referenced by SCC - findings. See: https://attack.mitre.org/techniques/enterprise/ - Next ID: 63 - - Values: - TECHNIQUE_UNSPECIFIED (0): - Unspecified value. - MASQUERADING (49): - T1036 - MATCH_LEGITIMATE_NAME_OR_LOCATION (50): - T1036.005 - BOOT_OR_LOGON_INITIALIZATION_SCRIPTS (37): - T1037 - STARTUP_ITEMS (38): - T1037.005 - NETWORK_SERVICE_DISCOVERY (32): - T1046 - PROCESS_DISCOVERY (56): - T1057 - COMMAND_AND_SCRIPTING_INTERPRETER (6): - T1059 - UNIX_SHELL (7): - T1059.004 - PYTHON (59): - T1059.006 - PERMISSION_GROUPS_DISCOVERY (18): - T1069 - CLOUD_GROUPS (19): - T1069.003 - APPLICATION_LAYER_PROTOCOL (45): - T1071 - DNS (46): - T1071.004 - SOFTWARE_DEPLOYMENT_TOOLS (47): - T1072 - VALID_ACCOUNTS (14): - T1078 - DEFAULT_ACCOUNTS (35): - T1078.001 - LOCAL_ACCOUNTS (15): - T1078.003 - CLOUD_ACCOUNTS (16): - T1078.004 - PROXY (9): - T1090 - EXTERNAL_PROXY (10): - T1090.002 - MULTI_HOP_PROXY (11): - T1090.003 - ACCOUNT_MANIPULATION (22): - T1098 - ADDITIONAL_CLOUD_CREDENTIALS (40): - T1098.001 - SSH_AUTHORIZED_KEYS (23): - T1098.004 - ADDITIONAL_CONTAINER_CLUSTER_ROLES (58): - T1098.006 - INGRESS_TOOL_TRANSFER (3): - T1105 - NATIVE_API (4): - T1106 - BRUTE_FORCE (44): - T1110 - SHARED_MODULES (5): - T1129 - ACCESS_TOKEN_MANIPULATION (33): - T1134 - TOKEN_IMPERSONATION_OR_THEFT (39): - T1134.001 - EXPLOIT_PUBLIC_FACING_APPLICATION (27): - T1190 - DOMAIN_POLICY_MODIFICATION (30): - T1484 - DATA_DESTRUCTION (29): - T1485 - SERVICE_STOP (52): - T1489 - INHIBIT_SYSTEM_RECOVERY (36): - T1490 - RESOURCE_HIJACKING (8): - T1496 - NETWORK_DENIAL_OF_SERVICE (17): - T1498 - CLOUD_SERVICE_DISCOVERY (48): - T1526 - STEAL_APPLICATION_ACCESS_TOKEN (42): - T1528 - ACCOUNT_ACCESS_REMOVAL (51): - T1531 - STEAL_WEB_SESSION_COOKIE (25): - T1539 - CREATE_OR_MODIFY_SYSTEM_PROCESS (24): - T1543 - ABUSE_ELEVATION_CONTROL_MECHANISM (34): - T1548 - UNSECURED_CREDENTIALS (13): - T1552 - MODIFY_AUTHENTICATION_PROCESS (28): - T1556 - IMPAIR_DEFENSES (31): - T1562 - DISABLE_OR_MODIFY_TOOLS (55): - T1562.001 - EXFILTRATION_OVER_WEB_SERVICE (20): - T1567 - EXFILTRATION_TO_CLOUD_STORAGE (21): - T1567.002 - DYNAMIC_RESOLUTION (12): - T1568 - LATERAL_TOOL_TRANSFER (41): - T1570 - MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE (26): - T1578 - CREATE_SNAPSHOT (54): - T1578.001 - CLOUD_INFRASTRUCTURE_DISCOVERY (53): - T1580 - OBTAIN_CAPABILITIES (43): - T1588 - ACTIVE_SCANNING (1): - T1595 - SCANNING_IP_BLOCKS (2): - T1595.001 - CONTAINER_ADMINISTRATION_COMMAND (60): - T1609 - ESCAPE_TO_HOST (61): - T1611 - CONTAINER_AND_RESOURCE_DISCOVERY (57): - T1613 - STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES (62): - T1649 - """ - TECHNIQUE_UNSPECIFIED = 0 - MASQUERADING = 49 - MATCH_LEGITIMATE_NAME_OR_LOCATION = 50 - BOOT_OR_LOGON_INITIALIZATION_SCRIPTS = 37 - STARTUP_ITEMS = 38 - NETWORK_SERVICE_DISCOVERY = 32 - PROCESS_DISCOVERY = 56 - COMMAND_AND_SCRIPTING_INTERPRETER = 6 - UNIX_SHELL = 7 - PYTHON = 59 - PERMISSION_GROUPS_DISCOVERY = 18 - CLOUD_GROUPS = 19 - APPLICATION_LAYER_PROTOCOL = 45 - DNS = 46 - SOFTWARE_DEPLOYMENT_TOOLS = 47 - VALID_ACCOUNTS = 14 - DEFAULT_ACCOUNTS = 35 - LOCAL_ACCOUNTS = 15 - CLOUD_ACCOUNTS = 16 - PROXY = 9 - EXTERNAL_PROXY = 10 - MULTI_HOP_PROXY = 11 - ACCOUNT_MANIPULATION = 22 - ADDITIONAL_CLOUD_CREDENTIALS = 40 - SSH_AUTHORIZED_KEYS = 23 - ADDITIONAL_CONTAINER_CLUSTER_ROLES = 58 - INGRESS_TOOL_TRANSFER = 3 - NATIVE_API = 4 - BRUTE_FORCE = 44 - SHARED_MODULES = 5 - ACCESS_TOKEN_MANIPULATION = 33 - TOKEN_IMPERSONATION_OR_THEFT = 39 - EXPLOIT_PUBLIC_FACING_APPLICATION = 27 - DOMAIN_POLICY_MODIFICATION = 30 - DATA_DESTRUCTION = 29 - SERVICE_STOP = 52 - INHIBIT_SYSTEM_RECOVERY = 36 - RESOURCE_HIJACKING = 8 - NETWORK_DENIAL_OF_SERVICE = 17 - CLOUD_SERVICE_DISCOVERY = 48 - STEAL_APPLICATION_ACCESS_TOKEN = 42 - ACCOUNT_ACCESS_REMOVAL = 51 - STEAL_WEB_SESSION_COOKIE = 25 - CREATE_OR_MODIFY_SYSTEM_PROCESS = 24 - ABUSE_ELEVATION_CONTROL_MECHANISM = 34 - UNSECURED_CREDENTIALS = 13 - MODIFY_AUTHENTICATION_PROCESS = 28 - IMPAIR_DEFENSES = 31 - DISABLE_OR_MODIFY_TOOLS = 55 - EXFILTRATION_OVER_WEB_SERVICE = 20 - EXFILTRATION_TO_CLOUD_STORAGE = 21 - DYNAMIC_RESOLUTION = 12 - LATERAL_TOOL_TRANSFER = 41 - MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE = 26 - CREATE_SNAPSHOT = 54 - CLOUD_INFRASTRUCTURE_DISCOVERY = 53 - OBTAIN_CAPABILITIES = 43 - ACTIVE_SCANNING = 1 - SCANNING_IP_BLOCKS = 2 - CONTAINER_ADMINISTRATION_COMMAND = 60 - ESCAPE_TO_HOST = 61 - CONTAINER_AND_RESOURCE_DISCOVERY = 57 - STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES = 62 - - primary_tactic: Tactic = proto.Field( - proto.ENUM, - number=1, - enum=Tactic, - ) - primary_techniques: MutableSequence[Technique] = proto.RepeatedField( - proto.ENUM, - number=2, - enum=Technique, - ) - additional_tactics: MutableSequence[Tactic] = proto.RepeatedField( - proto.ENUM, - number=3, - enum=Tactic, - ) - additional_techniques: MutableSequence[Technique] = proto.RepeatedField( - proto.ENUM, - number=4, - enum=Technique, - ) - version: str = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py deleted file mode 100644 index ee8a03538484..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.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 __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.securitycenter.v1', - manifest={ - 'MuteConfig', - }, -) - - -class MuteConfig(proto.Message): - r"""A mute config is a Cloud SCC resource that contains the - configuration to mute create/update events of findings. - - Attributes: - name (str): - This field will be ignored if provided on config creation. - Format - ``organizations/{organization}/muteConfigs/{mute_config}`` - ``folders/{folder}/muteConfigs/{mute_config}`` - ``projects/{project}/muteConfigs/{mute_config}`` - ``organizations/{organization}/locations/global/muteConfigs/{mute_config}`` - ``folders/{folder}/locations/global/muteConfigs/{mute_config}`` - ``projects/{project}/locations/global/muteConfigs/{mute_config}`` - display_name (str): - The human readable name to be displayed for - the mute config. - description (str): - A description of the mute config. - filter (str): - Required. An expression that defines the filter to apply - across create/update events of findings. While creating a - filter string, be mindful of the scope in which the mute - configuration is being created. E.g., If a filter contains - project = X but is created under the project = Y scope, it - might not match any findings. - - The following field and operator combinations are supported: - - - severity: ``=``, ``:`` - - category: ``=``, ``:`` - - resource.name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.folders.resource_folder: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - - finding_class: ``=``, ``:`` - - indicator.ip_addresses: ``=``, ``:`` - - indicator.domains: ``=``, ``:`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the mute - config was created. This field is set by the - server and will be ignored if provided on config - creation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The most recent time at which - the mute config was updated. This field is set - by the server and will be ignored if provided on - config creation or update. - most_recent_editor (str): - Output only. Email address of the user who - last edited the mute config. This field is set - by the server and will be ignored if provided on - config creation or update. - """ - - 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, - ) - filter: 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, - ) - most_recent_editor: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py deleted file mode 100644 index 564197159f0c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py +++ /dev/null @@ -1,72 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v1', - manifest={ - 'Notebook', - }, -) - - -class Notebook(proto.Message): - r"""Represents a Jupyter notebook IPYNB file, such as a `Colab - Enterprise - notebook `__ file, - that is associated with a finding. - - Attributes: - name (str): - The name of the notebook. - service (str): - The source notebook service, for example, - "Colab Enterprise". - last_author (str): - The user ID of the latest author to modify - the notebook. - notebook_update_time (google.protobuf.timestamp_pb2.Timestamp): - The most recent time the notebook was - updated. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - service: str = proto.Field( - proto.STRING, - number=2, - ) - last_author: str = proto.Field( - proto.STRING, - number=3, - ) - notebook_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.py deleted file mode 100644 index d26990314b74..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'NotificationConfig', - }, -) - - -class NotificationConfig(proto.Message): - r"""Cloud Security Command Center (Cloud SCC) notification - configs. - A notification config is a Cloud SCC resource that contains the - configuration to send notifications for create/update events of - findings, assets and etc. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The relative resource name of this notification config. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/notificationConfigs/notify_public_bucket", - "folders/{folder_id}/notificationConfigs/notify_public_bucket", - or - "projects/{project_id}/notificationConfigs/notify_public_bucket". - description (str): - The description of the notification config - (max of 1024 characters). - pubsub_topic (str): - The Pub/Sub topic to send notifications to. Its format is - "projects/[project_id]/topics/[topic]". - service_account (str): - Output only. The service account that needs - "pubsub.topics.publish" permission to publish to - the Pub/Sub topic. - streaming_config (google.cloud.securitycenter_v1.types.NotificationConfig.StreamingConfig): - The config for triggering streaming-based - notifications. - - This field is a member of `oneof`_ ``notify_config``. - """ - - class StreamingConfig(proto.Message): - r"""The config for streaming-based notifications, which send each - event as soon as it is detected. - - Attributes: - filter (str): - Expression that defines the filter to apply across - create/update events of assets or findings as specified by - the event type. The expression is a list of zero or more - restrictions combined via logical operators ``AND`` and - ``OR``. Parentheses are supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - """ - - filter: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - pubsub_topic: str = proto.Field( - proto.STRING, - number=3, - ) - service_account: str = proto.Field( - proto.STRING, - number=4, - ) - streaming_config: StreamingConfig = proto.Field( - proto.MESSAGE, - number=5, - oneof='notify_config', - message=StreamingConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.py deleted file mode 100644 index f979d5f7a0ec..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import resource as gcs_resource - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'NotificationMessage', - }, -) - - -class NotificationMessage(proto.Message): - r"""Cloud SCC's Notification - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - notification_config_name (str): - Name of the notification config that - generated current notification. - finding (google.cloud.securitycenter_v1.types.Finding): - If it's a Finding based notification config, - this field will be populated. - - This field is a member of `oneof`_ ``event``. - resource (google.cloud.securitycenter_v1.types.Resource): - The Cloud resource tied to this - notification's Finding. - """ - - notification_config_name: str = proto.Field( - proto.STRING, - number=1, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=2, - oneof='event', - message=gcs_finding.Finding, - ) - resource: gcs_resource.Resource = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_resource.Resource, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.py deleted file mode 100644 index ebd7ac4b0424..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.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.cloud.securitycenter.v1', - manifest={ - 'OrgPolicy', - }, -) - - -class OrgPolicy(proto.Message): - r"""Contains information about the org policies associated with - the finding. - - Attributes: - name (str): - The resource name of the org policy. Example: - "organizations/{organization_id}/policies/{constraint_name}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.py deleted file mode 100644 index 81c2816a1e66..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'OrganizationSettings', - }, -) - - -class OrganizationSettings(proto.Message): - r"""User specified settings that are attached to the Security - Command Center organization. - - Attributes: - name (str): - The relative resource name of the settings. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/organizationSettings". - enable_asset_discovery (bool): - A flag that indicates if Asset Discovery should be enabled. - If the flag is set to ``true``, then discovery of assets - will occur. If it is set to ``false``, all historical assets - will remain, but discovery of future assets will not occur. - asset_discovery_config (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig): - The configuration used for Asset Discovery - runs. - """ - - class AssetDiscoveryConfig(proto.Message): - r"""The configuration used for Asset Discovery runs. - - Attributes: - project_ids (MutableSequence[str]): - The project ids to use for filtering asset - discovery. - inclusion_mode (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): - The mode to use for filtering asset - discovery. - folder_ids (MutableSequence[str]): - The folder ids to use for filtering asset - discovery. It consists of only digits, e.g., - 756619654966. - """ - class InclusionMode(proto.Enum): - r"""The mode of inclusion when running Asset Discovery. Asset discovery - can be limited by explicitly identifying projects to be included or - excluded. If INCLUDE_ONLY is set, then only those projects within - the organization and their children are discovered during asset - discovery. If EXCLUDE is set, then projects that don't match those - projects are discovered during asset discovery. If neither are set, - then all projects within the organization are discovered during - asset discovery. - - Values: - INCLUSION_MODE_UNSPECIFIED (0): - Unspecified. Setting the mode with this value - will disable inclusion/exclusion filtering for - Asset Discovery. - INCLUDE_ONLY (1): - Asset Discovery will capture only the - resources within the projects specified. All - other resources will be ignored. - EXCLUDE (2): - Asset Discovery will ignore all resources - under the projects specified. All other - resources will be retrieved. - """ - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - project_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - inclusion_mode: 'OrganizationSettings.AssetDiscoveryConfig.InclusionMode' = proto.Field( - proto.ENUM, - number=2, - enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', - ) - folder_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - enable_asset_discovery: bool = proto.Field( - proto.BOOL, - number=2, - ) - asset_discovery_config: AssetDiscoveryConfig = proto.Field( - proto.MESSAGE, - number=3, - message=AssetDiscoveryConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py deleted file mode 100644 index 881b8df6dfa1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py +++ /dev/null @@ -1,136 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1.types import file - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Process', - 'EnvironmentVariable', - }, -) - - -class Process(proto.Message): - r"""Represents an operating system process. - - Attributes: - name (str): - The process name, as displayed in utilities like ``top`` and - ``ps``. This name can be accessed through - ``/proc/[pid]/comm`` and changed with - ``prctl(PR_SET_NAME)``. - binary (google.cloud.securitycenter_v1.types.File): - File information for the process executable. - libraries (MutableSequence[google.cloud.securitycenter_v1.types.File]): - File information for libraries loaded by the - process. - script (google.cloud.securitycenter_v1.types.File): - When the process represents the invocation of a script, - ``binary`` provides information about the interpreter, while - ``script`` provides information about the script file - provided to the interpreter. - args (MutableSequence[str]): - Process arguments as JSON encoded strings. - arguments_truncated (bool): - True if ``args`` is incomplete. - env_variables (MutableSequence[google.cloud.securitycenter_v1.types.EnvironmentVariable]): - Process environment variables. - env_variables_truncated (bool): - True if ``env_variables`` is incomplete. - pid (int): - The process ID. - parent_pid (int): - The parent process ID. - """ - - name: str = proto.Field( - proto.STRING, - number=12, - ) - binary: file.File = proto.Field( - proto.MESSAGE, - number=3, - message=file.File, - ) - libraries: MutableSequence[file.File] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=file.File, - ) - script: file.File = proto.Field( - proto.MESSAGE, - number=5, - message=file.File, - ) - args: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - arguments_truncated: bool = proto.Field( - proto.BOOL, - number=7, - ) - env_variables: MutableSequence['EnvironmentVariable'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='EnvironmentVariable', - ) - env_variables_truncated: bool = proto.Field( - proto.BOOL, - number=9, - ) - pid: int = proto.Field( - proto.INT64, - number=10, - ) - parent_pid: int = proto.Field( - proto.INT64, - number=11, - ) - - -class EnvironmentVariable(proto.Message): - r"""A name-value pair representing an environment variable used - in an operating system process. - - Attributes: - name (str): - Environment variable name as a JSON encoded - string. - val (str): - Environment variable value as a JSON encoded - string. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - val: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py deleted file mode 100644 index f66c0ab5f06d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py +++ /dev/null @@ -1,474 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1.types import folder - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'CloudProvider', - 'Resource', - 'AwsMetadata', - 'AzureMetadata', - 'ResourcePath', - }, -) - - -class CloudProvider(proto.Enum): - r"""Enumeration representing the various cloud providers a - finding's resource could reside in. - - Values: - CLOUD_PROVIDER_UNSPECIFIED (0): - The cloud provider is unspecified. - GOOGLE_CLOUD_PLATFORM (1): - The cloud provider is Google Cloud Platform. - AMAZON_WEB_SERVICES (2): - The cloud provider is Amazon Web Services. - MICROSOFT_AZURE (3): - The cloud provider is Microsoft Azure. - """ - CLOUD_PROVIDER_UNSPECIFIED = 0 - GOOGLE_CLOUD_PLATFORM = 1 - AMAZON_WEB_SERVICES = 2 - MICROSOFT_AZURE = 3 - - -class Resource(proto.Message): - r"""Information related to the Google Cloud 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): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - display_name (str): - The human readable name of the resource. - type_ (str): - The full resource type of the resource. - project (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The project ID that the resource belongs to. - parent (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (MutableSequence[google.cloud.securitycenter_v1.types.Folder]): - Output only. Contains a Folder message for - each folder in the assets ancestry. The first - folder is the deepest nested folder, and the - last folder is the folder directly under the - Organization. - cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): - Indicates which cloud provider the resource - resides in. - organization (str): - Indicates which organization or tenant in the - cloud provider the finding applies to. - service (str): - The parent service or product from which the - resource is provided, for example, GKE or SNS. - location (str): - The region or location of the service (if - applicable). - aws_metadata (google.cloud.securitycenter_v1.types.AwsMetadata): - The AWS metadata associated with the finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - azure_metadata (google.cloud.securitycenter_v1.types.AzureMetadata): - The Azure metadata associated with the - finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - resource_path (google.cloud.securitycenter_v1.types.ResourcePath): - Provides the path to the resource within the - resource hierarchy. - resource_path_string (str): - A string representation of the resource path. For Google - Cloud, it has the format of - ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` - where there can be any number of folders. For AWS, it has - the format of - ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` - where there can be any number of organizational units. For - Azure, it has the format of - ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` - where there can be any number of management groups. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=8, - ) - type_: str = proto.Field( - proto.STRING, - number=6, - ) - project: str = proto.Field( - proto.STRING, - number=2, - ) - project_display_name: str = proto.Field( - proto.STRING, - number=3, - ) - parent: str = proto.Field( - proto.STRING, - number=4, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=5, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=folder.Folder, - ) - cloud_provider: 'CloudProvider' = proto.Field( - proto.ENUM, - number=9, - enum='CloudProvider', - ) - organization: str = proto.Field( - proto.STRING, - number=10, - ) - service: str = proto.Field( - proto.STRING, - number=11, - ) - location: str = proto.Field( - proto.STRING, - number=12, - ) - aws_metadata: 'AwsMetadata' = proto.Field( - proto.MESSAGE, - number=16, - oneof='cloud_provider_metadata', - message='AwsMetadata', - ) - azure_metadata: 'AzureMetadata' = proto.Field( - proto.MESSAGE, - number=17, - oneof='cloud_provider_metadata', - message='AzureMetadata', - ) - resource_path: 'ResourcePath' = proto.Field( - proto.MESSAGE, - number=18, - message='ResourcePath', - ) - resource_path_string: str = proto.Field( - proto.STRING, - number=19, - ) - - -class AwsMetadata(proto.Message): - r"""AWS metadata associated with the resource, only applicable if - the finding's cloud provider is Amazon Web Services. - - Attributes: - organization (google.cloud.securitycenter_v1.types.AwsMetadata.AwsOrganization): - The AWS organization associated with the - resource. - organizational_units (MutableSequence[google.cloud.securitycenter_v1.types.AwsMetadata.AwsOrganizationalUnit]): - A list of AWS organizational units associated - with the resource, ordered from lowest level - (closest to the account) to highest level. - account (google.cloud.securitycenter_v1.types.AwsMetadata.AwsAccount): - The AWS account associated with the resource. - """ - - class AwsOrganization(proto.Message): - r"""An organization is a collection of accounts that are - centrally managed together using consolidated billing, organized - hierarchically with organizational units (OUs), and controlled - with policies. - - Attributes: - id (str): - The unique identifier (ID) for the - organization. The regex pattern for an - organization ID string requires "o-" followed by - from 10 to 32 lowercase letters or digits. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - - class AwsOrganizationalUnit(proto.Message): - r"""An Organizational Unit (OU) is a container of AWS accounts - within a root of an organization. Policies that are attached to - an OU apply to all accounts contained in that OU and in any - child OUs. - - Attributes: - id (str): - The unique identifier (ID) associated with - this OU. The regex pattern for an organizational - unit ID string requires "ou-" followed by from 4 - to 32 lowercase letters or digits (the ID of the - root that contains the OU). This string is - followed by a second "-" dash and from 8 to 32 - additional lowercase letters or digits. For - example, "ou-ab12-cd34ef56". - name (str): - The friendly name of the OU. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - - class AwsAccount(proto.Message): - r"""An AWS account that is a member of an organization. - - Attributes: - id (str): - The unique identifier (ID) of the account, - containing exactly 12 digits. - name (str): - The friendly name of this account. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - - organization: AwsOrganization = proto.Field( - proto.MESSAGE, - number=2, - message=AwsOrganization, - ) - organizational_units: MutableSequence[AwsOrganizationalUnit] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=AwsOrganizationalUnit, - ) - account: AwsAccount = proto.Field( - proto.MESSAGE, - number=4, - message=AwsAccount, - ) - - -class AzureMetadata(proto.Message): - r"""Azure metadata associated with the resource, only applicable - if the finding's cloud provider is Microsoft Azure. - - Attributes: - management_groups (MutableSequence[google.cloud.securitycenter_v1.types.AzureMetadata.AzureManagementGroup]): - A list of Azure management groups associated - with the resource, ordered from lowest level - (closest to the subscription) to highest level. - subscription (google.cloud.securitycenter_v1.types.AzureMetadata.AzureSubscription): - The Azure subscription associated with the - resource. - resource_group (google.cloud.securitycenter_v1.types.AzureMetadata.AzureResourceGroup): - The Azure resource group associated with the - resource. - """ - - class AzureManagementGroup(proto.Message): - r"""Represents an Azure management group. - - Attributes: - id (str): - The UUID of the Azure management group, for example, - ``20000000-0001-0000-0000-000000000000``. - display_name (str): - The display name of the Azure management - group. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - class AzureSubscription(proto.Message): - r"""Represents an Azure subscription. - - Attributes: - id (str): - The UUID of the Azure subscription, for example, - ``291bba3f-e0a5-47bc-a099-3bdcb2a50a05``. - display_name (str): - The display name of the Azure subscription. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - class AzureResourceGroup(proto.Message): - r"""Represents an Azure resource group. - - Attributes: - name (str): - The name of the Azure resource group. This is - not a UUID. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - management_groups: MutableSequence[AzureManagementGroup] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=AzureManagementGroup, - ) - subscription: AzureSubscription = proto.Field( - proto.MESSAGE, - number=5, - message=AzureSubscription, - ) - resource_group: AzureResourceGroup = proto.Field( - proto.MESSAGE, - number=6, - message=AzureResourceGroup, - ) - - -class ResourcePath(proto.Message): - r"""Represents the path of resources leading up to the resource - this finding is about. - - Attributes: - nodes (MutableSequence[google.cloud.securitycenter_v1.types.ResourcePath.ResourcePathNode]): - The list of nodes that make the up resource - path, ordered from lowest level to highest - level. - """ - class ResourcePathNodeType(proto.Enum): - r"""The type of resource the node represents. - - Values: - RESOURCE_PATH_NODE_TYPE_UNSPECIFIED (0): - Node type is unspecified. - GCP_ORGANIZATION (1): - The node represents a Google Cloud - organization. - GCP_FOLDER (2): - The node represents a Google Cloud folder. - GCP_PROJECT (3): - The node represents a Google Cloud project. - AWS_ORGANIZATION (4): - The node represents an AWS organization. - AWS_ORGANIZATIONAL_UNIT (5): - The node represents an AWS organizational - unit. - AWS_ACCOUNT (6): - The node represents an AWS account. - AZURE_MANAGEMENT_GROUP (7): - The node represents an Azure management - group. - AZURE_SUBSCRIPTION (8): - The node represents an Azure subscription. - AZURE_RESOURCE_GROUP (9): - The node represents an Azure resource group. - """ - RESOURCE_PATH_NODE_TYPE_UNSPECIFIED = 0 - GCP_ORGANIZATION = 1 - GCP_FOLDER = 2 - GCP_PROJECT = 3 - AWS_ORGANIZATION = 4 - AWS_ORGANIZATIONAL_UNIT = 5 - AWS_ACCOUNT = 6 - AZURE_MANAGEMENT_GROUP = 7 - AZURE_SUBSCRIPTION = 8 - AZURE_RESOURCE_GROUP = 9 - - class ResourcePathNode(proto.Message): - r"""A node within the resource path. Each node represents a - resource within the resource hierarchy. - - Attributes: - node_type (google.cloud.securitycenter_v1.types.ResourcePath.ResourcePathNodeType): - The type of resource this node represents. - id (str): - The ID of the resource this node represents. - display_name (str): - The display name of the resource this node - represents. - """ - - node_type: 'ResourcePath.ResourcePathNodeType' = proto.Field( - proto.ENUM, - number=1, - enum='ResourcePath.ResourcePathNodeType', - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - - nodes: MutableSequence[ResourcePathNode] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ResourcePathNode, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py deleted file mode 100644 index f88354103169..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py +++ /dev/null @@ -1,189 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1.types import resource -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'ResourceValue', - 'ResourceValueConfig', - }, -) - - -class ResourceValue(proto.Enum): - r"""Value enum to map to a resource - - Values: - RESOURCE_VALUE_UNSPECIFIED (0): - Unspecific value - HIGH (1): - High resource value - MEDIUM (2): - Medium resource value - LOW (3): - Low resource value - NONE (4): - No resource value, e.g. ignore these - resources - """ - RESOURCE_VALUE_UNSPECIFIED = 0 - HIGH = 1 - MEDIUM = 2 - LOW = 3 - NONE = 4 - - -class ResourceValueConfig(proto.Message): - r"""A resource value configuration (RVC) is a mapping - configuration of user's resources to resource values. Used in - Attack path simulations. - - Attributes: - name (str): - Name for the resource value configuration - resource_value (google.cloud.securitycenter_v1.types.ResourceValue): - Required. Resource value level this - expression represents - tag_values (MutableSequence[str]): - Required. Tag values combined with ``AND`` to check against. - Values in the form "tagValues/123" Example: - ``[ "tagValues/123", "tagValues/456", "tagValues/789" ]`` - https://cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing - resource_type (str): - Apply resource_value only to resources that match - resource_type. resource_type will be checked with ``AND`` of - other resources. For example, - "storage.googleapis.com/Bucket" with resource_value "HIGH" - will apply "HIGH" value only to - "storage.googleapis.com/Bucket" resources. - scope (str): - Project or folder to scope this configuration to. For - example, "project/456" would apply this configuration only - to resources in "project/456" scope will be checked with - ``AND`` of other resources. - resource_labels_selector (MutableMapping[str, str]): - List of resource labels to search for, evaluated with - ``AND``. For example, - ``"resource_labels_selector": {"key": "value", "env": "prod"}`` - will match resources with labels "key": "value" ``AND`` - "env": "prod" - https://cloud.google.com/resource-manager/docs/creating-managing-labels - description (str): - Description of the resource value - configuration. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp this resource value - configuration was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp this resource value - configuration was last updated. - cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): - Cloud provider this configuration applies to - sensitive_data_protection_mapping (google.cloud.securitycenter_v1.types.ResourceValueConfig.SensitiveDataProtectionMapping): - A mapping of the sensitivity on Sensitive Data Protection - finding to resource values. This mapping can only be used in - combination with a resource_type that is related to - BigQuery, e.g. "bigquery.googleapis.com/Dataset". - """ - - class SensitiveDataProtectionMapping(proto.Message): - r"""Resource value mapping for Sensitive Data Protection findings. If - any of these mappings have a resource value that is not unspecified, - the resource_value field will be ignored when reading this - configuration. - - Attributes: - high_sensitivity_mapping (google.cloud.securitycenter_v1.types.ResourceValue): - Resource value mapping for high-sensitivity - Sensitive Data Protection findings - medium_sensitivity_mapping (google.cloud.securitycenter_v1.types.ResourceValue): - Resource value mapping for medium-sensitivity - Sensitive Data Protection findings - """ - - high_sensitivity_mapping: 'ResourceValue' = proto.Field( - proto.ENUM, - number=1, - enum='ResourceValue', - ) - medium_sensitivity_mapping: 'ResourceValue' = proto.Field( - proto.ENUM, - number=2, - enum='ResourceValue', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - resource_value: 'ResourceValue' = proto.Field( - proto.ENUM, - number=2, - enum='ResourceValue', - ) - tag_values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - resource_type: str = proto.Field( - proto.STRING, - number=4, - ) - scope: str = proto.Field( - proto.STRING, - number=5, - ) - resource_labels_selector: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=6, - ) - description: str = proto.Field( - proto.STRING, - number=7, - ) - 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, - ) - cloud_provider: resource.CloudProvider = proto.Field( - proto.ENUM, - number=10, - enum=resource.CloudProvider, - ) - sensitive_data_protection_mapping: SensitiveDataProtectionMapping = proto.Field( - proto.MESSAGE, - number=11, - message=SensitiveDataProtectionMapping, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py deleted file mode 100644 index e6ccc16862c3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.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 - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'RunAssetDiscoveryResponse', - }, -) - - -class RunAssetDiscoveryResponse(proto.Message): - r"""Response of asset discovery run - - Attributes: - state (google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse.State): - The state of an asset discovery run. - duration (google.protobuf.duration_pb2.Duration): - The duration between asset discovery run - start and end - """ - class State(proto.Enum): - r"""The state of an asset discovery run. - - Values: - STATE_UNSPECIFIED (0): - Asset discovery run state was unspecified. - COMPLETED (1): - Asset discovery run completed successfully. - SUPERSEDED (2): - Asset discovery run was cancelled with tasks - still pending, as another run for the same - organization was started with a higher priority. - TERMINATED (3): - Asset discovery run was killed and - terminated. - """ - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py deleted file mode 100644 index bb412145607c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py +++ /dev/null @@ -1,173 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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 expr_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'CustomConfig', - }, -) - - -class CustomConfig(proto.Message): - r"""Defines the properties in a custom module configuration for - Security Health Analytics. Use the custom module configuration - to create custom detectors that generate custom findings for - resources that you specify. - - Attributes: - predicate (google.type.expr_pb2.Expr): - The CEL expression to evaluate to produce - findings. When the expression evaluates to true - against a resource, a finding is generated. - custom_output (google.cloud.securitycenter_v1.types.CustomConfig.CustomOutputSpec): - Custom output properties. - resource_selector (google.cloud.securitycenter_v1.types.CustomConfig.ResourceSelector): - The resource types that the custom module - operates on. Each custom module can specify up - to 5 resource types. - severity (google.cloud.securitycenter_v1.types.CustomConfig.Severity): - The severity to assign to findings generated - by the module. - description (str): - Text that describes the vulnerability or - misconfiguration that the custom module detects. - This explanation is returned with each finding - instance to help investigators understand the - detected issue. The text must be enclosed in - quotation marks. - recommendation (str): - An explanation of the recommended steps that security teams - can take to resolve the detected issue. This explanation is - returned with each finding generated by this module in the - ``nextSteps`` property of the finding JSON. - """ - class Severity(proto.Enum): - r"""Defines the valid value options for the severity of a - finding. - - Values: - SEVERITY_UNSPECIFIED (0): - Unspecified severity. - 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 - - class CustomOutputSpec(proto.Message): - r"""A set of optional name-value pairs that define custom source - properties to return with each finding that is generated by the - custom module. The custom source properties that are defined here - are included in the finding JSON under ``sourceProperties``. - - Attributes: - properties (MutableSequence[google.cloud.securitycenter_v1.types.CustomConfig.CustomOutputSpec.Property]): - A list of custom output properties to add to - the finding. - """ - - class Property(proto.Message): - r"""An individual name-value pair that defines a custom source - property. - - Attributes: - name (str): - Name of the property for the custom output. - value_expression (google.type.expr_pb2.Expr): - The CEL expression for the custom output. A - resource property can be specified to return the - value of the property or a text string enclosed - in quotation marks. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - value_expression: expr_pb2.Expr = proto.Field( - proto.MESSAGE, - number=2, - message=expr_pb2.Expr, - ) - - properties: MutableSequence['CustomConfig.CustomOutputSpec.Property'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='CustomConfig.CustomOutputSpec.Property', - ) - - class ResourceSelector(proto.Message): - r"""Resource for selecting resource type. - - Attributes: - resource_types (MutableSequence[str]): - The resource types to run the detector on. - """ - - resource_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - predicate: expr_pb2.Expr = proto.Field( - proto.MESSAGE, - number=1, - message=expr_pb2.Expr, - ) - custom_output: CustomOutputSpec = proto.Field( - proto.MESSAGE, - number=2, - message=CustomOutputSpec, - ) - resource_selector: ResourceSelector = proto.Field( - proto.MESSAGE, - number=3, - message=ResourceSelector, - ) - severity: Severity = proto.Field( - proto.ENUM, - number=4, - enum=Severity, - ) - description: str = proto.Field( - proto.STRING, - number=5, - ) - recommendation: str = proto.Field( - proto.STRING, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.py deleted file mode 100644 index 654cd7d75826..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'SecurityHealthAnalyticsCustomModule', - }, -) - - -class SecurityHealthAnalyticsCustomModule(proto.Message): - r"""Represents an instance of a Security Health Analytics custom - module, including its full module name, display name, enablement - state, and last updated time. You can create a custom module at - the organization, folder, or project level. Custom modules that - you create at the organization or folder level are inherited by - the child folders and projects. - - Attributes: - name (str): - Immutable. The resource name of the custom - module. Its format is - "organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}", - or - "folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}", - or - "projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}" - - The id {customModule} is server-generated and is - not user settable. It will be a numeric id - containing 1-20 digits. - display_name (str): - The display name of the Security Health - Analytics custom module. This display name - becomes the finding category for all findings - that are returned by this custom module. The - display name must be between 1 and 128 - characters, start with a lowercase letter, and - contain alphanumeric characters or underscores - only. - enablement_state (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule.EnablementState): - The enablement state of the custom module. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the custom - module was last updated. - last_editor (str): - Output only. The editor that last updated the - custom module. - ancestor_module (str): - Output only. If empty, indicates that the custom module was - created in the organization, folder, or project in which you - are viewing the custom module. Otherwise, - ``ancestor_module`` specifies the organization or folder - from which the custom module is inherited. - custom_config (google.cloud.securitycenter_v1.types.CustomConfig): - The user specified custom configuration for - the module. - """ - class EnablementState(proto.Enum): - r"""Possible enablement states of a custom module. - - Values: - ENABLEMENT_STATE_UNSPECIFIED (0): - Unspecified enablement state. - ENABLED (1): - The module is enabled at the given CRM - resource. - DISABLED (2): - The module is disabled at the given CRM - resource. - INHERITED (3): - State is inherited from an ancestor module. - The module will either be effectively ENABLED or - DISABLED based on its closest non-inherited - ancestor module in the CRM hierarchy. - """ - ENABLEMENT_STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - INHERITED = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - enablement_state: EnablementState = proto.Field( - proto.ENUM, - number=4, - enum=EnablementState, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - last_editor: str = proto.Field( - proto.STRING, - number=6, - ) - ancestor_module: str = proto.Field( - proto.STRING, - number=7, - ) - custom_config: security_health_analytics_custom_config.CustomConfig = proto.Field( - proto.MESSAGE, - number=8, - message=security_health_analytics_custom_config.CustomConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.py deleted file mode 100644 index 4c141c1aa108..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'SecurityMarks', - }, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (MutableMapping[str, str]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - canonical_name (str): - The canonical name of the marks. Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "folders/{folder_id}/assets/{asset_id}/securityMarks" - "projects/{project_number}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" - "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - marks: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.py deleted file mode 100644 index c929af3ef59a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'SecurityPosture', - }, -) - - -class SecurityPosture(proto.Message): - r"""Represents a posture that is deployed on Google Cloud by the - Security Command Center Posture Management service. A posture - contains one or more policy sets. A policy set is a group of - policies that enforce a set of security rules on Google Cloud. - - Attributes: - name (str): - Name of the posture, for example, ``CIS-Posture``. - revision_id (str): - The version of the posture, for example, ``c7cfa2a8``. - posture_deployment_resource (str): - The project, folder, or organization on which the posture is - deployed, for example, ``projects/{project_number}``. - posture_deployment (str): - The name of the posture deployment, for example, - ``organizations/{org_id}/posturedeployments/{posture_deployment_id}``. - changed_policy (str): - The name of the updated policy, for example, - ``projects/{project_id}/policies/{constraint_name}``. - policy_set (str): - The name of the updated policyset, for example, - ``cis-policyset``. - policy (str): - The ID of the updated policy, for example, - ``compute-policy-1``. - policy_drift_details (MutableSequence[google.cloud.securitycenter_v1.types.SecurityPosture.PolicyDriftDetails]): - The details about a change in an updated - policy that violates the deployed posture. - """ - - class PolicyDriftDetails(proto.Message): - r"""The policy field that violates the deployed posture and its - expected and detected values. - - Attributes: - field (str): - The name of the updated field, for example - constraint.implementation.policy_rules[0].enforce - expected_value (str): - The value of this field that was configured in a posture, - for example, ``true`` or - ``allowed_values={"projects/29831892"}``. - detected_value (str): - The detected value that violates the deployed posture, for - example, ``false`` or - ``allowed_values={"projects/22831892"}``. - """ - - field: str = proto.Field( - proto.STRING, - number=1, - ) - expected_value: str = proto.Field( - proto.STRING, - number=2, - ) - detected_value: str = proto.Field( - proto.STRING, - number=3, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - ) - posture_deployment_resource: str = proto.Field( - proto.STRING, - number=3, - ) - posture_deployment: str = proto.Field( - proto.STRING, - number=4, - ) - changed_policy: str = proto.Field( - proto.STRING, - number=5, - ) - policy_set: str = proto.Field( - proto.STRING, - number=6, - ) - policy: str = proto.Field( - proto.STRING, - number=7, - ) - policy_drift_details: MutableSequence[PolicyDriftDetails] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=PolicyDriftDetails, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py deleted file mode 100644 index 385bd4c37c53..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py +++ /dev/null @@ -1,3494 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1.types import asset as gcs_asset -from google.cloud.securitycenter_v1.types import attack_path -from google.cloud.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import folder -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import resource as gcs_resource -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import valued_resource -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'BulkMuteFindingsRequest', - 'BulkMuteFindingsResponse', - 'CreateFindingRequest', - 'CreateMuteConfigRequest', - 'CreateResourceValueConfigRequest', - 'BatchCreateResourceValueConfigsRequest', - 'BatchCreateResourceValueConfigsResponse', - 'DeleteResourceValueConfigRequest', - 'GetResourceValueConfigRequest', - 'ListResourceValueConfigsRequest', - 'ListResourceValueConfigsResponse', - 'UpdateResourceValueConfigRequest', - 'CreateNotificationConfigRequest', - 'CreateSecurityHealthAnalyticsCustomModuleRequest', - 'CreateSourceRequest', - 'DeleteMuteConfigRequest', - 'DeleteNotificationConfigRequest', - 'DeleteSecurityHealthAnalyticsCustomModuleRequest', - 'GetBigQueryExportRequest', - 'GetMuteConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', - 'GetSecurityHealthAnalyticsCustomModuleRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', - 'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', - 'ListValuedResourcesRequest', - 'ListValuedResourcesResponse', - 'ListAttackPathsRequest', - 'ListAttackPathsResponse', - 'GetSimulationRequest', - 'GetValuedResourceRequest', - 'ListMuteConfigsRequest', - 'ListMuteConfigsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', - 'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', - 'ListSecurityHealthAnalyticsCustomModulesRequest', - 'ListSecurityHealthAnalyticsCustomModulesResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'SetFindingStateRequest', - 'SetMuteRequest', - 'RunAssetDiscoveryRequest', - 'SimulateSecurityHealthAnalyticsCustomModuleRequest', - 'SimulateSecurityHealthAnalyticsCustomModuleResponse', - 'UpdateExternalSystemRequest', - 'UpdateFindingRequest', - 'UpdateMuteConfigRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityHealthAnalyticsCustomModuleRequest', - 'UpdateSourceRequest', - 'UpdateSecurityMarksRequest', - 'CreateBigQueryExportRequest', - 'UpdateBigQueryExportRequest', - 'ListBigQueryExportsRequest', - 'ListBigQueryExportsResponse', - 'DeleteBigQueryExportRequest', - 'CreateEventThreatDetectionCustomModuleRequest', - 'ValidateEventThreatDetectionCustomModuleRequest', - 'ValidateEventThreatDetectionCustomModuleResponse', - 'DeleteEventThreatDetectionCustomModuleRequest', - 'GetEventThreatDetectionCustomModuleRequest', - 'ListDescendantEventThreatDetectionCustomModulesRequest', - 'ListDescendantEventThreatDetectionCustomModulesResponse', - 'ListEventThreatDetectionCustomModulesRequest', - 'ListEventThreatDetectionCustomModulesResponse', - 'UpdateEventThreatDetectionCustomModuleRequest', - 'GetEffectiveEventThreatDetectionCustomModuleRequest', - 'ListEffectiveEventThreatDetectionCustomModulesRequest', - 'ListEffectiveEventThreatDetectionCustomModulesResponse', - }, -) - - -class BulkMuteFindingsRequest(proto.Message): - r"""Request message for bulk findings update. - - Note: - - 1. If multiple bulk update requests match the same resource, the - order in which they get executed is not defined. - 2. Once a bulk operation is started, there is no way to stop it. - - Attributes: - parent (str): - Required. The parent, at which bulk action needs to be - applied. Its format is ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - filter (str): - Expression that identifies findings that should be updated. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - mute_annotation (str): - This can be a mute configuration name or any - identifier for mute/unmute of findings based on - the filter. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - mute_annotation: str = proto.Field( - proto.STRING, - number=3, - ) - - -class BulkMuteFindingsResponse(proto.Message): - r"""The response to a BulkMute request. Contains the LRO - information. - - """ - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - - Attributes: - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - ``organizations/[organization_id]/sources/[source_id]``. - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - alphanumeric and less than or equal to 32 - characters and greater than 0 characters in - length. - finding (google.cloud.securitycenter_v1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - finding_id: str = proto.Field( - proto.STRING, - number=2, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_finding.Finding, - ) - - -class CreateMuteConfigRequest(proto.Message): - r"""Request message for creating a mute config. - - Attributes: - parent (str): - Required. Resource name of the new mute configs's parent. - Its format is ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - mute_config (google.cloud.securitycenter_v1.types.MuteConfig): - Required. The mute config being created. - mute_config_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must consist - of only lowercase letters, numbers, and hyphens, - must start with a letter, must end with either a - letter or a number, and must be 63 characters or - less. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - mute_config: gcs_mute_config.MuteConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_mute_config.MuteConfig, - ) - mute_config_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class CreateResourceValueConfigRequest(proto.Message): - r"""Request message to create single resource value config - - Attributes: - parent (str): - Required. Resource name of the new - ResourceValueConfig's parent. - resource_value_config (google.cloud.securitycenter_v1.types.ResourceValueConfig): - Required. The resource value config being - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_resource_value_config.ResourceValueConfig, - ) - - -class BatchCreateResourceValueConfigsRequest(proto.Message): - r"""Request message to create multiple resource value configs - - Attributes: - parent (str): - Required. Resource name of the new - ResourceValueConfig's parent. The parent field - in the CreateResourceValueConfigRequest messages - must either be empty or match this field. - requests (MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]): - Required. The resource value configs to be - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - requests: MutableSequence['CreateResourceValueConfigRequest'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='CreateResourceValueConfigRequest', - ) - - -class BatchCreateResourceValueConfigsResponse(proto.Message): - r"""Response message for BatchCreateResourceValueConfigs - - Attributes: - resource_value_configs (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfig]): - The resource value configs created - """ - - resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_resource_value_config.ResourceValueConfig, - ) - - -class DeleteResourceValueConfigRequest(proto.Message): - r"""Request message to delete resource value config - - Attributes: - name (str): - Required. Name of the ResourceValueConfig to - delete - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetResourceValueConfigRequest(proto.Message): - r"""Request message to get resource value config - - Attributes: - name (str): - Required. Name of the resource value config to retrieve. Its - format is - ``organizations/{organization}/resourceValueConfigs/{config_id}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListResourceValueConfigsRequest(proto.Message): - r"""Request message to list resource value configs of a parent - - Attributes: - parent (str): - Required. The parent, which owns the collection of resource - value configs. Its format is - ``organizations/[organization_id]`` - page_size (int): - The number of results to return. The service - may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - A page token, received from a previous - ``ListResourceValueConfigs`` call. Provide this to retrieve - the subsequent page. - - When paginating, all other parameters provided to - ``ListResourceValueConfigs`` must match the call that - provided the page token. - - page_size can be specified, and the new page_size 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, - ) - - -class ListResourceValueConfigsResponse(proto.Message): - r"""Response message to list resource value configs - - Attributes: - resource_value_configs (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfig]): - The resource value configs from the specified - parent. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is empty, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_resource_value_config.ResourceValueConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateResourceValueConfigRequest(proto.Message): - r"""Request message to update resource value config - - Attributes: - resource_value_config (google.cloud.securitycenter_v1.types.ResourceValueConfig): - Required. The resource value config being - updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - If empty all mutable fields will be updated. - """ - - resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_resource_value_config.ResourceValueConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class CreateNotificationConfigRequest(proto.Message): - r"""Request message for creating a notification config. - - Attributes: - parent (str): - Required. Resource name of the new notification config's - parent. Its format is ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - config_id (str): - Required. - Unique identifier provided by the client within - the parent scope. It must be between 1 and 128 - characters and contain alphanumeric characters, - underscores, or hyphens only. - notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): - Required. The notification config being - created. The name and the service account will - be ignored as they are both output only fields - on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - config_id: str = proto.Field( - proto.STRING, - number=2, - ) - notification_config: gcs_notification_config.NotificationConfig = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_notification_config.NotificationConfig, - ) - - -class CreateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Request message for creating Security Health Analytics custom - modules. - - Attributes: - parent (str): - Required. Resource name of the new custom module's parent. - Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): - Required. SecurityHealthAnalytics custom - module to create. The provided name is ignored - and reset with provided parent information and - server-generated ID. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - security_health_analytics_custom_module: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - ) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be ``organizations/[organization_id]``. - source (google.cloud.securitycenter_v1.types.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_source.Source, - ) - - -class DeleteMuteConfigRequest(proto.Message): - r"""Request message for deleting a mute config. - - Attributes: - name (str): - Required. Name of the mute config to delete. Its format is - ``organizations/{organization}/muteConfigs/{config_id}``, - ``folders/{folder}/muteConfigs/{config_id}``, - ``projects/{project}/muteConfigs/{config_id}``, - ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, - ``folders/{folder}/locations/global/muteConfigs/{config_id}``, - or - ``projects/{project}/locations/global/muteConfigs/{config_id}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteNotificationConfigRequest(proto.Message): - r"""Request message for deleting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to delete. Its - format is - ``organizations/[organization_id]/notificationConfigs/[config_id]``, - ``folders/[folder_id]/notificationConfigs/[config_id]``, or - ``projects/[project_id]/notificationConfigs/[config_id]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Request message for deleting Security Health Analytics custom - modules. - - Attributes: - name (str): - Required. Name of the custom module to delete. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetBigQueryExportRequest(proto.Message): - r"""Request message for retrieving a BigQuery export. - - Attributes: - name (str): - Required. Name of the BigQuery export to retrieve. Its - format is - ``organizations/{organization}/bigQueryExports/{export_id}``, - ``folders/{folder}/bigQueryExports/{export_id}``, or - ``projects/{project}/bigQueryExports/{export_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetMuteConfigRequest(proto.Message): - r"""Request message for retrieving a mute config. - - Attributes: - name (str): - Required. Name of the mute config to retrieve. Its format is - ``organizations/{organization}/muteConfigs/{config_id}``, - ``folders/{folder}/muteConfigs/{config_id}``, - ``projects/{project}/muteConfigs/{config_id}``, - ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, - ``folders/{folder}/locations/global/muteConfigs/{config_id}``, - or - ``projects/{project}/locations/global/muteConfigs/{config_id}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetNotificationConfigRequest(proto.Message): - r"""Request message for getting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to get. Its format - is - ``organizations/[organization_id]/notificationConfigs/[config_id]``, - ``folders/[folder_id]/notificationConfigs/[config_id]``, or - ``projects/[project_id]/notificationConfigs/[config_id]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetOrganizationSettingsRequest(proto.Message): - r"""Request message for getting organization settings. - - Attributes: - name (str): - Required. Name of the organization to get organization - settings for. Its format is - ``organizations/[organization_id]/organizationSettings``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Request message for getting effective Security Health - Analytics custom modules. - - Attributes: - name (str): - Required. Name of the effective custom module to get. Its - format is - ``organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Request message for getting Security Health Analytics custom - modules. - - Attributes: - name (str): - Required. Name of the custom module to get. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is ``organizations/[organization_id]/source/[source_id]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GroupAssetsRequest(proto.Message): - r"""Request message for grouping by assets. - - Attributes: - parent (str): - Required. The name of the parent to group the assets by. Its - format is ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, - ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is - not set: - - - security_center_properties.resource_project - - security_center_properties.resource_project_display_name - - security_center_properties.resource_type - - security_center_properties.resource_parent - - security_center_properties.resource_parent_display_name - - The following fields are supported when compare_duration is - set: - - - security_center_properties.resource_type - - security_center_properties.resource_project_display_name - - security_center_properties.resource_parent_display_name - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the GroupResult's - "state_change" property is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at - reference_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and reference_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupAssetsResponse``; - indicates that this is a continuation of a prior - ``GroupAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - page_size: int = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupAssetsResponse(proto.Message): - r"""Response message for grouping by assets. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - - Attributes: - parent (str): - Required. Name of the source to groupBy. Its format is - ``organizations/[organization_id]/sources/[source_id]``, - ``folders/[folder_id]/sources/[source_id]``, or - ``projects/[project_id]/sources/[source_id]``. To groupBy - across all sources provide a source_id of ``-``. For - example: - ``organizations/{organization_id}/sources/-, folders/{folder_id}/sources/-``, - or ``projects/{project_id}/sources/-`` - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - severity: ``=``, ``:`` - - - workflow_state: ``=``, ``:`` - - - security_marks.marks: ``=``, ``:`` - - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based - on a property existing: - ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - - - resource: - - - resource.name: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping (including ``state_change``). The string value - should follow SQL syntax: comma separated list of fields. - For example: "parent,resource_name". - - The following fields are supported when compare_duration is - set: - - - state_change - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the GroupResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - page_size: int = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message=struct_pb2.Value, - ) - count: int = proto.Field( - proto.INT64, - number=2, - ) - - -class ListDescendantSecurityHealthAnalyticsCustomModulesRequest(proto.Message): - r"""Request message for listing descendant Security Health - Analytics custom modules. - - Attributes: - parent (str): - Required. Name of parent to list descendant custom modules. - Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - page_token (str): - The value returned by the last call - indicating a continuation - """ - - 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 ListDescendantSecurityHealthAnalyticsCustomModulesResponse(proto.Message): - r"""Response message for listing descendant Security Health - Analytics custom modules. - - Attributes: - security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule]): - Custom modules belonging to the requested - parent and its descendants. - next_page_token (str): - If not empty, indicates that there may be - more custom modules to be returned. - """ - - @property - def raw_page(self): - return self - - security_health_analytics_custom_modules: MutableSequence[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListValuedResourcesRequest(proto.Message): - r"""Request message for listing the valued resources for a given - simulation. - - Attributes: - parent (str): - Required. Name of parent to list valued resources. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - filter (str): - The filter expression that filters the valued resources in - the response. Supported fields: - - - ``resource_value`` supports = - - ``resource_type`` supports = - page_token (str): - The value returned by the last - ``ListValuedResourcesResponse``; indicates that this is a - continuation of a prior ``ListValuedResources`` call, and - that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - order_by (str): - Optional. The fields by which to order the valued resources - response. - - Supported fields: - - - ``exposed_score`` - - - ``resource_value`` - - - ``resource_type`` - - - ``resource`` - - - ``display_name`` - - Values should be a comma separated list of fields. For - example: ``exposed_score,resource_value``. - - The default sorting order is descending. To specify - ascending or descending order for a field, append a ``ASC`` - or a ``DESC`` suffix, respectively; for example: - ``exposed_score DESC``. - """ - - 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, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListValuedResourcesResponse(proto.Message): - r"""Response message for listing the valued resources for a given - simulation. - - Attributes: - valued_resources (MutableSequence[google.cloud.securitycenter_v1.types.ValuedResource]): - The valued resources that the attack path - simulation identified. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The estimated total number of results - matching the query. - """ - - @property - def raw_page(self): - return self - - valued_resources: MutableSequence[valued_resource.ValuedResource] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=valued_resource.ValuedResource, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class ListAttackPathsRequest(proto.Message): - r"""Request message for listing the attack paths for a given - simulation or valued resource. - - Attributes: - parent (str): - Required. Name of parent to list attack paths. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - filter (str): - The filter expression that filters the attack path in the - response. Supported fields: - - - ``valued_resources`` supports = - page_token (str): - The value returned by the last ``ListAttackPathsResponse``; - indicates that this is a continuation of a prior - ``ListAttackPaths`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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 ListAttackPathsResponse(proto.Message): - r"""Response message for listing the attack paths for a given - simulation or valued resource. - - Attributes: - attack_paths (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath]): - The attack paths that the attack path - simulation identified. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - attack_paths: MutableSequence[attack_path.AttackPath] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=attack_path.AttackPath, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetSimulationRequest(proto.Message): - r"""Request message for getting simulation. - Simulation name can include "latest" to retrieve the latest - simulation For example, "organizations/123/simulations/latest" - - Attributes: - name (str): - Required. The organization name or simulation name of this - simulation - - Valid format: - ``organizations/{organization}/simulations/latest`` - ``organizations/{organization}/simulations/{simulation}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetValuedResourceRequest(proto.Message): - r"""Request message for getting a valued resource. - - Attributes: - name (str): - Required. The name of this valued resource - - Valid format: - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListMuteConfigsRequest(proto.Message): - r"""Request message for listing mute configs at a given scope - e.g. organization, folder or project. - - Attributes: - parent (str): - Required. The parent, which owns the collection of mute - configs. Its format is ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - page_size (int): - The maximum number of configs to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - A page token, received from a previous ``ListMuteConfigs`` - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListMuteConfigs`` 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 ListMuteConfigsResponse(proto.Message): - r"""Response message for listing mute configs. - - Attributes: - mute_configs (MutableSequence[google.cloud.securitycenter_v1.types.MuteConfig]): - The mute configs from the specified parent. - 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 - - mute_configs: MutableSequence[gcs_mute_config.MuteConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_mute_config.MuteConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListNotificationConfigsRequest(proto.Message): - r"""Request message for listing notification configs. - - Attributes: - parent (str): - Required. The name of the parent in which to list the - notification configurations. Its format is - "organizations/[organization_id]", "folders/[folder_id]", or - "projects/[project_id]". - page_token (str): - The value returned by the last - ``ListNotificationConfigsResponse``; indicates that this is - a continuation of a prior ``ListNotificationConfigs`` call, - and that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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 ListNotificationConfigsResponse(proto.Message): - r"""Response message for listing notification configs. - - Attributes: - notification_configs (MutableSequence[google.cloud.securitycenter_v1.types.NotificationConfig]): - Notification configs belonging to the - requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - notification_configs: MutableSequence[gcs_notification_config.NotificationConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(proto.Message): - r"""Request message for listing effective Security Health - Analytics custom modules. - - Attributes: - parent (str): - Required. Name of parent to list effective custom modules. - Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - page_token (str): - The value returned by the last call - indicating a continuation - """ - - 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 ListEffectiveSecurityHealthAnalyticsCustomModulesResponse(proto.Message): - r"""Response message for listing effective Security Health - Analytics custom modules. - - Attributes: - effective_security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule]): - Effective custom modules belonging to the - requested parent. - next_page_token (str): - If not empty, indicates that there may be - more effective custom modules to be returned. - """ - - @property - def raw_page(self): - return self - - effective_security_health_analytics_custom_modules: MutableSequence[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListSecurityHealthAnalyticsCustomModulesRequest(proto.Message): - r"""Request message for listing Security Health Analytics custom - modules. - - Attributes: - parent (str): - Required. Name of parent to list custom modules. Its format - is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - page_token (str): - The value returned by the last call - indicating a continuation - """ - - 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 ListSecurityHealthAnalyticsCustomModulesResponse(proto.Message): - r"""Response message for listing Security Health Analytics custom - modules. - - Attributes: - security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule]): - Custom modules belonging to the requested - parent. - next_page_token (str): - If not empty, indicates that there may be - more custom modules to be returned. - """ - - @property - def raw_page(self): - return self - - security_health_analytics_custom_modules: MutableSequence[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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=7, - ) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - - Attributes: - sources (MutableSequence[google.cloud.securitycenter_v1.types.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListAssetsRequest(proto.Message): - r"""Request message for listing assets. - - Attributes: - parent (str): - Required. The name of the parent resource that contains the - assets. The value that you can specify on parent depends on - the method in which you specify parent. You can specify one - of the following values: - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following are the allowed field and operator - combinations: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, - ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,resource_properties.a_property". - Redundant space characters in the syntax are insignificant. - "name desc,resource_properties.a_property" and " name desc , - resource_properties.a_property " are equivalent. - - The following fields are supported: name update_time - resource_properties security_marks.marks - security_center_properties.resource_name - security_center_properties.resource_display_name - security_center_properties.resource_parent - security_center_properties.resource_parent_display_name - security_center_properties.resource_project - security_center_properties.resource_project_display_name - security_center_properties.resource_type - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListAssetsResult's - "state_change" attribute is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at read_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at read_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the ListAssetsResult - fields to be listed in the response. - An empty field mask will list all fields. - page_token (str): - The value returned by the last ``ListAssetsResponse``; - indicates that this is a continuation of a prior - ``ListAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=8, - ) - page_size: int = proto.Field( - proto.INT32, - number=9, - ) - - -class ListAssetsResponse(proto.Message): - r"""Response message for listing assets. - - Attributes: - list_assets_results (MutableSequence[google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult]): - Assets matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of assets matching the - query. - """ - - class ListAssetsResult(proto.Message): - r"""Result containing the Asset and its State. - - Attributes: - asset (google.cloud.securitycenter_v1.types.Asset): - Asset matching the search request. - state_change (google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult.StateChange): - State change of the asset between the points - in time. - """ - class StateChange(proto.Enum): - r"""The change in state of the asset. - - When querying across two points in time this describes the change - between the two points: ADDED, REMOVED, or ACTIVE. If there was no - compare_duration supplied in the request the state change will be: - UNUSED - - Values: - UNUSED (0): - State change is unused, this is the canonical - default for this enum. - ADDED (1): - Asset was added between the points in time. - REMOVED (2): - Asset was removed between the points in time. - ACTIVE (3): - Asset was present at both point(s) in time. - """ - UNUSED = 0 - ADDED = 1 - REMOVED = 2 - ACTIVE = 3 - - asset: gcs_asset.Asset = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_asset.Asset, - ) - state_change: 'ListAssetsResponse.ListAssetsResult.StateChange' = proto.Field( - proto.ENUM, - number=2, - enum='ListAssetsResponse.ListAssetsResult.StateChange', - ) - - @property - def raw_page(self): - return self - - list_assets_results: MutableSequence[ListAssetsResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListAssetsResult, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - - Attributes: - parent (str): - Required. Name of the source the findings belong to. Its - format is - ``organizations/[organization_id]/sources/[source_id]``, - ``folders/[folder_id]/sources/[source_id]``, or - ``projects/[project_id]/sources/[source_id]``. To list - across all sources provide a source_id of ``-``. For - example: ``organizations/{organization_id}/sources/-``, - ``folders/{folder_id}/sources/-`` or - ``projects/{projects_id}/sources/-`` - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - severity: ``=``, ``:`` - - - workflow_state: ``=``, ``:`` - - - security_marks.marks: ``=``, ``:`` - - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based - on a property existing: - ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - - - resource: - - - resource.name: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - - resource.folders.resource_folder: ``=``, ``:`` - - resource.display_name: ``=``, ``:`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,source_properties.a_property". Redundant - space characters in the syntax are insignificant. "name - desc,source_properties.a_property" and " name desc , - source_properties.a_property " are equivalent. - - The following fields are supported: name parent state - category resource_name event_time source_properties - security_marks.marks - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListFindingsResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added in any state during - the compare_duration period of time that precedes the - read_time. This is the time between (read_time - - compare_duration) and read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the Finding fields to - be listed in the response. An empty field mask - will list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=8, - ) - page_size: int = proto.Field( - proto.INT32, - number=9, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - - Attributes: - list_findings_results (MutableSequence[google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult]): - Findings matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - class ListFindingsResult(proto.Message): - r"""Result containing the Finding and its StateChange. - - Attributes: - finding (google.cloud.securitycenter_v1.types.Finding): - Finding matching the search request. - state_change (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.StateChange): - State change of the finding between the - points in time. - resource (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.Resource): - Output only. Resource that is associated with - this finding. - """ - class StateChange(proto.Enum): - r"""The change in state of the finding. - - When querying across two points in time this describes the change in - the finding between the two points: CHANGED, UNCHANGED, ADDED, or - REMOVED. Findings can not be deleted, so REMOVED implies that the - finding at timestamp does not match the filter specified, but it did - at timestamp - compare_duration. If there was no compare_duration - supplied in the request the state change will be: UNUSED - - Values: - UNUSED (0): - State change is unused, this is the canonical - default for this enum. - CHANGED (1): - The finding has changed state in some way - between the points in time and existed at both - points. - UNCHANGED (2): - The finding has not changed state between the - points in time and existed at both points. - ADDED (3): - The finding was created between the points in - time. - REMOVED (4): - The finding at timestamp does not match the filter - specified, but it did at timestamp - compare_duration. - """ - UNUSED = 0 - CHANGED = 1 - UNCHANGED = 2 - ADDED = 3 - REMOVED = 4 - - class Resource(proto.Message): - r"""Information related to the Google Cloud resource that is - associated with this finding. - - 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): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - display_name (str): - The human readable name of the resource. - type_ (str): - The full resource type of the resource. - project_name (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The project ID that the resource belongs to. - parent_name (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (MutableSequence[google.cloud.securitycenter_v1.types.Folder]): - Contains a Folder message for each folder in - the assets ancestry. The first folder is the - deepest nested folder, and the last folder is - the folder directly under the Organization. - cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): - Indicates which cloud provider the finding is - from. - organization (str): - Indicates which organization / tenant the - finding is for. - service (str): - The service or resource provider associated - with the resource. - location (str): - The region or location of the service (if - applicable). - aws_metadata (google.cloud.securitycenter_v1.types.AwsMetadata): - The AWS metadata associated with the finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - azure_metadata (google.cloud.securitycenter_v1.types.AzureMetadata): - The Azure metadata associated with the - finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - resource_path (google.cloud.securitycenter_v1.types.ResourcePath): - Provides the path to the resource within the - resource hierarchy. - resource_path_string (str): - A string representation of the resource path. For Google - Cloud, it has the format of - ``org/{organization_id}/folder/{folder_id}/folder/{folder_id}/project/{project_id}`` - where there can be any number of folders. For AWS, it has - the format of - ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` - where there can be any number of organizational units. For - Azure, it has the format of - ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` - where there can be any number of management groups. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=8, - ) - type_: str = proto.Field( - proto.STRING, - number=6, - ) - project_name: str = proto.Field( - proto.STRING, - number=2, - ) - project_display_name: str = proto.Field( - proto.STRING, - number=3, - ) - parent_name: str = proto.Field( - proto.STRING, - number=4, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=5, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=folder.Folder, - ) - cloud_provider: gcs_resource.CloudProvider = proto.Field( - proto.ENUM, - number=9, - enum=gcs_resource.CloudProvider, - ) - organization: str = proto.Field( - proto.STRING, - number=10, - ) - service: str = proto.Field( - proto.STRING, - number=11, - ) - location: str = proto.Field( - proto.STRING, - number=12, - ) - aws_metadata: gcs_resource.AwsMetadata = proto.Field( - proto.MESSAGE, - number=16, - oneof='cloud_provider_metadata', - message=gcs_resource.AwsMetadata, - ) - azure_metadata: gcs_resource.AzureMetadata = proto.Field( - proto.MESSAGE, - number=17, - oneof='cloud_provider_metadata', - message=gcs_resource.AzureMetadata, - ) - resource_path: gcs_resource.ResourcePath = proto.Field( - proto.MESSAGE, - number=18, - message=gcs_resource.ResourcePath, - ) - resource_path_string: str = proto.Field( - proto.STRING, - number=19, - ) - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - state_change: 'ListFindingsResponse.ListFindingsResult.StateChange' = proto.Field( - proto.ENUM, - number=2, - enum='ListFindingsResponse.ListFindingsResult.StateChange', - ) - resource: 'ListFindingsResponse.ListFindingsResult.Resource' = proto.Field( - proto.MESSAGE, - number=3, - message='ListFindingsResponse.ListFindingsResult.Resource', - ) - - @property - def raw_page(self): - return self - - list_findings_results: MutableSequence[ListFindingsResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListFindingsResult, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - - Attributes: - name (str): - Required. The `relative resource - name `__ - of the finding. Example: - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. - state (google.cloud.securitycenter_v1.types.Finding.State): - Required. The desired State of the finding. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the updated state - takes effect. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: gcs_finding.Finding.State = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.State, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class SetMuteRequest(proto.Message): - r"""Request message for updating a finding's mute status. - - Attributes: - name (str): - Required. The `relative resource - name `__ - of the finding. Example: - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. - mute (google.cloud.securitycenter_v1.types.Finding.Mute): - Required. The desired state of the Mute. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - mute: gcs_finding.Finding.Mute = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.Mute, - ) - - -class RunAssetDiscoveryRequest(proto.Message): - r"""Request message for running asset discovery for an - organization. - - Attributes: - parent (str): - Required. Name of the organization to run asset discovery - for. Its format is ``organizations/[organization_id]``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class SimulateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Request message to simulate a CustomConfig against a given - test resource. Maximum size of the request is 4 MB by default. - - Attributes: - parent (str): - Required. The relative resource name of the organization, - project, or folder. For more information about relative - resource names, see `Relative Resource - Name `__ - Example: ``organizations/{organization_id}`` - custom_config (google.cloud.securitycenter_v1.types.CustomConfig): - Required. The custom configuration that you - need to test. - resource (google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource): - Required. Resource data to simulate custom - module against. - """ - - class SimulatedResource(proto.Message): - r"""Manually constructed resource name. If the custom module evaluates - against only the resource data, you can omit the ``iam_policy_data`` - field. If it evaluates only the ``iam_policy_data`` field, you can - omit the resource data. - - Attributes: - resource_type (str): - Required. The type of the resource, for example, - ``compute.googleapis.com/Disk``. - resource_data (google.protobuf.struct_pb2.Struct): - Optional. A representation of the Google - Cloud resource. Should match the Google Cloud - resource JSON format. - iam_policy_data (google.iam.v1.policy_pb2.Policy): - Optional. A representation of the IAM policy. - """ - - resource_type: str = proto.Field( - proto.STRING, - number=1, - ) - resource_data: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - iam_policy_data: policy_pb2.Policy = proto.Field( - proto.MESSAGE, - number=3, - message=policy_pb2.Policy, - ) - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - custom_config: security_health_analytics_custom_config.CustomConfig = proto.Field( - proto.MESSAGE, - number=2, - message=security_health_analytics_custom_config.CustomConfig, - ) - resource: SimulatedResource = proto.Field( - proto.MESSAGE, - number=3, - message=SimulatedResource, - ) - - -class SimulateSecurityHealthAnalyticsCustomModuleResponse(proto.Message): - r"""Response message for simulating a - ``SecurityHealthAnalyticsCustomModule`` against a given resource. - - Attributes: - result (google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse.SimulatedResult): - Result for test case in the corresponding - request. - """ - - class SimulatedResult(proto.Message): - r"""Possible test 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: - finding (google.cloud.securitycenter_v1.types.Finding): - Finding that would be published for the test - case, if a violation is detected. - - This field is a member of `oneof`_ ``result``. - no_violation (google.protobuf.empty_pb2.Empty): - Indicates that the test case does not trigger - any violation. - - This field is a member of `oneof`_ ``result``. - error (google.rpc.status_pb2.Status): - Error encountered during the test. - - This field is a member of `oneof`_ ``result``. - """ - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - oneof='result', - message=gcs_finding.Finding, - ) - no_violation: empty_pb2.Empty = proto.Field( - proto.MESSAGE, - number=2, - oneof='result', - message=empty_pb2.Empty, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - oneof='result', - message=status_pb2.Status, - ) - - result: SimulatedResult = proto.Field( - proto.MESSAGE, - number=1, - message=SimulatedResult, - ) - - -class UpdateExternalSystemRequest(proto.Message): - r"""Request message for updating a ExternalSystem resource. - - Attributes: - external_system (google.cloud.securitycenter_v1.types.ExternalSystem): - Required. The external system resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - external system resource. - If empty all mutable fields will be updated. - """ - - external_system: gcs_external_system.ExternalSystem = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_external_system.ExternalSystem, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - - Attributes: - finding (google.cloud.securitycenter_v1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must be alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing source_properties. - Individual source_properties can be added/updated by using - "source_properties." in the field mask. - """ - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateMuteConfigRequest(proto.Message): - r"""Request message for updating a mute config. - - Attributes: - mute_config (google.cloud.securitycenter_v1.types.MuteConfig): - Required. The mute config being updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - If empty all mutable fields will be updated. - """ - - mute_config: gcs_mute_config.MuteConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_mute_config.MuteConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateNotificationConfigRequest(proto.Message): - r"""Request message for updating a notification config. - - Attributes: - notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): - Required. The notification config to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - notification config. - If empty all mutable fields will be updated. - """ - - notification_config: gcs_notification_config.NotificationConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateOrganizationSettingsRequest(proto.Message): - r"""Request message for updating an organization's settings. - - Attributes: - organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): - Required. The organization settings resource - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - settings resource. - If empty all mutable fields will be updated. - """ - - organization_settings: gcs_organization_settings.OrganizationSettings = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_organization_settings.OrganizationSettings, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Request message for updating Security Health Analytics custom - modules. - - Attributes: - security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): - Required. The SecurityHealthAnalytics custom - module to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. The only fields that can - be updated are ``enablement_state`` and ``custom_config``. - If empty or set to the wildcard value ``*``, both - ``enablement_state`` and ``custom_config`` are updated. - """ - - security_health_analytics_custom_module: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - - Attributes: - source (google.cloud.securitycenter_v1.types.Source): - Required. The source resource to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the source - resource. - If empty all mutable fields will be updated. - """ - - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - - Attributes: - security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): - Required. The security marks resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If empty - or set to "marks", all marks will be replaced. Individual - marks can be updated using "marks.". - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the updated SecurityMarks - take effect. If not set uses current server - time. Updates will be applied to the - SecurityMarks that are active immediately - preceding this time. Must be earlier or equal to - the server time. - """ - - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_security_marks.SecurityMarks, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class CreateBigQueryExportRequest(proto.Message): - r"""Request message for creating a BigQuery export. - - Attributes: - parent (str): - Required. The name of the parent resource of the new - BigQuery export. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): - Required. The BigQuery export being created. - big_query_export_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must consist - of only lowercase letters, numbers, and hyphens, - must start with a letter, must end with either a - letter or a number, and must be 63 characters or - less. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - big_query_export: bigquery_export.BigQueryExport = proto.Field( - proto.MESSAGE, - number=2, - message=bigquery_export.BigQueryExport, - ) - big_query_export_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateBigQueryExportRequest(proto.Message): - r"""Request message for updating a BigQuery export. - - Attributes: - big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): - Required. The BigQuery export being updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - If empty all mutable fields will be updated. - """ - - big_query_export: bigquery_export.BigQueryExport = proto.Field( - proto.MESSAGE, - number=1, - message=bigquery_export.BigQueryExport, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ListBigQueryExportsRequest(proto.Message): - r"""Request message for listing BigQuery exports at a given scope - e.g. organization, folder or project. - - Attributes: - parent (str): - Required. The parent, which owns the collection of BigQuery - exports. Its format is ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - page_size (int): - The maximum number of configs to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - A page token, received from a previous - ``ListBigQueryExports`` call. Provide this to retrieve the - subsequent page. When paginating, all other parameters - provided to ``ListBigQueryExports`` 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 ListBigQueryExportsResponse(proto.Message): - r"""Response message for listing BigQuery exports. - - Attributes: - big_query_exports (MutableSequence[google.cloud.securitycenter_v1.types.BigQueryExport]): - The BigQuery exports from the specified - parent. - 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 - - big_query_exports: MutableSequence[bigquery_export.BigQueryExport] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=bigquery_export.BigQueryExport, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteBigQueryExportRequest(proto.Message): - r"""Request message for deleting a BigQuery export. - - Attributes: - name (str): - Required. The name of the BigQuery export to delete. Its - format is - ``organizations/{organization}/bigQueryExports/{export_id}``, - ``folders/{folder}/bigQueryExports/{export_id}``, or - ``projects/{project}/bigQueryExports/{export_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Request to create an Event Threat Detection custom module. - - Attributes: - parent (str): - Required. The new custom module's parent. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): - Required. The module to create. The - event_threat_detection_custom_module.name will be ignored - and server generated. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - event_threat_detection_custom_module: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, - ) - - -class ValidateEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Request to validate an Event Threat Detection custom module. - - Attributes: - parent (str): - Required. Resource name of the parent to validate the Custom - Module under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - raw_text (str): - Required. The raw text of the module's - contents. Used to generate error messages. - type_ (str): - Required. The type of the module (e.g. CONFIGURABLE_BAD_IP). - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - raw_text: str = proto.Field( - proto.STRING, - number=2, - ) - type_: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ValidateEventThreatDetectionCustomModuleResponse(proto.Message): - r"""Response to validating an Event Threat Detection custom - module. - - Attributes: - errors (google.cloud.securitycenter_v1.types.CustomModuleValidationErrors): - A list of errors returned by the validator. - If the list is empty, there were no errors. - """ - - errors: event_threat_detection_custom_module_validation_errors.CustomModuleValidationErrors = proto.Field( - proto.MESSAGE, - number=2, - message=event_threat_detection_custom_module_validation_errors.CustomModuleValidationErrors, - ) - - -class DeleteEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Request to delete an Event Threat Detection custom module. - - Attributes: - name (str): - Required. Name of the custom module to delete. - - Its format is: - - - "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}". - - "folders/{folder}/eventThreatDetectionSettings/customModules/{module}". - - "projects/{project}/eventThreatDetectionSettings/customModules/{module}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Request to get an Event Threat Detection custom module. - - Attributes: - name (str): - Required. Name of the custom module to get. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDescendantEventThreatDetectionCustomModulesRequest(proto.Message): - r"""Request to list current and descendant resident Event Threat - Detection custom modules. - - Attributes: - parent (str): - Required. Name of the parent to list custom modules under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - page_token (str): - A page token, received from a previous - ``ListDescendantEventThreatDetectionCustomModules`` call. - Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListDescendantEventThreatDetectionCustomModules`` must - match the call that provided the page token. - page_size (int): - The maximum number of modules to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - """ - - 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 ListDescendantEventThreatDetectionCustomModulesResponse(proto.Message): - r"""Response for listing current and descendant resident - Event Threat Detection custom modules. - - Attributes: - event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule]): - Custom modules belonging to the requested - parent. - 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 - - event_threat_detection_custom_modules: MutableSequence[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListEventThreatDetectionCustomModulesRequest(proto.Message): - r"""Request to list Event Threat Detection custom modules. - - Attributes: - parent (str): - Required. Name of the parent to list custom modules under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - page_token (str): - A page token, received from a previous - ``ListEventThreatDetectionCustomModules`` call. Provide this - to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListEventThreatDetectionCustomModules`` must match the - call that provided the page token. - page_size (int): - The maximum number of modules to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - """ - - 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 ListEventThreatDetectionCustomModulesResponse(proto.Message): - r"""Response for listing Event Threat Detection custom modules. - - Attributes: - event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule]): - Custom modules belonging to the requested - parent. - 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 - - event_threat_detection_custom_modules: MutableSequence[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Request to update an Event Threat Detection custom module. - - Attributes: - event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): - Required. The module being updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - If empty all mutable fields will be updated. - """ - - event_threat_detection_custom_module: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetEffectiveEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Request to get an EffectiveEventThreatDetectionCustomModule. - - Attributes: - name (str): - Required. The resource name of the effective Event Threat - Detection custom module. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListEffectiveEventThreatDetectionCustomModulesRequest(proto.Message): - r"""Request to list effective Event Threat Detection custom - modules. - - Attributes: - parent (str): - Required. Name of the parent to list custom modules for. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - page_token (str): - A page token, received from a previous - ``ListEffectiveEventThreatDetectionCustomModules`` call. - Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListEffectiveEventThreatDetectionCustomModules`` must - match the call that provided the page token. - page_size (int): - The maximum number of modules to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - """ - - 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 ListEffectiveEventThreatDetectionCustomModulesResponse(proto.Message): - r"""Response for listing - EffectiveEventThreatDetectionCustomModules. - - Attributes: - effective_event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule]): - Effective custom modules belonging to the - requested parent. - 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 - - effective_event_threat_detection_custom_modules: MutableSequence[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py deleted file mode 100644 index 941b7452d7e0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py +++ /dev/null @@ -1,73 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1.types import resource -from google.cloud.securitycenter_v1.types import valued_resource -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Simulation', - }, -) - - -class Simulation(proto.Message): - r"""Attack path simulation - - Attributes: - name (str): - Full resource name of the Simulation: - ``organizations/123/simulations/456`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time simulation was created - resource_value_configs_metadata (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfigMetadata]): - Resource value configurations' metadata used - in this simulation. Maximum of 100. - cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): - Indicates which cloud provider was used in - this simulation. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - resource_value_configs_metadata: MutableSequence[valued_resource.ResourceValueConfigMetadata] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=valued_resource.ResourceValueConfigMetadata, - ) - cloud_provider: resource.CloudProvider = proto.Field( - proto.ENUM, - number=4, - enum=resource.CloudProvider, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.py deleted file mode 100644 index e1c53a7c05a9..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Source', - }, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, and other tools. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and outdated or - insecure libraries.". - canonical_name (str): - The canonical name of the finding source. It's either - "organizations/{organization_id}/sources/{source_id}", - "folders/{folder_id}/sources/{source_id}", or - "projects/{project_number}/sources/{source_id}", depending - on the closest CRM ancestor of the resource associated with - the finding. - """ - - 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, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=14, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.py deleted file mode 100644 index 77f790f8d5f6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'ToxicCombination', - }, -) - - -class ToxicCombination(proto.Message): - r"""Contains details about a group of security issues that, when - the issues occur together, represent a greater risk than when - the issues occur independently. A group of such issues is - referred to as a toxic combination. - - Attributes: - attack_exposure_score (float): - The `Attack exposure - score `__ - of this toxic combination. The score is a measure of how - much this toxic combination exposes one or more high-value - resources to potential attack. - related_findings (MutableSequence[str]): - List of resource names of findings associated with this - toxic combination. For example, - ``organizations/123/sources/456/findings/789``. - """ - - attack_exposure_score: float = proto.Field( - proto.DOUBLE, - number=1, - ) - related_findings: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.py deleted file mode 100644 index 5d48f6fabfa1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'ValuedResource', - 'ResourceValueConfigMetadata', - }, -) - - -class ValuedResource(proto.Message): - r"""A resource that is determined to have value to a user's - system - - Attributes: - name (str): - Valued resource name, for example, e.g.: - ``organizations/123/simulations/456/valuedResources/789`` - resource (str): - The `full resource - name `__ - of the valued resource. - resource_type (str): - The `resource - type `__ - of the valued resource. - display_name (str): - Human-readable name of the valued resource. - resource_value (google.cloud.securitycenter_v1.types.ValuedResource.ResourceValue): - How valuable this resource is. - exposed_score (float): - Exposed score for this valued resource. A - value of 0 means no exposure was detected - exposure. - resource_value_configs_used (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfigMetadata]): - List of resource value configurations' - metadata used to determine the value of this - resource. Maximum of 100. - """ - class ResourceValue(proto.Enum): - r"""How valuable the resource is. - - Values: - RESOURCE_VALUE_UNSPECIFIED (0): - The resource value isn't specified. - RESOURCE_VALUE_LOW (1): - This is a low-value resource. - RESOURCE_VALUE_MEDIUM (2): - This is a medium-value resource. - RESOURCE_VALUE_HIGH (3): - This is a high-value resource. - """ - RESOURCE_VALUE_UNSPECIFIED = 0 - RESOURCE_VALUE_LOW = 1 - RESOURCE_VALUE_MEDIUM = 2 - RESOURCE_VALUE_HIGH = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - resource: str = proto.Field( - proto.STRING, - number=2, - ) - resource_type: str = proto.Field( - proto.STRING, - number=3, - ) - display_name: str = proto.Field( - proto.STRING, - number=4, - ) - resource_value: ResourceValue = proto.Field( - proto.ENUM, - number=5, - enum=ResourceValue, - ) - exposed_score: float = proto.Field( - proto.DOUBLE, - number=6, - ) - resource_value_configs_used: MutableSequence['ResourceValueConfigMetadata'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='ResourceValueConfigMetadata', - ) - - -class ResourceValueConfigMetadata(proto.Message): - r"""Metadata about a ResourceValueConfig. For example, id and - name. - - Attributes: - name (str): - Resource value config name - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py deleted file mode 100644 index 5dbae9a7832c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py +++ /dev/null @@ -1,538 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.securitycenter.v1', - manifest={ - 'Vulnerability', - 'Cve', - 'Reference', - 'Cvssv3', - 'Package', - 'SecurityBulletin', - }, -) - - -class Vulnerability(proto.Message): - r"""Refers to common vulnerability fields e.g. cve, cvss, cwe - etc. - - Attributes: - cve (google.cloud.securitycenter_v1.types.Cve): - CVE stands for Common Vulnerabilities and - Exposures (https://cve.mitre.org/about/) - offending_package (google.cloud.securitycenter_v1.types.Package): - The offending package is relevant to the - finding. - fixed_package (google.cloud.securitycenter_v1.types.Package): - The fixed package is relevant to the finding. - security_bulletin (google.cloud.securitycenter_v1.types.SecurityBulletin): - The security bulletin is relevant to this - finding. - """ - - cve: 'Cve' = proto.Field( - proto.MESSAGE, - number=1, - message='Cve', - ) - offending_package: 'Package' = proto.Field( - proto.MESSAGE, - number=2, - message='Package', - ) - fixed_package: 'Package' = proto.Field( - proto.MESSAGE, - number=3, - message='Package', - ) - security_bulletin: 'SecurityBulletin' = proto.Field( - proto.MESSAGE, - number=4, - message='SecurityBulletin', - ) - - -class Cve(proto.Message): - r"""CVE stands for Common Vulnerabilities and Exposures. Information - from the `CVE - record `__ that - describes this vulnerability. - - Attributes: - id (str): - The unique identifier for the vulnerability. - e.g. CVE-2021-34527 - references (MutableSequence[google.cloud.securitycenter_v1.types.Reference]): - Additional information about the CVE. - e.g. - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527 - cvssv3 (google.cloud.securitycenter_v1.types.Cvssv3): - Describe Common Vulnerability Scoring System - specified at - https://www.first.org/cvss/v3.1/specification-document - upstream_fix_available (bool): - Whether upstream fix is available for the - CVE. - impact (google.cloud.securitycenter_v1.types.Cve.RiskRating): - The potential impact of the vulnerability if - it was to be exploited. - exploitation_activity (google.cloud.securitycenter_v1.types.Cve.ExploitationActivity): - The exploitation activity of the - vulnerability in the wild. - observed_in_the_wild (bool): - Whether or not the vulnerability has been - observed in the wild. - zero_day (bool): - Whether or not the vulnerability was zero day - when the finding was published. - """ - class RiskRating(proto.Enum): - r"""The possible values of impact of the vulnerability if it was - to be exploited. - - Values: - RISK_RATING_UNSPECIFIED (0): - Invalid or empty value. - LOW (1): - Exploitation would have little to no security - impact. - MEDIUM (2): - Exploitation would enable attackers to - perform activities, or could allow attackers to - have a direct impact, but would require - additional steps. - HIGH (3): - Exploitation would enable attackers to have a - notable direct impact without needing to - overcome any major mitigating factors. - CRITICAL (4): - Exploitation would fundamentally undermine - the security of affected systems, enable actors - to perform significant attacks with minimal - effort, with little to no mitigating factors to - overcome. - """ - RISK_RATING_UNSPECIFIED = 0 - LOW = 1 - MEDIUM = 2 - HIGH = 3 - CRITICAL = 4 - - class ExploitationActivity(proto.Enum): - r"""The possible values of exploitation activity of the - vulnerability in the wild. - - Values: - EXPLOITATION_ACTIVITY_UNSPECIFIED (0): - Invalid or empty value. - WIDE (1): - Exploitation has been reported or confirmed - to widely occur. - CONFIRMED (2): - Limited reported or confirmed exploitation - activities. - AVAILABLE (3): - Exploit is publicly available. - ANTICIPATED (4): - No known exploitation activity, but has a - high potential for exploitation. - NO_KNOWN (5): - No known exploitation activity. - """ - EXPLOITATION_ACTIVITY_UNSPECIFIED = 0 - WIDE = 1 - CONFIRMED = 2 - AVAILABLE = 3 - ANTICIPATED = 4 - NO_KNOWN = 5 - - id: str = proto.Field( - proto.STRING, - number=1, - ) - references: MutableSequence['Reference'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Reference', - ) - cvssv3: 'Cvssv3' = proto.Field( - proto.MESSAGE, - number=3, - message='Cvssv3', - ) - upstream_fix_available: bool = proto.Field( - proto.BOOL, - number=4, - ) - impact: RiskRating = proto.Field( - proto.ENUM, - number=5, - enum=RiskRating, - ) - exploitation_activity: ExploitationActivity = proto.Field( - proto.ENUM, - number=6, - enum=ExploitationActivity, - ) - observed_in_the_wild: bool = proto.Field( - proto.BOOL, - number=7, - ) - zero_day: bool = proto.Field( - proto.BOOL, - number=8, - ) - - -class Reference(proto.Message): - r"""Additional Links - - Attributes: - source (str): - Source of the reference e.g. NVD - uri (str): - Uri for the mentioned source e.g. - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527. - """ - - source: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Cvssv3(proto.Message): - r"""Common Vulnerability Scoring System version 3. - - Attributes: - base_score (float): - The base score is a function of the base - metric scores. - attack_vector (google.cloud.securitycenter_v1.types.Cvssv3.AttackVector): - Base Metrics - Represents the intrinsic characteristics of a - vulnerability that are constant over time and - across user environments. This metric reflects - the context by which vulnerability exploitation - is possible. - attack_complexity (google.cloud.securitycenter_v1.types.Cvssv3.AttackComplexity): - This metric describes the conditions beyond - the attacker's control that must exist in order - to exploit the vulnerability. - privileges_required (google.cloud.securitycenter_v1.types.Cvssv3.PrivilegesRequired): - This metric describes the level of privileges - an attacker must possess before successfully - exploiting the vulnerability. - user_interaction (google.cloud.securitycenter_v1.types.Cvssv3.UserInteraction): - This metric captures the requirement for a - human user, other than the attacker, to - participate in the successful compromise of the - vulnerable component. - scope (google.cloud.securitycenter_v1.types.Cvssv3.Scope): - The Scope metric captures whether a - vulnerability in one vulnerable component - impacts resources in components beyond its - security scope. - confidentiality_impact (google.cloud.securitycenter_v1.types.Cvssv3.Impact): - This metric measures the impact to the - confidentiality of the information resources - managed by a software component due to a - successfully exploited vulnerability. - integrity_impact (google.cloud.securitycenter_v1.types.Cvssv3.Impact): - This metric measures the impact to integrity - of a successfully exploited vulnerability. - availability_impact (google.cloud.securitycenter_v1.types.Cvssv3.Impact): - This metric measures the impact to the - availability of the impacted component resulting - from a successfully exploited vulnerability. - """ - class AttackVector(proto.Enum): - r"""This metric reflects the context by which vulnerability - exploitation is possible. - - Values: - ATTACK_VECTOR_UNSPECIFIED (0): - Invalid value. - ATTACK_VECTOR_NETWORK (1): - The vulnerable component is bound to the - network stack and the set of possible attackers - extends beyond the other options listed below, - up to and including the entire Internet. - ATTACK_VECTOR_ADJACENT (2): - The vulnerable component is bound to the - network stack, but the attack is limited at the - protocol level to a logically adjacent topology. - ATTACK_VECTOR_LOCAL (3): - The vulnerable component is not bound to the - network stack and the attacker's path is via - read/write/execute capabilities. - ATTACK_VECTOR_PHYSICAL (4): - The attack requires the attacker to - physically touch or manipulate the vulnerable - component. - """ - ATTACK_VECTOR_UNSPECIFIED = 0 - ATTACK_VECTOR_NETWORK = 1 - ATTACK_VECTOR_ADJACENT = 2 - ATTACK_VECTOR_LOCAL = 3 - ATTACK_VECTOR_PHYSICAL = 4 - - class AttackComplexity(proto.Enum): - r"""This metric describes the conditions beyond the attacker's - control that must exist in order to exploit the vulnerability. - - Values: - ATTACK_COMPLEXITY_UNSPECIFIED (0): - Invalid value. - ATTACK_COMPLEXITY_LOW (1): - Specialized access conditions or extenuating - circumstances do not exist. An attacker can - expect repeatable success when attacking the - vulnerable component. - ATTACK_COMPLEXITY_HIGH (2): - A successful attack depends on conditions - beyond the attacker's control. That is, a - successful attack cannot be accomplished at - will, but requires the attacker to invest in - some measurable amount of effort in preparation - or execution against the vulnerable component - before a successful attack can be expected. - """ - ATTACK_COMPLEXITY_UNSPECIFIED = 0 - ATTACK_COMPLEXITY_LOW = 1 - ATTACK_COMPLEXITY_HIGH = 2 - - class PrivilegesRequired(proto.Enum): - r"""This metric describes the level of privileges an attacker - must possess before successfully exploiting the vulnerability. - - Values: - PRIVILEGES_REQUIRED_UNSPECIFIED (0): - Invalid value. - PRIVILEGES_REQUIRED_NONE (1): - The attacker is unauthorized prior to attack, - and therefore does not require any access to - settings or files of the vulnerable system to - carry out an attack. - PRIVILEGES_REQUIRED_LOW (2): - The attacker requires privileges that provide - basic user capabilities that could normally - affect only settings and files owned by a user. - Alternatively, an attacker with Low privileges - has the ability to access only non-sensitive - resources. - PRIVILEGES_REQUIRED_HIGH (3): - The attacker requires privileges that provide - significant (e.g., administrative) control over - the vulnerable component allowing access to - component-wide settings and files. - """ - PRIVILEGES_REQUIRED_UNSPECIFIED = 0 - PRIVILEGES_REQUIRED_NONE = 1 - PRIVILEGES_REQUIRED_LOW = 2 - PRIVILEGES_REQUIRED_HIGH = 3 - - class UserInteraction(proto.Enum): - r"""This metric captures the requirement for a human user, other - than the attacker, to participate in the successful compromise - of the vulnerable component. - - Values: - USER_INTERACTION_UNSPECIFIED (0): - Invalid value. - USER_INTERACTION_NONE (1): - The vulnerable system can be exploited - without interaction from any user. - USER_INTERACTION_REQUIRED (2): - Successful exploitation of this vulnerability - requires a user to take some action before the - vulnerability can be exploited. - """ - USER_INTERACTION_UNSPECIFIED = 0 - USER_INTERACTION_NONE = 1 - USER_INTERACTION_REQUIRED = 2 - - class Scope(proto.Enum): - r"""The Scope metric captures whether a vulnerability in one - vulnerable component impacts resources in components beyond its - security scope. - - Values: - SCOPE_UNSPECIFIED (0): - Invalid value. - SCOPE_UNCHANGED (1): - An exploited vulnerability can only affect - resources managed by the same security - authority. - SCOPE_CHANGED (2): - An exploited vulnerability can affect - resources beyond the security scope managed by - the security authority of the vulnerable - component. - """ - SCOPE_UNSPECIFIED = 0 - SCOPE_UNCHANGED = 1 - SCOPE_CHANGED = 2 - - class Impact(proto.Enum): - r"""The Impact metrics capture the effects of a successfully - exploited vulnerability on the component that suffers the worst - outcome that is most directly and predictably associated with - the attack. - - Values: - IMPACT_UNSPECIFIED (0): - Invalid value. - IMPACT_HIGH (1): - High impact. - IMPACT_LOW (2): - Low impact. - IMPACT_NONE (3): - No impact. - """ - IMPACT_UNSPECIFIED = 0 - IMPACT_HIGH = 1 - IMPACT_LOW = 2 - IMPACT_NONE = 3 - - base_score: float = proto.Field( - proto.DOUBLE, - number=1, - ) - attack_vector: AttackVector = proto.Field( - proto.ENUM, - number=5, - enum=AttackVector, - ) - attack_complexity: AttackComplexity = proto.Field( - proto.ENUM, - number=6, - enum=AttackComplexity, - ) - privileges_required: PrivilegesRequired = proto.Field( - proto.ENUM, - number=7, - enum=PrivilegesRequired, - ) - user_interaction: UserInteraction = proto.Field( - proto.ENUM, - number=8, - enum=UserInteraction, - ) - scope: Scope = proto.Field( - proto.ENUM, - number=9, - enum=Scope, - ) - confidentiality_impact: Impact = proto.Field( - proto.ENUM, - number=10, - enum=Impact, - ) - integrity_impact: Impact = proto.Field( - proto.ENUM, - number=11, - enum=Impact, - ) - availability_impact: Impact = proto.Field( - proto.ENUM, - number=12, - enum=Impact, - ) - - -class Package(proto.Message): - r"""Package is a generic definition of a package. - - Attributes: - package_name (str): - The name of the package where the - vulnerability was detected. - cpe_uri (str): - The CPE URI where the vulnerability was - detected. - package_type (str): - Type of package, for example, os, maven, or - go. - package_version (str): - The version of the package. - """ - - package_name: str = proto.Field( - proto.STRING, - number=1, - ) - cpe_uri: str = proto.Field( - proto.STRING, - number=2, - ) - package_type: str = proto.Field( - proto.STRING, - number=3, - ) - package_version: str = proto.Field( - proto.STRING, - number=4, - ) - - -class SecurityBulletin(proto.Message): - r"""SecurityBulletin are notifications of vulnerabilities of - Google products. - - Attributes: - bulletin_id (str): - ID of the bulletin corresponding to the - vulnerability. - submission_time (google.protobuf.timestamp_pb2.Timestamp): - Submission time of this Security Bulletin. - suggested_upgrade_version (str): - This represents a version that the cluster - receiving this notification should be upgraded - to, based on its current version. For example, - 1.15.0 - """ - - bulletin_id: str = proto.Field( - proto.STRING, - number=1, - ) - submission_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - suggested_upgrade_version: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v1/noxfile.py deleted file mode 100644 index c30f405f3ad8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-securitycenter' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -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"): - 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/securitycenter_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"): - 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", - "grpcio", - "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/securitycenter_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( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): - # Ignore release of mypy 1.11.0 which may have a regression - 'mypy!=1.11.0', - '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-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py deleted file mode 100644 index e404756019e2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - requests = securitycenter_v1.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - requests.resource_value_config.resource_value = "NONE" - requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py deleted file mode 100644 index 3723f44be2cb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - requests = securitycenter_v1.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - requests.resource_value_config.resource_value = "NONE" - requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_async.py deleted file mode 100644 index c0d550405cbd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_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 BulkMuteFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py deleted file mode 100644 index 39611042828f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_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 BulkMuteFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_async.py deleted file mode 100644 index 6f27ee2174b6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_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 CreateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = await client.create_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_sync.py deleted file mode 100644 index 48ddbf103dea..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_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 CreateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = client.create_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py deleted file mode 100644 index 196255a15a29..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_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 CreateEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py deleted file mode 100644 index 2544f1d14706..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_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 CreateEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_async.py deleted file mode 100644 index 84c10d4bf3f8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_sync.py deleted file mode 100644 index 3c594dcc28cb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_async.py deleted file mode 100644 index aa47e9565150..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_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 CreateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = await client.create_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_sync.py deleted file mode 100644 index aa64e4c92f71..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_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 CreateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = client.create_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_async.py deleted file mode 100644 index c1e37d27979b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_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 CreateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.create_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_sync.py deleted file mode 100644 index f313379f2bda..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_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 CreateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = client.create_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py deleted file mode 100644 index 20431387d14e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_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 CreateSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py deleted file mode 100644 index cc70b8c77485..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_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 CreateSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_async.py deleted file mode 100644 index 5a9938f4f606..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_source(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_sync.py deleted file mode 100644 index d79924fc941f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_source(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_async.py deleted file mode 100644 index 990cd91d3f2f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - await client.delete_big_query_export(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_sync.py deleted file mode 100644 index 7b8a0710a6b6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - client.delete_big_query_export(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py deleted file mode 100644 index 6fd5fad55d83..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_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 DeleteEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_delete_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - await client.delete_event_threat_detection_custom_module(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py deleted file mode 100644 index 4126fb7da0d3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_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 DeleteEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_delete_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - client.delete_event_threat_detection_custom_module(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_async.py deleted file mode 100644 index c4f1c8484a6e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_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 DeleteMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_delete_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_mute_config(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_sync.py deleted file mode 100644 index 04a1241d4610..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_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 DeleteMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_delete_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_mute_config(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_async.py deleted file mode 100644 index a2ea5ed9a93d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_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 DeleteNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_config(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_sync.py deleted file mode 100644 index bb408a4637e4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_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 DeleteNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_config(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_async.py deleted file mode 100644 index 42d63c083d6a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_resource_value_config(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py deleted file mode 100644 index a84b69405090..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_resource_value_config(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py deleted file mode 100644 index 9e2c550b018b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_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 DeleteSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_delete_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - await client.delete_security_health_analytics_custom_module(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py deleted file mode 100644 index 44d1b7765a20..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_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 DeleteSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_delete_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - client.delete_security_health_analytics_custom_module(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_async.py deleted file mode 100644 index 2d3a4e11966a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_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 GetBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = await client.get_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_sync.py deleted file mode 100644 index f3754570b866..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_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 GetBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = client.get_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py deleted file mode 100644 index fe81fc63fb30..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_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 GetEffectiveEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_effective_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_effective_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py deleted file mode 100644 index 1d4d49fff5bd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_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 GetEffectiveEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_effective_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_effective_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py deleted file mode 100644 index fe87fa09b31f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_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 GetEffectiveSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_effective_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_effective_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py deleted file mode 100644 index bfa2f6f00642..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_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 GetEffectiveSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_effective_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_effective_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py deleted file mode 100644 index 62c809c57f6f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_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 GetEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py deleted file mode 100644 index cbde7132fb16..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_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 GetEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_async.py deleted file mode 100644 index 3884cd78982e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_sync.py deleted file mode 100644 index 04461d2bd874..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_async.py deleted file mode 100644 index cd5077ce53bb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_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 GetMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_sync.py deleted file mode 100644 index 0794d6d0a981..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_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 GetMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_async.py deleted file mode 100644 index 4ca94a312da4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_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 GetNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_sync.py deleted file mode 100644 index a9fdde5359f3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_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 GetNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_async.py deleted file mode 100644 index 5cf5ce3a26d2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_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 GetOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_sync.py deleted file mode 100644 index fb45a62aeafa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_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 GetOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_async.py deleted file mode 100644 index 30fb9d9c366b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_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 GetResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_sync.py deleted file mode 100644 index 0b453f060803..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_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 GetResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py deleted file mode 100644 index 4f3caf3a11bd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_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 GetSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py deleted file mode 100644 index 55bae4951d45..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_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 GetSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_async.py deleted file mode 100644 index 1b99150b7442..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_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 GetSimulation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetSimulation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_simulation(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_simulation(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetSimulation_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_sync.py deleted file mode 100644 index 083acba19009..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_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 GetSimulation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetSimulation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_simulation(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = client.get_simulation(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetSimulation_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_async.py deleted file mode 100644 index 3b09eb27dfef..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_source(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_sync.py deleted file mode 100644 index ae5d605951c4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_source(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_async.py deleted file mode 100644 index ba715be17d9c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_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 GetValuedResource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetValuedResource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_valued_resource(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_valued_resource(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetValuedResource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_sync.py deleted file mode 100644 index b3aa5036453d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_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 GetValuedResource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetValuedResource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_valued_resource(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_valued_resource(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetValuedResource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_async.py deleted file mode 100644 index 972ab2a30dc1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_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 GroupAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GroupAssets_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_group_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GroupAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_sync.py deleted file mode 100644 index 85fa08c63683..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_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 GroupAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GroupAssets_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_group_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GroupAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_async.py deleted file mode 100644 index 8277a2723cc7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GroupFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_group_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_sync.py deleted file mode 100644 index 501397bb2a26..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GroupFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_group_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_async.py deleted file mode 100644 index d7eb57f6976c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_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 ListAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListAssets_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_sync.py deleted file mode 100644 index 129d168899aa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_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 ListAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListAssets_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_async.py deleted file mode 100644 index 1fd2c65f76c6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_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 ListAttackPaths -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListAttackPaths_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_attack_paths(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListAttackPaths_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_sync.py deleted file mode 100644 index ceea93417e1d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_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 ListAttackPaths -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListAttackPaths_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_attack_paths(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListAttackPaths_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_async.py deleted file mode 100644 index 438df71d9c0c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_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 ListBigQueryExports -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_sync.py deleted file mode 100644 index b967f0a3cc2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_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 ListBigQueryExports -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py deleted file mode 100644 index 7b214a5e3786..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_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 ListDescendantEventThreatDetectionCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_descendant_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py deleted file mode 100644 index 764f1cbe9905..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_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 ListDescendantEventThreatDetectionCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_descendant_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py deleted file mode 100644 index 4f577cf8f0e1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_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 ListDescendantSecurityHealthAnalyticsCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_descendant_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py deleted file mode 100644 index 44aacf778aaa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_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 ListDescendantSecurityHealthAnalyticsCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_descendant_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py deleted file mode 100644 index 40ac4b1fae7f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_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 ListEffectiveEventThreatDetectionCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_effective_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_event_threat_detection_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py deleted file mode 100644 index d339fb184b9f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_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 ListEffectiveEventThreatDetectionCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_effective_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_event_threat_detection_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py deleted file mode 100644 index 2ddb1fdf50a9..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_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 ListEffectiveSecurityHealthAnalyticsCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_effective_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_security_health_analytics_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py deleted file mode 100644 index a6d1e35fe7a4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_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 ListEffectiveSecurityHealthAnalyticsCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_effective_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_security_health_analytics_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py deleted file mode 100644 index 053e3047b38a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_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 ListEventThreatDetectionCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_event_threat_detection_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py deleted file mode 100644 index 8216523320e3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_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 ListEventThreatDetectionCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_event_threat_detection_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_async.py deleted file mode 100644 index f2fc2cc4e0e4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_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 securitycenter_v1 - - -async def sample_list_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_sync.py deleted file mode 100644 index 574c0709c259..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_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 securitycenter_v1 - - -def sample_list_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_async.py deleted file mode 100644 index b4984b693810..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_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 ListMuteConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_mute_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_sync.py deleted file mode 100644 index 451cf050e43b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_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 ListMuteConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_mute_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_async.py deleted file mode 100644 index 9b8132cda94b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_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 ListNotificationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_sync.py deleted file mode 100644 index 27e3721c377d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_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 ListNotificationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_async.py deleted file mode 100644 index 6d2ebd0e1a1e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_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 ListResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py deleted file mode 100644 index a34c9520517f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_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 ListResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py deleted file mode 100644 index b6d94d40eb3e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_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 ListSecurityHealthAnalyticsCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_security_health_analytics_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py deleted file mode 100644 index d352446e7eed..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_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 ListSecurityHealthAnalyticsCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_security_health_analytics_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_async.py deleted file mode 100644 index 6e653789098a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListSources_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_sources(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_sync.py deleted file mode 100644 index 3d73c443003d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListSources_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_sources(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_async.py deleted file mode 100644 index 09db5a4658e4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_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 ListValuedResources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListValuedResources_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_valued_resources(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListValuedResources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_sync.py deleted file mode 100644 index 0c4289dd7f65..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_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 ListValuedResources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListValuedResources_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_valued_resources(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListValuedResources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_async.py deleted file mode 100644 index 3e126713c3e2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_sync.py deleted file mode 100644 index de045eb9e950..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_async.py deleted file mode 100644 index 83c439f5e761..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SetFindingState_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_set_finding_state(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_sync.py deleted file mode 100644 index b6c47c7d5405..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SetFindingState_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_set_finding_state(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_async.py deleted file mode 100644 index d0828598e4ea..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_sync.py deleted file mode 100644 index 9592707e3a59..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_async.py deleted file mode 100644 index 1d2631a20453..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_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 SetMute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SetMute_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_set_mute(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = await client.set_mute(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SetMute_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_sync.py deleted file mode 100644 index 10b240d03f92..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_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 SetMute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SetMute_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_set_mute(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = client.set_mute(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SetMute_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py deleted file mode 100644 index 8f323db2f936..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_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 SimulateSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_simulate_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - resource = securitycenter_v1.SimulatedResource() - resource.resource_type = "resource_type_value" - - request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - resource=resource, - ) - - # Make the request - response = await client.simulate_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py deleted file mode 100644 index 81d436d78385..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_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 SimulateSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_simulate_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - resource = securitycenter_v1.SimulatedResource() - resource.resource_type = "resource_type_value" - - request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - resource=resource, - ) - - # Make the request - response = client.simulate_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_async.py deleted file mode 100644 index 479364cbe039..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_sync.py deleted file mode 100644 index d39b8072621c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_async.py deleted file mode 100644 index e07c6c16bb47..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_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 UpdateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateBigQueryExportRequest( - ) - - # Make the request - response = await client.update_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_sync.py deleted file mode 100644 index 0569a012c3bc..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_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 UpdateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateBigQueryExportRequest( - ) - - # Make the request - response = client.update_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py deleted file mode 100644 index fd503424dd75..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_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 UpdateEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( - ) - - # Make the request - response = await client.update_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py deleted file mode 100644 index 05ca8e32603f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_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 UpdateEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( - ) - - # Make the request - response = client.update_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_async.py deleted file mode 100644 index dd917f4ac903..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_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 UpdateExternalSystem -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_external_system(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateExternalSystemRequest( - ) - - # Make the request - response = await client.update_external_system(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_sync.py deleted file mode 100644 index fc184d7026aa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_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 UpdateExternalSystem -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_external_system(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateExternalSystemRequest( - ) - - # Make the request - response = client.update_external_system(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_async.py deleted file mode 100644 index fb05f8e20bdf..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_sync.py deleted file mode 100644 index 3c4fe5bc7ec5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_async.py deleted file mode 100644 index 39d5f038be44..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_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 UpdateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = await client.update_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_sync.py deleted file mode 100644 index 245f3c802a09..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_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 UpdateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = client.update_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_async.py deleted file mode 100644 index 6dfffbef6f93..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_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 UpdateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = await client.update_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_sync.py deleted file mode 100644 index a8ca94d09985..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_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 UpdateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = client.update_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_async.py deleted file mode 100644 index b88b1aa0af5e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = await client.update_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_sync.py deleted file mode 100644 index c897ad8cdba4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = client.update_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_async.py deleted file mode 100644 index 2b7526207b34..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_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 UpdateResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - resource_value_config = securitycenter_v1.ResourceValueConfig() - resource_value_config.resource_value = "NONE" - resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.UpdateResourceValueConfigRequest( - resource_value_config=resource_value_config, - ) - - # Make the request - response = await client.update_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_sync.py deleted file mode 100644 index fe7fb7c93f87..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_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 UpdateResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - resource_value_config = securitycenter_v1.ResourceValueConfig() - resource_value_config.resource_value = "NONE" - resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.UpdateResourceValueConfigRequest( - resource_value_config=resource_value_config, - ) - - # Make the request - response = client.update_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py deleted file mode 100644 index 66f5cd744979..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_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 UpdateSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( - ) - - # Make the request - response = await client.update_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py deleted file mode 100644 index ed56eba54e03..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_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 UpdateSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( - ) - - # Make the request - response = client.update_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_async.py deleted file mode 100644 index 1b69e29a2d37..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_security_marks(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_sync.py deleted file mode 100644 index b0c6a29d705b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_security_marks(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_async.py deleted file mode 100644 index 659495e1c73f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_source(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_sync.py deleted file mode 100644 index 80ac8afaabd7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_source(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py deleted file mode 100644 index 38c6309258a8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_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 ValidateEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_validate_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - raw_text="raw_text_value", - type_="type__value", - ) - - # Make the request - response = await client.validate_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py deleted file mode 100644 index dbcc6d5f0f5c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_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 ValidateEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_validate_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - raw_text="raw_text_value", - type_="type__value", - ) - - # Make the request - response = client.validate_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json deleted file mode 100644 index 176395462f39..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json +++ /dev/null @@ -1,10298 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.securitycenter.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-securitycenter", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.batch_create_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BatchCreateResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BatchCreateResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "requests", - "type": "MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse", - "shortName": "batch_create_resource_value_configs" - }, - "description": "Sample for BatchCreateResourceValueConfigs", - "file": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.batch_create_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BatchCreateResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BatchCreateResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "requests", - "type": "MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse", - "shortName": "batch_create_resource_value_configs" - }, - "description": "Sample for BatchCreateResourceValueConfigs", - "file": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.bulk_mute_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BulkMuteFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BulkMuteFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "bulk_mute_findings" - }, - "description": "Sample for BulkMuteFindings", - "file": "securitycenter_v1_generated_security_center_bulk_mute_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v1_generated_security_center_bulk_mute_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.bulk_mute_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BulkMuteFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BulkMuteFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "bulk_mute_findings" - }, - "description": "Sample for BulkMuteFindings", - "file": "securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v1.types.BigQueryExport" - }, - { - "name": "big_query_export_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.BigQueryExport", - "shortName": "create_big_query_export" - }, - "description": "Sample for CreateBigQueryExport", - "file": "securitycenter_v1_generated_security_center_create_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v1_generated_security_center_create_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v1.types.BigQueryExport" - }, - { - "name": "big_query_export_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.BigQueryExport", - "shortName": "create_big_query_export" - }, - "description": "Sample for CreateBigQueryExport", - "file": "securitycenter_v1_generated_security_center_create_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v1_generated_security_center_create_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "event_threat_detection_custom_module", - "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule", - "shortName": "create_event_threat_detection_custom_module" - }, - "description": "Sample for CreateEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "event_threat_detection_custom_module", - "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule", - "shortName": "create_event_threat_detection_custom_module" - }, - "description": "Sample for CreateEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v1_generated_security_center_create_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1_generated_security_center_create_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v1_generated_security_center_create_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1_generated_security_center_create_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateMuteConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v1.types.MuteConfig" - }, - { - "name": "mute_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.cloud.securitycenter_v1.types.MuteConfig", - "shortName": "create_mute_config" - }, - "description": "Sample for CreateMuteConfig", - "file": "securitycenter_v1_generated_security_center_create_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v1_generated_security_center_create_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateMuteConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v1.types.MuteConfig" - }, - { - "name": "mute_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.cloud.securitycenter_v1.types.MuteConfig", - "shortName": "create_mute_config" - }, - "description": "Sample for CreateMuteConfig", - "file": "securitycenter_v1_generated_security_center_create_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v1_generated_security_center_create_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "config_id", - "type": "str" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1.types.NotificationConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.NotificationConfig", - "shortName": "create_notification_config" - }, - "description": "Sample for CreateNotificationConfig", - "file": "securitycenter_v1_generated_security_center_create_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1_generated_security_center_create_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "config_id", - "type": "str" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1.types.NotificationConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.NotificationConfig", - "shortName": "create_notification_config" - }, - "description": "Sample for CreateNotificationConfig", - "file": "securitycenter_v1_generated_security_center_create_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1_generated_security_center_create_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "security_health_analytics_custom_module", - "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", - "shortName": "create_security_health_analytics_custom_module" - }, - "description": "Sample for CreateSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "security_health_analytics_custom_module", - "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", - "shortName": "create_security_health_analytics_custom_module" - }, - "description": "Sample for CreateSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v1_generated_security_center_create_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_create_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v1_generated_security_center_create_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_create_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest" - }, - { - "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_big_query_export" - }, - "description": "Sample for DeleteBigQueryExport", - "file": "securitycenter_v1_generated_security_center_delete_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v1_generated_security_center_delete_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest" - }, - { - "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_big_query_export" - }, - "description": "Sample for DeleteBigQueryExport", - "file": "securitycenter_v1_generated_security_center_delete_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v1_generated_security_center_delete_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest" - }, - { - "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_event_threat_detection_custom_module" - }, - "description": "Sample for DeleteEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest" - }, - { - "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_event_threat_detection_custom_module" - }, - "description": "Sample for DeleteEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest" - }, - { - "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_mute_config" - }, - "description": "Sample for DeleteMuteConfig", - "file": "securitycenter_v1_generated_security_center_delete_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v1_generated_security_center_delete_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest" - }, - { - "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_mute_config" - }, - "description": "Sample for DeleteMuteConfig", - "file": "securitycenter_v1_generated_security_center_delete_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v1_generated_security_center_delete_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest" - }, - { - "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_config" - }, - "description": "Sample for DeleteNotificationConfig", - "file": "securitycenter_v1_generated_security_center_delete_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1_generated_security_center_delete_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest" - }, - { - "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_config" - }, - "description": "Sample for DeleteNotificationConfig", - "file": "securitycenter_v1_generated_security_center_delete_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1_generated_security_center_delete_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest" - }, - { - "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_resource_value_config" - }, - "description": "Sample for DeleteResourceValueConfig", - "file": "securitycenter_v1_generated_security_center_delete_resource_value_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v1_generated_security_center_delete_resource_value_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest" - }, - { - "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_resource_value_config" - }, - "description": "Sample for DeleteResourceValueConfig", - "file": "securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "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_security_health_analytics_custom_module" - }, - "description": "Sample for DeleteSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "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_security_health_analytics_custom_module" - }, - "description": "Sample for DeleteSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetBigQueryExportRequest" - }, - { - "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.securitycenter_v1.types.BigQueryExport", - "shortName": "get_big_query_export" - }, - "description": "Sample for GetBigQueryExport", - "file": "securitycenter_v1_generated_security_center_get_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetBigQueryExportRequest" - }, - { - "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.securitycenter_v1.types.BigQueryExport", - "shortName": "get_big_query_export" - }, - "description": "Sample for GetBigQueryExport", - "file": "securitycenter_v1_generated_security_center_get_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_effective_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetEffectiveEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule", - "shortName": "get_effective_event_threat_detection_custom_module" - }, - "description": "Sample for GetEffectiveEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_effective_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetEffectiveEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule", - "shortName": "get_effective_event_threat_detection_custom_module" - }, - "description": "Sample for GetEffectiveEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_effective_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetEffectiveSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule", - "shortName": "get_effective_security_health_analytics_custom_module" - }, - "description": "Sample for GetEffectiveSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_effective_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetEffectiveSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule", - "shortName": "get_effective_security_health_analytics_custom_module" - }, - "description": "Sample for GetEffectiveSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.EventThreatDetectionCustomModule", - "shortName": "get_event_threat_detection_custom_module" - }, - "description": "Sample for GetEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.EventThreatDetectionCustomModule", - "shortName": "get_event_threat_detection_custom_module" - }, - "description": "Sample for GetEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v1_generated_security_center_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v1_generated_security_center_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetMuteConfigRequest" - }, - { - "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.securitycenter_v1.types.MuteConfig", - "shortName": "get_mute_config" - }, - "description": "Sample for GetMuteConfig", - "file": "securitycenter_v1_generated_security_center_get_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetMuteConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetMuteConfigRequest" - }, - { - "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.securitycenter_v1.types.MuteConfig", - "shortName": "get_mute_config" - }, - "description": "Sample for GetMuteConfig", - "file": "securitycenter_v1_generated_security_center_get_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetMuteConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetNotificationConfigRequest" - }, - { - "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.securitycenter_v1.types.NotificationConfig", - "shortName": "get_notification_config" - }, - "description": "Sample for GetNotificationConfig", - "file": "securitycenter_v1_generated_security_center_get_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetNotificationConfigRequest" - }, - { - "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.securitycenter_v1.types.NotificationConfig", - "shortName": "get_notification_config" - }, - "description": "Sample for GetNotificationConfig", - "file": "securitycenter_v1_generated_security_center_get_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest" - }, - { - "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.securitycenter_v1.types.OrganizationSettings", - "shortName": "get_organization_settings" - }, - "description": "Sample for GetOrganizationSettings", - "file": "securitycenter_v1_generated_security_center_get_organization_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_organization_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest" - }, - { - "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.securitycenter_v1.types.OrganizationSettings", - "shortName": "get_organization_settings" - }, - "description": "Sample for GetOrganizationSettings", - "file": "securitycenter_v1_generated_security_center_get_organization_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_organization_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest" - }, - { - "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.securitycenter_v1.types.ResourceValueConfig", - "shortName": "get_resource_value_config" - }, - "description": "Sample for GetResourceValueConfig", - "file": "securitycenter_v1_generated_security_center_get_resource_value_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_resource_value_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest" - }, - { - "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.securitycenter_v1.types.ResourceValueConfig", - "shortName": "get_resource_value_config" - }, - "description": "Sample for GetResourceValueConfig", - "file": "securitycenter_v1_generated_security_center_get_resource_value_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_resource_value_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", - "shortName": "get_security_health_analytics_custom_module" - }, - "description": "Sample for GetSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", - "shortName": "get_security_health_analytics_custom_module" - }, - "description": "Sample for GetSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_simulation", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSimulation", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSimulation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetSimulationRequest" - }, - { - "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.securitycenter_v1.types.Simulation", - "shortName": "get_simulation" - }, - "description": "Sample for GetSimulation", - "file": "securitycenter_v1_generated_security_center_get_simulation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSimulation_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_simulation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_simulation", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSimulation", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSimulation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetSimulationRequest" - }, - { - "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.securitycenter_v1.types.Simulation", - "shortName": "get_simulation" - }, - "description": "Sample for GetSimulation", - "file": "securitycenter_v1_generated_security_center_get_simulation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSimulation_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_simulation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetSourceRequest" - }, - { - "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.securitycenter_v1.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v1_generated_security_center_get_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetSourceRequest" - }, - { - "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.securitycenter_v1.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v1_generated_security_center_get_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_valued_resource", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetValuedResource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetValuedResource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetValuedResourceRequest" - }, - { - "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.securitycenter_v1.types.ValuedResource", - "shortName": "get_valued_resource" - }, - "description": "Sample for GetValuedResource", - "file": "securitycenter_v1_generated_security_center_get_valued_resource_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetValuedResource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_valued_resource_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_valued_resource", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetValuedResource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetValuedResource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetValuedResourceRequest" - }, - { - "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.securitycenter_v1.types.ValuedResource", - "shortName": "get_valued_resource" - }, - "description": "Sample for GetValuedResource", - "file": "securitycenter_v1_generated_security_center_get_valued_resource_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetValuedResource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_valued_resource_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.group_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GroupAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsAsyncPager", - "shortName": "group_assets" - }, - "description": "Sample for GroupAssets", - "file": "securitycenter_v1_generated_security_center_group_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1_generated_security_center_group_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.group_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GroupAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsPager", - "shortName": "group_assets" - }, - "description": "Sample for GroupAssets", - "file": "securitycenter_v1_generated_security_center_group_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1_generated_security_center_group_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsAsyncPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v1_generated_security_center_group_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1_generated_security_center_group_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v1_generated_security_center_group_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1_generated_security_center_group_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsAsyncPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "securitycenter_v1_generated_security_center_list_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1_generated_security_center_list_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "securitycenter_v1_generated_security_center_list_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1_generated_security_center_list_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_attack_paths", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAttackPaths", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAttackPaths" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListAttackPathsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListAttackPathsAsyncPager", - "shortName": "list_attack_paths" - }, - "description": "Sample for ListAttackPaths", - "file": "securitycenter_v1_generated_security_center_list_attack_paths_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v1_generated_security_center_list_attack_paths_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_attack_paths", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAttackPaths", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAttackPaths" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListAttackPathsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListAttackPathsPager", - "shortName": "list_attack_paths" - }, - "description": "Sample for ListAttackPaths", - "file": "securitycenter_v1_generated_security_center_list_attack_paths_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v1_generated_security_center_list_attack_paths_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_big_query_exports", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListBigQueryExports", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListBigQueryExports" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsAsyncPager", - "shortName": "list_big_query_exports" - }, - "description": "Sample for ListBigQueryExports", - "file": "securitycenter_v1_generated_security_center_list_big_query_exports_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v1_generated_security_center_list_big_query_exports_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_big_query_exports", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListBigQueryExports", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListBigQueryExports" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsPager", - "shortName": "list_big_query_exports" - }, - "description": "Sample for ListBigQueryExports", - "file": "securitycenter_v1_generated_security_center_list_big_query_exports_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v1_generated_security_center_list_big_query_exports_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_descendant_event_threat_detection_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantEventThreatDetectionCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListDescendantEventThreatDetectionCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager", - "shortName": "list_descendant_event_threat_detection_custom_modules" - }, - "description": "Sample for ListDescendantEventThreatDetectionCustomModules", - "file": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_descendant_event_threat_detection_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantEventThreatDetectionCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListDescendantEventThreatDetectionCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesPager", - "shortName": "list_descendant_event_threat_detection_custom_modules" - }, - "description": "Sample for ListDescendantEventThreatDetectionCustomModules", - "file": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_descendant_security_health_analytics_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantSecurityHealthAnalyticsCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListDescendantSecurityHealthAnalyticsCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager", - "shortName": "list_descendant_security_health_analytics_custom_modules" - }, - "description": "Sample for ListDescendantSecurityHealthAnalyticsCustomModules", - "file": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_descendant_security_health_analytics_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantSecurityHealthAnalyticsCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListDescendantSecurityHealthAnalyticsCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager", - "shortName": "list_descendant_security_health_analytics_custom_modules" - }, - "description": "Sample for ListDescendantSecurityHealthAnalyticsCustomModules", - "file": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_effective_event_threat_detection_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveEventThreatDetectionCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListEffectiveEventThreatDetectionCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesAsyncPager", - "shortName": "list_effective_event_threat_detection_custom_modules" - }, - "description": "Sample for ListEffectiveEventThreatDetectionCustomModules", - "file": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_effective_event_threat_detection_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveEventThreatDetectionCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListEffectiveEventThreatDetectionCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesPager", - "shortName": "list_effective_event_threat_detection_custom_modules" - }, - "description": "Sample for ListEffectiveEventThreatDetectionCustomModules", - "file": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_effective_security_health_analytics_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveSecurityHealthAnalyticsCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListEffectiveSecurityHealthAnalyticsCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager", - "shortName": "list_effective_security_health_analytics_custom_modules" - }, - "description": "Sample for ListEffectiveSecurityHealthAnalyticsCustomModules", - "file": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_effective_security_health_analytics_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveSecurityHealthAnalyticsCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListEffectiveSecurityHealthAnalyticsCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager", - "shortName": "list_effective_security_health_analytics_custom_modules" - }, - "description": "Sample for ListEffectiveSecurityHealthAnalyticsCustomModules", - "file": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_event_threat_detection_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEventThreatDetectionCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListEventThreatDetectionCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesAsyncPager", - "shortName": "list_event_threat_detection_custom_modules" - }, - "description": "Sample for ListEventThreatDetectionCustomModules", - "file": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_event_threat_detection_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEventThreatDetectionCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListEventThreatDetectionCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesPager", - "shortName": "list_event_threat_detection_custom_modules" - }, - "description": "Sample for ListEventThreatDetectionCustomModules", - "file": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_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.securitycenter_v1.services.security_center.pagers.ListFindingsAsyncPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v1_generated_security_center_list_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1_generated_security_center_list_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_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.securitycenter_v1.services.security_center.pagers.ListFindingsPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v1_generated_security_center_list_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1_generated_security_center_list_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_mute_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListMuteConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListMuteConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListMuteConfigsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsAsyncPager", - "shortName": "list_mute_configs" - }, - "description": "Sample for ListMuteConfigs", - "file": "securitycenter_v1_generated_security_center_list_mute_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v1_generated_security_center_list_mute_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_mute_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListMuteConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListMuteConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListMuteConfigsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsPager", - "shortName": "list_mute_configs" - }, - "description": "Sample for ListMuteConfigs", - "file": "securitycenter_v1_generated_security_center_list_mute_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v1_generated_security_center_list_mute_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_notification_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListNotificationConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListNotificationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsAsyncPager", - "shortName": "list_notification_configs" - }, - "description": "Sample for ListNotificationConfigs", - "file": "securitycenter_v1_generated_security_center_list_notification_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1_generated_security_center_list_notification_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_notification_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListNotificationConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListNotificationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsPager", - "shortName": "list_notification_configs" - }, - "description": "Sample for ListNotificationConfigs", - "file": "securitycenter_v1_generated_security_center_list_notification_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1_generated_security_center_list_notification_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsAsyncPager", - "shortName": "list_resource_value_configs" - }, - "description": "Sample for ListResourceValueConfigs", - "file": "securitycenter_v1_generated_security_center_list_resource_value_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v1_generated_security_center_list_resource_value_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsPager", - "shortName": "list_resource_value_configs" - }, - "description": "Sample for ListResourceValueConfigs", - "file": "securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_security_health_analytics_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSecurityHealthAnalyticsCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSecurityHealthAnalyticsCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager", - "shortName": "list_security_health_analytics_custom_modules" - }, - "description": "Sample for ListSecurityHealthAnalyticsCustomModules", - "file": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_security_health_analytics_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSecurityHealthAnalyticsCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSecurityHealthAnalyticsCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesPager", - "shortName": "list_security_health_analytics_custom_modules" - }, - "description": "Sample for ListSecurityHealthAnalyticsCustomModules", - "file": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListSourcesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListSourcesAsyncPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v1_generated_security_center_list_sources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSources_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": "securitycenter_v1_generated_security_center_list_sources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListSourcesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListSourcesPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v1_generated_security_center_list_sources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSources_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": "securitycenter_v1_generated_security_center_list_sources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_valued_resources", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListValuedResources", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListValuedResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListValuedResourcesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesAsyncPager", - "shortName": "list_valued_resources" - }, - "description": "Sample for ListValuedResources", - "file": "securitycenter_v1_generated_security_center_list_valued_resources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v1_generated_security_center_list_valued_resources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_valued_resources", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListValuedResources", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListValuedResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListValuedResourcesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesPager", - "shortName": "list_valued_resources" - }, - "description": "Sample for ListValuedResources", - "file": "securitycenter_v1_generated_security_center_list_valued_resources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v1_generated_security_center_list_valued_resources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.run_asset_discovery", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.RunAssetDiscovery", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "RunAssetDiscovery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "run_asset_discovery" - }, - "description": "Sample for RunAssetDiscovery", - "file": "securitycenter_v1_generated_security_center_run_asset_discovery_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1_generated_security_center_run_asset_discovery_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.run_asset_discovery", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.RunAssetDiscovery", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "RunAssetDiscovery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "run_asset_discovery" - }, - "description": "Sample for RunAssetDiscovery", - "file": "securitycenter_v1_generated_security_center_run_asset_discovery_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1_generated_security_center_run_asset_discovery_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v1.types.Finding.State" - }, - { - "name": "start_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v1_generated_security_center_set_finding_state_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1_generated_security_center_set_finding_state_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v1.types.Finding.State" - }, - { - "name": "start_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v1_generated_security_center_set_finding_state_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1_generated_security_center_set_finding_state_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v1_generated_security_center_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v1_generated_security_center_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.set_mute", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetMute", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetMute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.SetMuteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "mute", - "type": "google.cloud.securitycenter_v1.types.Finding.Mute" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "set_mute" - }, - "description": "Sample for SetMute", - "file": "securitycenter_v1_generated_security_center_set_mute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SetMute_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": "securitycenter_v1_generated_security_center_set_mute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.set_mute", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetMute", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetMute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.SetMuteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "mute", - "type": "google.cloud.securitycenter_v1.types.Finding.Mute" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "set_mute" - }, - "description": "Sample for SetMute", - "file": "securitycenter_v1_generated_security_center_set_mute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SetMute_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": "securitycenter_v1_generated_security_center_set_mute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.simulate_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SimulateSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SimulateSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "custom_config", - "type": "google.cloud.securitycenter_v1.types.CustomConfig" - }, - { - "name": "resource", - "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse", - "shortName": "simulate_security_health_analytics_custom_module" - }, - "description": "Sample for SimulateSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.simulate_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SimulateSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SimulateSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "custom_config", - "type": "google.cloud.securitycenter_v1.types.CustomConfig" - }, - { - "name": "resource", - "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse", - "shortName": "simulate_security_health_analytics_custom_module" - }, - "description": "Sample for SimulateSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v1_generated_security_center_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v1_generated_security_center_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v1.types.BigQueryExport" - }, - { - "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.securitycenter_v1.types.BigQueryExport", - "shortName": "update_big_query_export" - }, - "description": "Sample for UpdateBigQueryExport", - "file": "securitycenter_v1_generated_security_center_update_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v1_generated_security_center_update_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v1.types.BigQueryExport" - }, - { - "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.securitycenter_v1.types.BigQueryExport", - "shortName": "update_big_query_export" - }, - "description": "Sample for UpdateBigQueryExport", - "file": "securitycenter_v1_generated_security_center_update_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v1_generated_security_center_update_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest" - }, - { - "name": "event_threat_detection_custom_module", - "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" - }, - { - "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.securitycenter_v1.types.EventThreatDetectionCustomModule", - "shortName": "update_event_threat_detection_custom_module" - }, - "description": "Sample for UpdateEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest" - }, - { - "name": "event_threat_detection_custom_module", - "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" - }, - { - "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.securitycenter_v1.types.EventThreatDetectionCustomModule", - "shortName": "update_event_threat_detection_custom_module" - }, - "description": "Sample for UpdateEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_external_system", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateExternalSystem", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateExternalSystem" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest" - }, - { - "name": "external_system", - "type": "google.cloud.securitycenter_v1.types.ExternalSystem" - }, - { - "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.securitycenter_v1.types.ExternalSystem", - "shortName": "update_external_system" - }, - "description": "Sample for UpdateExternalSystem", - "file": "securitycenter_v1_generated_security_center_update_external_system_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v1_generated_security_center_update_external_system_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_external_system", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateExternalSystem", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateExternalSystem" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest" - }, - { - "name": "external_system", - "type": "google.cloud.securitycenter_v1.types.ExternalSystem" - }, - { - "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.securitycenter_v1.types.ExternalSystem", - "shortName": "update_external_system" - }, - "description": "Sample for UpdateExternalSystem", - "file": "securitycenter_v1_generated_security_center_update_external_system_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v1_generated_security_center_update_external_system_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v1_generated_security_center_update_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1_generated_security_center_update_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v1_generated_security_center_update_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1_generated_security_center_update_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v1.types.MuteConfig" - }, - { - "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.securitycenter_v1.types.MuteConfig", - "shortName": "update_mute_config" - }, - "description": "Sample for UpdateMuteConfig", - "file": "securitycenter_v1_generated_security_center_update_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v1_generated_security_center_update_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v1.types.MuteConfig" - }, - { - "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.securitycenter_v1.types.MuteConfig", - "shortName": "update_mute_config" - }, - "description": "Sample for UpdateMuteConfig", - "file": "securitycenter_v1_generated_security_center_update_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v1_generated_security_center_update_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1.types.NotificationConfig" - }, - { - "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.securitycenter_v1.types.NotificationConfig", - "shortName": "update_notification_config" - }, - "description": "Sample for UpdateNotificationConfig", - "file": "securitycenter_v1_generated_security_center_update_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1_generated_security_center_update_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1.types.NotificationConfig" - }, - { - "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.securitycenter_v1.types.NotificationConfig", - "shortName": "update_notification_config" - }, - "description": "Sample for UpdateNotificationConfig", - "file": "securitycenter_v1_generated_security_center_update_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1_generated_security_center_update_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest" - }, - { - "name": "organization_settings", - "type": "google.cloud.securitycenter_v1.types.OrganizationSettings" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.OrganizationSettings", - "shortName": "update_organization_settings" - }, - "description": "Sample for UpdateOrganizationSettings", - "file": "securitycenter_v1_generated_security_center_update_organization_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1_generated_security_center_update_organization_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest" - }, - { - "name": "organization_settings", - "type": "google.cloud.securitycenter_v1.types.OrganizationSettings" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.OrganizationSettings", - "shortName": "update_organization_settings" - }, - "description": "Sample for UpdateOrganizationSettings", - "file": "securitycenter_v1_generated_security_center_update_organization_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1_generated_security_center_update_organization_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest" - }, - { - "name": "resource_value_config", - "type": "google.cloud.securitycenter_v1.types.ResourceValueConfig" - }, - { - "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.securitycenter_v1.types.ResourceValueConfig", - "shortName": "update_resource_value_config" - }, - "description": "Sample for UpdateResourceValueConfig", - "file": "securitycenter_v1_generated_security_center_update_resource_value_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v1_generated_security_center_update_resource_value_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest" - }, - { - "name": "resource_value_config", - "type": "google.cloud.securitycenter_v1.types.ResourceValueConfig" - }, - { - "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.securitycenter_v1.types.ResourceValueConfig", - "shortName": "update_resource_value_config" - }, - "description": "Sample for UpdateResourceValueConfig", - "file": "securitycenter_v1_generated_security_center_update_resource_value_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v1_generated_security_center_update_resource_value_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "name": "security_health_analytics_custom_module", - "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" - }, - { - "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", - "shortName": "update_security_health_analytics_custom_module" - }, - "description": "Sample for UpdateSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "name": "security_health_analytics_custom_module", - "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" - }, - { - "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", - "shortName": "update_security_health_analytics_custom_module" - }, - "description": "Sample for UpdateSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v1.types.SecurityMarks" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v1_generated_security_center_update_security_marks_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1_generated_security_center_update_security_marks_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v1.types.SecurityMarks" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v1_generated_security_center_update_security_marks_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1_generated_security_center_update_security_marks_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v1_generated_security_center_update_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1_generated_security_center_update_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v1_generated_security_center_update_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1_generated_security_center_update_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.validate_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ValidateEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ValidateEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse", - "shortName": "validate_event_threat_detection_custom_module" - }, - "description": "Sample for ValidateEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.validate_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ValidateEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ValidateEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse", - "shortName": "validate_event_threat_detection_custom_module" - }, - "description": "Sample for ValidateEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py deleted file mode 100644 index f99f1a291b7b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py +++ /dev/null @@ -1,238 +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 securitycenterCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_create_resource_value_configs': ('parent', 'requests', ), - 'bulk_mute_findings': ('parent', 'filter', 'mute_annotation', ), - 'create_big_query_export': ('parent', 'big_query_export', 'big_query_export_id', ), - 'create_event_threat_detection_custom_module': ('parent', 'event_threat_detection_custom_module', ), - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_mute_config': ('parent', 'mute_config', 'mute_config_id', ), - 'create_notification_config': ('parent', 'config_id', 'notification_config', ), - 'create_security_health_analytics_custom_module': ('parent', 'security_health_analytics_custom_module', ), - 'create_source': ('parent', 'source', ), - 'delete_big_query_export': ('name', ), - 'delete_event_threat_detection_custom_module': ('name', ), - 'delete_mute_config': ('name', ), - 'delete_notification_config': ('name', ), - 'delete_resource_value_config': ('name', ), - 'delete_security_health_analytics_custom_module': ('name', ), - 'get_big_query_export': ('name', ), - 'get_effective_event_threat_detection_custom_module': ('name', ), - 'get_effective_security_health_analytics_custom_module': ('name', ), - 'get_event_threat_detection_custom_module': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_mute_config': ('name', ), - 'get_notification_config': ('name', ), - 'get_organization_settings': ('name', ), - 'get_resource_value_config': ('name', ), - 'get_security_health_analytics_custom_module': ('name', ), - 'get_simulation': ('name', ), - 'get_source': ('name', ), - 'get_valued_resource': ('name', ), - 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), - 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), - 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_attack_paths': ('parent', 'filter', 'page_token', 'page_size', ), - 'list_big_query_exports': ('parent', 'page_size', 'page_token', ), - 'list_descendant_event_threat_detection_custom_modules': ('parent', 'page_token', 'page_size', ), - 'list_descendant_security_health_analytics_custom_modules': ('parent', 'page_size', 'page_token', ), - 'list_effective_event_threat_detection_custom_modules': ('parent', 'page_token', 'page_size', ), - 'list_effective_security_health_analytics_custom_modules': ('parent', 'page_size', 'page_token', ), - 'list_event_threat_detection_custom_modules': ('parent', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_mute_configs': ('parent', 'page_size', 'page_token', ), - 'list_notification_configs': ('parent', 'page_token', 'page_size', ), - 'list_resource_value_configs': ('parent', 'page_size', 'page_token', ), - 'list_security_health_analytics_custom_modules': ('parent', 'page_size', 'page_token', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'list_valued_resources': ('parent', 'filter', 'page_token', 'page_size', 'order_by', ), - 'run_asset_discovery': ('parent', ), - 'set_finding_state': ('name', 'state', 'start_time', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'set_mute': ('name', 'mute', ), - 'simulate_security_health_analytics_custom_module': ('parent', 'custom_config', 'resource', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_big_query_export': ('big_query_export', 'update_mask', ), - 'update_event_threat_detection_custom_module': ('event_threat_detection_custom_module', 'update_mask', ), - 'update_external_system': ('external_system', 'update_mask', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_mute_config': ('mute_config', 'update_mask', ), - 'update_notification_config': ('notification_config', 'update_mask', ), - 'update_organization_settings': ('organization_settings', 'update_mask', ), - 'update_resource_value_config': ('resource_value_config', 'update_mask', ), - 'update_security_health_analytics_custom_module': ('security_health_analytics_custom_module', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), - 'update_source': ('source', 'update_mask', ), - 'validate_event_threat_detection_custom_module': ('parent', 'raw_text', 'type_', ), - } - - 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=securitycenterCallTransformer(), -): - """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 securitycenter 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-securitycenter/v1/setup.py b/owl-bot-staging/google-cloud-securitycenter/v1/setup.py deleted file mode 100644 index c4538ec101f3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/setup.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. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-securitycenter' - - -description = "Google Cloud Securitycenter API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/securitycenter/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", - "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", -] -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" - -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/unit/gapic/securitycenter_v1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_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-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py deleted file mode 100644 index 7d5099f2f3cd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py +++ /dev/null @@ -1,48250 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -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 - -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.securitycenter_v1.services.security_center import SecurityCenterAsyncClient -from google.cloud.securitycenter_v1.services.security_center import SecurityCenterClient -from google.cloud.securitycenter_v1.services.security_center import pagers -from google.cloud.securitycenter_v1.services.security_center import transports -from google.cloud.securitycenter_v1.types import access -from google.cloud.securitycenter_v1.types import application -from google.cloud.securitycenter_v1.types import attack_exposure -from google.cloud.securitycenter_v1.types import attack_path -from google.cloud.securitycenter_v1.types import backup_disaster_recovery -from google.cloud.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import cloud_armor -from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile -from google.cloud.securitycenter_v1.types import cloud_dlp_inspection -from google.cloud.securitycenter_v1.types import compliance -from google.cloud.securitycenter_v1.types import connection -from google.cloud.securitycenter_v1.types import contact_details -from google.cloud.securitycenter_v1.types import container -from google.cloud.securitycenter_v1.types import database -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors -from google.cloud.securitycenter_v1.types import exfiltration -from google.cloud.securitycenter_v1.types import external_system -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import file -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import group_membership -from google.cloud.securitycenter_v1.types import iam_binding -from google.cloud.securitycenter_v1.types import indicator -from google.cloud.securitycenter_v1.types import kernel_rootkit -from google.cloud.securitycenter_v1.types import kubernetes -from google.cloud.securitycenter_v1.types import label -from google.cloud.securitycenter_v1.types import load_balancer -from google.cloud.securitycenter_v1.types import log_entry -from google.cloud.securitycenter_v1.types import mitre_attack -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notebook -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import org_policy -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import process -from google.cloud.securitycenter_v1.types import resource -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import security_posture -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import toxic_combination -from google.cloud.securitycenter_v1.types import valued_resource -from google.cloud.securitycenter_v1.types import vulnerability -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 duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None - assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert SecurityCenterClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SecurityCenterGrpcTransport, "grpc"), - (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - 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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -def test_security_center_client_get_transport_class(): - transport = SecurityCenterClient.get_transport_class() - available_transports = [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterRestTransport, - ] - assert transport in available_transports - - transport = SecurityCenterClient.get_transport_class("grpc") - assert transport == transports.SecurityCenterGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, 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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), -]) -def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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_security_center_client_client_options_from_dict(): - with mock.patch('google.cloud.securitycenter_v1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.BulkMuteFindingsRequest, - dict, -]) -def test_bulk_mute_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.bulk_mute_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BulkMuteFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_bulk_mute_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.bulk_mute_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BulkMuteFindingsRequest() - - -def test_bulk_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.BulkMuteFindingsRequest( - parent='parent_value', - filter='filter_value', - mute_annotation='mute_annotation_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.bulk_mute_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BulkMuteFindingsRequest( - parent='parent_value', - filter='filter_value', - mute_annotation='mute_annotation_value', - ) - -def test_bulk_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc - request = {} - client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BulkMuteFindingsRequest() - -@pytest.mark.asyncio -async def test_bulk_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.bulk_mute_findings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.bulk_mute_findings] = mock_object - - request = {} - await client.bulk_mute_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.bulk_mute_findings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_bulk_mute_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BulkMuteFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BulkMuteFindingsRequest() - 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_bulk_mute_findings_async_from_dict(): - await test_bulk_mute_findings_async(request_type=dict) - - -def test_bulk_mute_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BulkMuteFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.bulk_mute_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_bulk_mute_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BulkMuteFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.bulk_mute_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_bulk_mute_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings( - 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_bulk_mute_findings_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.bulk_mute_findings( - securitycenter_service.BulkMuteFindingsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_bulk_mute_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings( - 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_bulk_mute_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.bulk_mute_findings( - securitycenter_service.BulkMuteFindingsRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_create_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - ) - response = client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - - -def test_create_security_health_analytics_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - - -def test_create_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_security_health_analytics_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest( - parent='parent_value', - ) - -def test_create_security_health_analytics_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc - request = {} - client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_security_health_analytics_custom_module(request) - - # Establish that a new wrapper 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_security_health_analytics_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - )) - response = await client.create_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - -@pytest.mark.asyncio -async def test_create_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_security_health_analytics_custom_module] = mock_object - - request = {} - await client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - )) - response = await client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - - -@pytest.mark.asyncio -async def test_create_security_health_analytics_custom_module_async_from_dict(): - await test_create_security_health_analytics_custom_module_async(request_type=dict) - - -def test_create_security_health_analytics_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_security_health_analytics_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - await client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_security_health_analytics_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_security_health_analytics_custom_module( - parent='parent_value', - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - ) - - # Establish that the 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].security_health_analytics_custom_module - mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value') - assert arg == mock_val - - -def test_create_security_health_analytics_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_health_analytics_custom_module( - securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(), - parent='parent_value', - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_security_health_analytics_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_security_health_analytics_custom_module( - parent='parent_value', - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - ) - - # Establish that 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].security_health_analytics_custom_module - mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_security_health_analytics_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_security_health_analytics_custom_module( - securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(), - parent='parent_value', - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_create_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object - - request = {} - await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_create_source_async_from_dict(): - await test_create_source_async(request_type=dict) - - -def test_create_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.create_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - - -def test_create_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_create_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.create_finding] = mock_rpc - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object - - request = {} - await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_create_finding_async_from_dict(): - await test_create_finding_async(request_type=dict) - - -def test_create_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - arg = args[0].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - - -def test_create_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - arg = args[0].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateMuteConfigRequest, - dict, -]) -def test_create_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - ) - response = client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - - -def test_create_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateMuteConfigRequest() - - -def test_create_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateMuteConfigRequest( - parent='parent_value', - mute_config_id='mute_config_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateMuteConfigRequest( - parent='parent_value', - mute_config_id='mute_config_id_value', - ) - -def test_create_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - request = {} - client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - )) - response = await client.create_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateMuteConfigRequest() - -@pytest.mark.asyncio -async def test_create_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_mute_config] = mock_object - - request = {} - await client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - )) - response = await client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - - -@pytest.mark.asyncio -async def test_create_mute_config_async_from_dict(): - await test_create_mute_config_async(request_type=dict) - - -def test_create_mute_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateMuteConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.create_mute_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_mute_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateMuteConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) - await client.create_mute_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_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_mute_config( - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_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].mute_config - mock_val = gcs_mute_config.MuteConfig(name='name_value') - assert arg == mock_val - arg = args[0].mute_config_id - mock_val = 'mute_config_id_value' - assert arg == mock_val - - -def test_create_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.CreateMuteConfigRequest(), - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_mute_config( - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_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].mute_config - mock_val = gcs_mute_config.MuteConfig(name='name_value') - assert arg == mock_val - arg = args[0].mute_config_id - mock_val = 'mute_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_mute_config( - securitycenter_service.CreateMuteConfigRequest(), - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateNotificationConfigRequest, - dict, -]) -def test_create_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_create_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateNotificationConfigRequest( - parent='parent_value', - config_id='config_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest( - parent='parent_value', - config_id='config_id_value', - ) - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_create_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_notification_config] = mock_object - - request = {} - await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_create_notification_config_async_from_dict(): - await test_create_notification_config_async(request_type=dict) - - -def test_create_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.create_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.create_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_notification_config( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - # Establish that the 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].config_id - mock_val = 'config_id_value' - assert arg == mock_val - arg = args[0].notification_config - mock_val = gcs_notification_config.NotificationConfig(name='name_value') - assert arg == mock_val - - -def test_create_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_notification_config( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - # Establish that 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].config_id - mock_val = 'config_id_value' - assert arg == mock_val - arg = args[0].notification_config - mock_val = gcs_notification_config.NotificationConfig(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_notification_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteMuteConfigRequest, - dict, -]) -def test_delete_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteMuteConfigRequest() - - -def test_delete_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteMuteConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteMuteConfigRequest( - name='name_value', - ) - -def test_delete_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - request = {} - client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteMuteConfigRequest() - -@pytest.mark.asyncio -async def test_delete_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_mute_config] = mock_object - - request = {} - await client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteMuteConfigRequest() - 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_mute_config_async_from_dict(): - await test_delete_mute_config_async(request_type=dict) - - -def test_delete_mute_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteMuteConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value = None - client.delete_mute_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_mute_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteMuteConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_mute_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_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.DeleteMuteConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_mute_config( - securitycenter_service.DeleteMuteConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteNotificationConfigRequest, - dict, -]) -def test_delete_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteNotificationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest( - name='name_value', - ) - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_delete_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_notification_config] = mock_object - - request = {} - await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteNotificationConfigRequest() - 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_config_async_from_dict(): - await test_delete_notification_config_async(request_type=dict) - - -def test_delete_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = None - client.delete_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_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_notification_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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_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_notification_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_notification_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_delete_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_security_health_analytics_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - - -def test_delete_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_security_health_analytics_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest( - name='name_value', - ) - -def test_delete_security_health_analytics_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc - request = {} - client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_security_health_analytics_custom_module(request) - - # Establish that a new wrapper 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_security_health_analytics_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - -@pytest.mark.asyncio -async def test_delete_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_security_health_analytics_custom_module] = mock_object - - request = {} - await client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - 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_security_health_analytics_custom_module_async_from_dict(): - await test_delete_security_health_analytics_custom_module_async(request_type=dict) - - -def test_delete_security_health_analytics_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = None - client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_security_health_analytics_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_security_health_analytics_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__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_security_health_analytics_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_security_health_analytics_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_health_analytics_custom_module( - securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_security_health_analytics_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__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_security_health_analytics_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_security_health_analytics_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_security_health_analytics_custom_module( - securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSimulationRequest, - dict, -]) -def test_get_simulation(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - response = client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSimulationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, simulation.Simulation) - assert response.name == 'name_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -def test_get_simulation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_simulation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSimulationRequest() - - -def test_get_simulation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSimulationRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_simulation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSimulationRequest( - name='name_value', - ) - -def test_get_simulation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_simulation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc - request = {} - client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_simulation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_simulation_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_simulation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSimulationRequest() - -@pytest.mark.asyncio -async def test_get_simulation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_simulation in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_simulation] = mock_object - - request = {} - await client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_simulation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_simulation_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSimulationRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSimulationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, simulation.Simulation) - assert response.name == 'name_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -@pytest.mark.asyncio -async def test_get_simulation_async_from_dict(): - await test_get_simulation_async(request_type=dict) - - -def test_get_simulation_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSimulationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value = simulation.Simulation() - client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_simulation_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSimulationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) - await client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_simulation_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = simulation.Simulation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_simulation( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_simulation_flattened_error(): - client = SecurityCenterClient( - credentials=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_simulation( - securitycenter_service.GetSimulationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_simulation_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = simulation.Simulation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_simulation( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_simulation_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_simulation( - securitycenter_service.GetSimulationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetValuedResourceRequest, - dict, -]) -def test_get_valued_resource(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - ) - response = client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetValuedResourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, valued_resource.ValuedResource) - assert response.name == 'name_value' - assert response.resource == 'resource_value' - assert response.resource_type == 'resource_type_value' - assert response.display_name == 'display_name_value' - assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW - assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) - - -def test_get_valued_resource_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_valued_resource() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetValuedResourceRequest() - - -def test_get_valued_resource_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetValuedResourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_valued_resource(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetValuedResourceRequest( - name='name_value', - ) - -def test_get_valued_resource_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_valued_resource in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc - request = {} - client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_valued_resource(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_valued_resource_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - )) - response = await client.get_valued_resource() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetValuedResourceRequest() - -@pytest.mark.asyncio -async def test_get_valued_resource_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_valued_resource in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_valued_resource] = mock_object - - request = {} - await client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_valued_resource(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_valued_resource_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetValuedResourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - )) - response = await client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetValuedResourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, valued_resource.ValuedResource) - assert response.name == 'name_value' - assert response.resource == 'resource_value' - assert response.resource_type == 'resource_type_value' - assert response.display_name == 'display_name_value' - assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW - assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) - - -@pytest.mark.asyncio -async def test_get_valued_resource_async_from_dict(): - await test_get_valued_resource_async(request_type=dict) - - -def test_get_valued_resource_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetValuedResourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value = valued_resource.ValuedResource() - client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_valued_resource_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetValuedResourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) - await client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_valued_resource_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = valued_resource.ValuedResource() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_valued_resource( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_valued_resource_flattened_error(): - client = SecurityCenterClient( - credentials=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_valued_resource( - securitycenter_service.GetValuedResourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_valued_resource_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = valued_resource.ValuedResource() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_valued_resource( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_valued_resource_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_valued_resource( - securitycenter_service.GetValuedResourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetBigQueryExportRequest, - dict, -]) -def test_get_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - response = client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -def test_get_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetBigQueryExportRequest() - - -def test_get_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetBigQueryExportRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetBigQueryExportRequest( - name='name_value', - ) - -def test_get_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc - request = {} - client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.get_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_get_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_big_query_export] = mock_object - - request = {} - await client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -@pytest.mark.asyncio -async def test_get_big_query_export_async_from_dict(): - await test_get_big_query_export_async(request_type=dict) - - -def test_get_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value = bigquery_export.BigQueryExport() - client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - await client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.GetBigQueryExportRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_big_query_export( - securitycenter_service.GetBigQueryExportRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.GetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest( - resource='resource_value', - ) - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object - - request = {} - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_get_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetMuteConfigRequest, - dict, -]) -def test_get_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - ) - response = client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - - -def test_get_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetMuteConfigRequest() - - -def test_get_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetMuteConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetMuteConfigRequest( - name='name_value', - ) - -def test_get_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_mute_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_mute_config] = mock_rpc - request = {} - client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - )) - response = await client.get_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetMuteConfigRequest() - -@pytest.mark.asyncio -async def test_get_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_mute_config] = mock_object - - request = {} - await client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - )) - response = await client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - - -@pytest.mark.asyncio -async def test_get_mute_config_async_from_dict(): - await test_get_mute_config_async(request_type=dict) - - -def test_get_mute_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetMuteConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value = mute_config.MuteConfig() - client.get_mute_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_mute_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetMuteConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig()) - await client.get_mute_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_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mute_config.MuteConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_mute_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_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.GetMuteConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mute_config.MuteConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_mute_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_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_mute_config( - securitycenter_service.GetMuteConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetNotificationConfigRequest, - dict, -]) -def test_get_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_get_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetNotificationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest( - name='name_value', - ) - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_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_notification_config] = mock_rpc - request = {} - client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_get_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_notification_config] = mock_object - - request = {} - await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_get_notification_config_async_from_dict(): - await test_get_notification_config_async(request_type=dict) - - -def test_get_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = notification_config.NotificationConfig() - client.get_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - await client.get_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_notification_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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_notification_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_notification_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetOrganizationSettingsRequest, - dict, -]) -def test_get_organization_settings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_get_organization_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetOrganizationSettingsRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_organization_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest( - name='name_value', - ) - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_organization_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_organization_settings] = mock_rpc - request = {} - client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_organization_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_organization_settings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - -@pytest.mark.asyncio -async def test_get_organization_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_organization_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_organization_settings] = mock_object - - request = {} - await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_organization_settings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_get_organization_settings_async_from_dict(): - await test_get_organization_settings_async(request_type=dict) - - -def test_get_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = organization_settings.OrganizationSettings() - client.get_organization_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_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - await client.get_organization_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_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_organization_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_organization_settings_flattened_error(): - client = SecurityCenterClient( - credentials=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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_organization_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_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_get_effective_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( - name='name_value', - enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - display_name='display_name_value', - ) - response = client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.enablement_state == effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.display_name == 'display_name_value' - - -def test_get_effective_security_health_analytics_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_effective_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - - -def test_get_effective_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_effective_security_health_analytics_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( - name='name_value', - ) - -def test_get_effective_security_health_analytics_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_effective_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_effective_security_health_analytics_custom_module] = mock_rpc - request = {} - client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_effective_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_effective_security_health_analytics_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( - name='name_value', - enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - display_name='display_name_value', - )) - response = await client.get_effective_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - -@pytest.mark.asyncio -async def test_get_effective_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_effective_security_health_analytics_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_effective_security_health_analytics_custom_module] = mock_object - - request = {} - await client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_effective_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_effective_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( - name='name_value', - enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - display_name='display_name_value', - )) - response = await client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.enablement_state == effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_get_effective_security_health_analytics_custom_module_async_from_dict(): - await test_get_effective_security_health_analytics_custom_module_async(request_type=dict) - - -def test_get_effective_security_health_analytics_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_effective_security_health_analytics_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule()) - await client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_effective_security_health_analytics_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_effective_security_health_analytics_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_effective_security_health_analytics_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_effective_security_health_analytics_custom_module( - securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_effective_security_health_analytics_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_effective_security_health_analytics_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_effective_security_health_analytics_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_effective_security_health_analytics_custom_module( - securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_get_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - ) - response = client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - - -def test_get_security_health_analytics_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - - -def test_get_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_security_health_analytics_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest( - name='name_value', - ) - -def test_get_security_health_analytics_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_security_health_analytics_custom_module] = mock_rpc - request = {} - client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_security_health_analytics_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - )) - response = await client.get_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - -@pytest.mark.asyncio -async def test_get_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_security_health_analytics_custom_module] = mock_object - - request = {} - await client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - )) - response = await client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - - -@pytest.mark.asyncio -async def test_get_security_health_analytics_custom_module_async_from_dict(): - await test_get_security_health_analytics_custom_module_async(request_type=dict) - - -def test_get_security_health_analytics_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_security_health_analytics_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - await client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_security_health_analytics_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_security_health_analytics_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_security_health_analytics_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_health_analytics_custom_module( - securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_security_health_analytics_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_security_health_analytics_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_security_health_analytics_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_security_health_analytics_custom_module( - securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_get_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest( - name='name_value', - ) - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - -@pytest.mark.asyncio -async def test_get_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object - - request = {} - await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_get_source_async_from_dict(): - await test_get_source_async(request_type=dict) - - -def test_get_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = source.Source() - client.get_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_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_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_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_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupAssetsRequest, - dict, -]) -def test_group_assets(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_assets_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - -def test_group_assets_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupAssetsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_assets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_assets_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc - request = {} - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_group_assets_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - -@pytest.mark.asyncio -async def test_group_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_assets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_assets] = mock_object - - request = {} - await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_assets_async_from_dict(): - await test_group_assets_async(request_type=dict) - - -def test_group_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = securitycenter_service.GroupAssetsResponse() - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_group_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) - await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_group_assets_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_assets(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, securitycenter_service.GroupResult) - for i in results) -def test_group_assets_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_assets(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_group_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_assets(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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_assets(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", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - -@pytest.mark.asyncio -async def test_group_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_findings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object - - request = {} - await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_findings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_findings_async_from_dict(): - await test_group_findings_async(request_type=dict) - - -def test_group_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_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_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - await client.group_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_group_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that the 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - - -def test_group_findings_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - -@pytest.mark.asyncio -async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_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, securitycenter_service.GroupResult) - for i in results) -def test_group_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_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_group_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_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", [ - securitycenter_service.ListAssetsRequest, - dict, -]) -def test_list_assets(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_assets_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - -def test_list_assets_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListAssetsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_assets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_value', - page_token='page_token_value', - ) - -def test_list_assets_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc - request = {} - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_assets_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - -@pytest.mark.asyncio -async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_assets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object - - request = {} - await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_assets_async_from_dict(): - await test_list_assets_async(request_type=dict) - - -def test_list_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = securitycenter_service.ListAssetsResponse() - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) - await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_assets_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) -def test_list_assets_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_assets(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_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - 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_assets(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", [ - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, - dict, -]) -def test_list_descendant_security_health_analytics_custom_modules(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_descendant_security_health_analytics_custom_modules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_descendant_security_health_analytics_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - - -def test_list_descendant_security_health_analytics_custom_modules_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( - 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_descendant_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_descendant_security_health_analytics_custom_modules(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_descendant_security_health_analytics_custom_modules_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_descendant_security_health_analytics_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_descendant_security_health_analytics_custom_modules] = mock_rpc - request = {} - client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_descendant_security_health_analytics_custom_modules_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_descendant_security_health_analytics_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - -@pytest.mark.asyncio -async def test_list_descendant_security_health_analytics_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_descendant_security_health_analytics_custom_modules in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_descendant_security_health_analytics_custom_modules] = mock_object - - request = {} - await client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_descendant_security_health_analytics_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_descendant_security_health_analytics_custom_modules_async_from_dict(): - await test_list_descendant_security_health_analytics_custom_modules_async(request_type=dict) - - -def test_list_descendant_security_health_analytics_custom_modules_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_descendant_security_health_analytics_custom_modules_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse()) - await client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_descendant_security_health_analytics_custom_modules_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_descendant_security_health_analytics_custom_modules( - 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_descendant_security_health_analytics_custom_modules_flattened_error(): - client = SecurityCenterClient( - credentials=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_descendant_security_health_analytics_custom_modules( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_descendant_security_health_analytics_custom_modules_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_descendant_security_health_analytics_custom_modules( - 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_descendant_security_health_analytics_custom_modules_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_descendant_security_health_analytics_custom_modules( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_descendant_security_health_analytics_custom_modules_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_descendant_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - for i in results) -def test_list_descendant_security_health_analytics_custom_modules_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_descendant_security_health_analytics_custom_modules(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_descendant_security_health_analytics_custom_modules_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_descendant_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_descendant_security_health_analytics_custom_modules_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - 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_descendant_security_health_analytics_custom_modules(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", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -def test_list_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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] == securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - -@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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object - - request = {} - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -@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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in results) -def test_list_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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 = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_findings_async_pages(): - client = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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", [ - securitycenter_service.ListMuteConfigsRequest, - dict, -]) -def test_list_mute_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListMuteConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMuteConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_mute_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_mute_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListMuteConfigsRequest() - - -def test_list_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListMuteConfigsRequest( - 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_mute_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_mute_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListMuteConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_mute_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_mute_configs] = mock_rpc - request = {} - client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_mute_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_mute_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_mute_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListMuteConfigsRequest() - -@pytest.mark.asyncio -async def test_list_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_mute_configs] = mock_object - - request = {} - await client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_mute_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_mute_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListMuteConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListMuteConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMuteConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_mute_configs_async_from_dict(): - await test_list_mute_configs_async(request_type=dict) - - -def test_list_mute_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListMuteConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListMuteConfigsResponse() - client.list_mute_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_mute_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListMuteConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse()) - await client.list_mute_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_mute_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListMuteConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_mute_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_mute_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_configs( - securitycenter_service.ListMuteConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_mute_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListMuteConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_mute_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_mute_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_mute_configs( - securitycenter_service.ListMuteConfigsRequest(), - parent='parent_value', - ) - - -def test_list_mute_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_mute_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, mute_config.MuteConfig) - for i in results) -def test_list_mute_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_mute_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_mute_configs_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_mute_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, mute_config.MuteConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_mute_configs_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - 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_mute_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", [ - securitycenter_service.ListNotificationConfigsRequest, - dict, -]) -def test_list_notification_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListNotificationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_notification_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListNotificationConfigsRequest( - 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_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notification_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_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_notification_configs] = mock_rpc - request = {} - client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_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_notification_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - -@pytest.mark.asyncio -async def test_list_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_notification_configs] = mock_object - - request = {} - await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_notification_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListNotificationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_from_dict(): - await test_list_notification_configs_async(request_type=dict) - - -def test_list_notification_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - 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_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - client.list_notification_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_notification_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - 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_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - await client.list_notification_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_notification_configs_flattened(): - client = SecurityCenterClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_notification_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_notification_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_notification_configs_flattened_async(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_notification_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_notification_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_notification_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - 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_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, notification_config.NotificationConfig) - for i in results) -def test_list_notification_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_notification_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_notification_configs_async_pager(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_notification_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, notification_config.NotificationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_pages(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - 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_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", [ - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, - dict, -]) -def test_list_effective_security_health_analytics_custom_modules(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_effective_security_health_analytics_custom_modules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_effective_security_health_analytics_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - - -def test_list_effective_security_health_analytics_custom_modules_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( - 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_effective_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_effective_security_health_analytics_custom_modules(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_effective_security_health_analytics_custom_modules_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_effective_security_health_analytics_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_effective_security_health_analytics_custom_modules] = mock_rpc - request = {} - client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_effective_security_health_analytics_custom_modules_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_effective_security_health_analytics_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - -@pytest.mark.asyncio -async def test_list_effective_security_health_analytics_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_effective_security_health_analytics_custom_modules in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_effective_security_health_analytics_custom_modules] = mock_object - - request = {} - await client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_effective_security_health_analytics_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_effective_security_health_analytics_custom_modules_async_from_dict(): - await test_list_effective_security_health_analytics_custom_modules_async(request_type=dict) - - -def test_list_effective_security_health_analytics_custom_modules_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_effective_security_health_analytics_custom_modules_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse()) - await client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_effective_security_health_analytics_custom_modules_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_effective_security_health_analytics_custom_modules( - 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_effective_security_health_analytics_custom_modules_flattened_error(): - client = SecurityCenterClient( - credentials=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_effective_security_health_analytics_custom_modules( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_effective_security_health_analytics_custom_modules_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_effective_security_health_analytics_custom_modules( - 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_effective_security_health_analytics_custom_modules_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_effective_security_health_analytics_custom_modules( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_effective_security_health_analytics_custom_modules_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_effective_security_health_analytics_custom_modules(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, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) - for i in results) -def test_list_effective_security_health_analytics_custom_modules_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_effective_security_health_analytics_custom_modules(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_effective_security_health_analytics_custom_modules_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_effective_security_health_analytics_custom_modules(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, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_effective_security_health_analytics_custom_modules_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - ), - 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_effective_security_health_analytics_custom_modules(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", [ - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, - dict, -]) -def test_list_security_health_analytics_custom_modules(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSecurityHealthAnalyticsCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_security_health_analytics_custom_modules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_security_health_analytics_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - - -def test_list_security_health_analytics_custom_modules_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest( - 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_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_security_health_analytics_custom_modules(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_security_health_analytics_custom_modules_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_security_health_analytics_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_security_health_analytics_custom_modules] = mock_rpc - request = {} - client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_security_health_analytics_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_security_health_analytics_custom_modules_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_security_health_analytics_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - -@pytest.mark.asyncio -async def test_list_security_health_analytics_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_health_analytics_custom_modules in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_security_health_analytics_custom_modules] = mock_object - - request = {} - await client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_security_health_analytics_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_security_health_analytics_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_security_health_analytics_custom_modules_async_from_dict(): - await test_list_security_health_analytics_custom_modules_async(request_type=dict) - - -def test_list_security_health_analytics_custom_modules_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_security_health_analytics_custom_modules_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse()) - await client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_security_health_analytics_custom_modules_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_security_health_analytics_custom_modules( - 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_security_health_analytics_custom_modules_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_health_analytics_custom_modules( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_security_health_analytics_custom_modules_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_security_health_analytics_custom_modules( - 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_security_health_analytics_custom_modules_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_security_health_analytics_custom_modules( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_security_health_analytics_custom_modules_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - for i in results) -def test_list_security_health_analytics_custom_modules_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_security_health_analytics_custom_modules(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_security_health_analytics_custom_modules_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_security_health_analytics_custom_modules_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - 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_security_health_analytics_custom_modules(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", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_sources_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListSourcesRequest( - 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_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - -@pytest.mark.asyncio -async def test_list_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_sources in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object - - request = {} - await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_sources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_sources_async_from_dict(): - await test_list_sources_async(request_type=dict) - - -def test_list_sources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = securitycenter_service.ListSourcesResponse() - client.list_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_sources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - await client.list_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_sources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_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_sources_flattened_error(): - client = SecurityCenterClient( - credentials=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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_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_sources_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_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, source.Source) - for i in results) -def test_list_sources_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = list(client.list_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_sources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_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, source.Source) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - 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_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", [ - securitycenter_service.RunAssetDiscoveryRequest, - dict, -]) -def test_run_asset_discovery(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.RunAssetDiscoveryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_run_asset_discovery_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - -def test_run_asset_discovery_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.RunAssetDiscoveryRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.run_asset_discovery(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest( - parent='parent_value', - ) - -def test_run_asset_discovery_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.run_asset_discovery in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc - request = {} - client.run_asset_discovery(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.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_run_asset_discovery_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - -@pytest.mark.asyncio -async def test_run_asset_discovery_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.run_asset_discovery in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.run_asset_discovery] = mock_object - - request = {} - await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.RunAssetDiscoveryRequest() - 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_run_asset_discovery_async_from_dict(): - await test_run_asset_discovery_async(request_type=dict) - - -def test_run_asset_discovery_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_run_asset_discovery_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_run_asset_discovery_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery( - 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_run_asset_discovery_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_run_asset_discovery_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery( - 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_run_asset_discovery_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_set_finding_state_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - -@pytest.mark.asyncio -async def test_set_finding_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object - - request = {} - await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_finding_state(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_set_finding_state_async_from_dict(): - await test_set_finding_state_async(request_type=dict) - - -def test_set_finding_state_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = finding.Finding() - client.set_finding_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_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_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_set_finding_state_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - - -def test_set_finding_state_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetMuteRequest, - dict, -]) -def test_set_mute(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetMuteRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_set_mute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_mute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetMuteRequest() - - -def test_set_mute_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SetMuteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_mute(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetMuteRequest( - name='name_value', - ) - -def test_set_mute_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_mute in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc - request = {} - client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_mute(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_set_mute_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_mute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetMuteRequest() - -@pytest.mark.asyncio -async def test_set_mute_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_mute in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_mute] = mock_object - - request = {} - await client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_mute(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_mute_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetMuteRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetMuteRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_set_mute_async_from_dict(): - await test_set_mute_async(request_type=dict) - - -def test_set_mute_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetMuteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value = finding.Finding() - client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_mute_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetMuteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_set_mute_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__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.set_mute( - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].mute - mock_val = finding.Finding.Mute.MUTED - assert arg == mock_val - - -def test_set_mute_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_mute( - securitycenter_service.SetMuteRequest(), - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - -@pytest.mark.asyncio -async def test_set_mute_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__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.set_mute( - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].mute - mock_val = finding.Finding.Mute.MUTED - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_mute_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_mute( - securitycenter_service.SetMuteRequest(), - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.SetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest( - resource='resource_value', - ) - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object - - request = {} - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = SecurityCenterClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.TestIamPermissionsRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( - resource='resource_value', - ) - -def test_test_iam_permissions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object - - request = {} - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_simulate_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( - ) - response = client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) - - -def test_simulate_security_health_analytics_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.simulate_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - - -def test_simulate_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.simulate_security_health_analytics_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest( - parent='parent_value', - ) - -def test_simulate_security_health_analytics_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.simulate_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.simulate_security_health_analytics_custom_module] = mock_rpc - request = {} - client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.simulate_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( - )) - response = await client.simulate_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.simulate_security_health_analytics_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.simulate_security_health_analytics_custom_module] = mock_object - - request = {} - await client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.simulate_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( - )) - response = await client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) - - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_async_from_dict(): - await test_simulate_security_health_analytics_custom_module_async(request_type=dict) - - -def test_simulate_security_health_analytics_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse()) - await client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_simulate_security_health_analytics_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.simulate_security_health_analytics_custom_module( - parent='parent_value', - custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), - resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), - ) - - # Establish that the 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].custom_config - mock_val = security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')) - assert arg == mock_val - arg = args[0].resource - mock_val = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value') - assert arg == mock_val - - -def test_simulate_security_health_analytics_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.simulate_security_health_analytics_custom_module( - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(), - parent='parent_value', - custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), - resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), - ) - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.simulate_security_health_analytics_custom_module( - parent='parent_value', - custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), - resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), - ) - - # Establish that 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].custom_config - mock_val = security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')) - assert arg == mock_val - arg = args[0].resource - mock_val = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.simulate_security_health_analytics_custom_module( - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(), - parent='parent_value', - custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), - resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateExternalSystemRequest, - dict, -]) -def test_update_external_system(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - ) - response = client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateExternalSystemRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_external_system.ExternalSystem) - assert response.name == 'name_value' - assert response.assignees == ['assignees_value'] - assert response.external_uid == 'external_uid_value' - assert response.status == 'status_value' - assert response.case_uri == 'case_uri_value' - assert response.case_priority == 'case_priority_value' - - -def test_update_external_system_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_external_system() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateExternalSystemRequest() - - -def test_update_external_system_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateExternalSystemRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_external_system(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateExternalSystemRequest( - ) - -def test_update_external_system_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_external_system in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc - request = {} - client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_external_system(request) - - # Establish that a new wrapper 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_external_system_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - )) - response = await client.update_external_system() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateExternalSystemRequest() - -@pytest.mark.asyncio -async def test_update_external_system_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_external_system in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_external_system] = mock_object - - request = {} - await client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_external_system(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_external_system_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateExternalSystemRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - )) - response = await client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateExternalSystemRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_external_system.ExternalSystem) - assert response.name == 'name_value' - assert response.assignees == ['assignees_value'] - assert response.external_uid == 'external_uid_value' - assert response.status == 'status_value' - assert response.case_uri == 'case_uri_value' - assert response.case_priority == 'case_priority_value' - - -@pytest.mark.asyncio -async def test_update_external_system_async_from_dict(): - await test_update_external_system_async(request_type=dict) - - -def test_update_external_system_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateExternalSystemRequest() - - request.external_system.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value = gcs_external_system.ExternalSystem() - client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'external_system.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_external_system_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateExternalSystemRequest() - - request.external_system.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) - await client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'external_system.name=name_value', - ) in kw['metadata'] - - -def test_update_external_system_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_external_system.ExternalSystem() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_external_system( - external_system=gcs_external_system.ExternalSystem(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].external_system - mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error(): - client = SecurityCenterClient( - credentials=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_external_system( - securitycenter_service.UpdateExternalSystemRequest(), - external_system=gcs_external_system.ExternalSystem(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_external_system_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_external_system.ExternalSystem() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_external_system( - external_system=gcs_external_system.ExternalSystem(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].external_system - mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_external_system( - securitycenter_service.UpdateExternalSystemRequest(), - external_system=gcs_external_system.ExternalSystem(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_update_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateFindingRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.update_finding] = mock_rpc - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object - - request = {} - await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_update_finding_async_from_dict(): - await test_update_finding_async(request_type=dict) - - -def test_update_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -def test_update_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_finding( - finding=gcs_finding.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].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - - -def test_update_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_finding( - finding=gcs_finding.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].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateMuteConfigRequest, - dict, -]) -def test_update_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - ) - response = client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - - -def test_update_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateMuteConfigRequest() - - -def test_update_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateMuteConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateMuteConfigRequest( - ) - -def test_update_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - request = {} - client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - )) - response = await client.update_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateMuteConfigRequest() - -@pytest.mark.asyncio -async def test_update_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_mute_config] = mock_object - - request = {} - await client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - )) - response = await client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - - -@pytest.mark.asyncio -async def test_update_mute_config_async_from_dict(): - await test_update_mute_config_async(request_type=dict) - - -def test_update_mute_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateMuteConfigRequest() - - request.mute_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.update_mute_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', - 'mute_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_mute_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateMuteConfigRequest() - - request.mute_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) - await client.update_mute_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', - 'mute_config.name=name_value', - ) in kw['metadata'] - - -def test_update_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_mute_config( - mute_config=gcs_mute_config.MuteConfig(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].mute_config - mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.UpdateMuteConfigRequest(), - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_mute_config( - mute_config=gcs_mute_config.MuteConfig(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].mute_config - mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_mute_config( - securitycenter_service.UpdateMuteConfigRequest(), - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateNotificationConfigRequest, - dict, -]) -def test_update_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_update_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateNotificationConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest( - ) - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_update_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_notification_config] = mock_object - - request = {} - await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_update_notification_config_async_from_dict(): - await test_update_notification_config_async(request_type=dict) - - -def test_update_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.update_notification_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', - 'notification_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.update_notification_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', - 'notification_config.name=name_value', - ) in kw['metadata'] - - -def test_update_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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].notification_config - mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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].notification_config - mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_notification_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateOrganizationSettingsRequest, - dict, -]) -def test_update_organization_settings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_update_organization_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateOrganizationSettingsRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_organization_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest( - ) - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_organization_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_organization_settings] = mock_rpc - request = {} - client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_organization_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_organization_settings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - -@pytest.mark.asyncio -async def test_update_organization_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_organization_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_organization_settings] = mock_object - - request = {} - await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_organization_settings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_update_organization_settings_async_from_dict(): - await test_update_organization_settings_async(request_type=dict) - - -def test_update_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = gcs_organization_settings.OrganizationSettings() - client.update_organization_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', - 'organization_settings.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - await client.update_organization_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', - 'organization_settings.name=name_value', - ) in kw['metadata'] - - -def test_update_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].organization_settings - mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') - assert arg == mock_val - - -def test_update_organization_settings_flattened_error(): - client = SecurityCenterClient( - credentials=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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].organization_settings - mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_update_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - ) - response = client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - - -def test_update_security_health_analytics_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - - -def test_update_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_health_analytics_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest( - ) - -def test_update_security_health_analytics_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_health_analytics_custom_module] = mock_rpc - request = {} - client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_health_analytics_custom_module(request) - - # Establish that a new wrapper 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_security_health_analytics_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - )) - response = await client.update_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - -@pytest.mark.asyncio -async def test_update_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_security_health_analytics_custom_module] = mock_object - - request = {} - await client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - )) - response = await client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - - -@pytest.mark.asyncio -async def test_update_security_health_analytics_custom_module_async_from_dict(): - await test_update_security_health_analytics_custom_module_async(request_type=dict) - - -def test_update_security_health_analytics_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - - request.security_health_analytics_custom_module.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_health_analytics_custom_module.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_health_analytics_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - - request.security_health_analytics_custom_module.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - await client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_health_analytics_custom_module.name=name_value', - ) in kw['metadata'] - - -def test_update_security_health_analytics_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_health_analytics_custom_module( - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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].security_health_analytics_custom_module - mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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_security_health_analytics_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_health_analytics_custom_module( - securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(), - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_security_health_analytics_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_health_analytics_custom_module( - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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].security_health_analytics_custom_module - mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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_security_health_analytics_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_security_health_analytics_custom_module( - securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(), - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSourceRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object - - request = {} - await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_source_async_from_dict(): - await test_update_source_async(request_type=dict) - - -def test_update_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -def test_update_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_source( - source=gcs_source.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].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - - -def test_update_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_source( - source=gcs_source.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].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - response = client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_security_marks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - -def test_update_security_marks_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSecurityMarksRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( - ) - -def test_update_security_marks_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish that a new wrapper 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_security_marks_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - -@pytest.mark.asyncio -async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_marks in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object - - request = {} - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_security_marks(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_security_marks_async_from_dict(): - await test_update_security_marks_async(request_type=dict) - - -def test_update_security_marks_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -def test_update_security_marks_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].security_marks - mock_val = gcs_security_marks.SecurityMarks(name='name_value') - assert arg == mock_val - - -def test_update_security_marks_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].security_marks - mock_val = gcs_security_marks.SecurityMarks(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateBigQueryExportRequest, - dict, -]) -def test_create_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - response = client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -def test_create_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateBigQueryExportRequest() - - -def test_create_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateBigQueryExportRequest( - parent='parent_value', - big_query_export_id='big_query_export_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateBigQueryExportRequest( - parent='parent_value', - big_query_export_id='big_query_export_id_value', - ) - -def test_create_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - request = {} - client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_big_query_export(request) - - # Establish that a new wrapper 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_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.create_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_create_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_big_query_export] = mock_object - - request = {} - await client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -@pytest.mark.asyncio -async def test_create_big_query_export_async_from_dict(): - await test_create_big_query_export_async(request_type=dict) - - -def test_create_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateBigQueryExportRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value = bigquery_export.BigQueryExport() - client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateBigQueryExportRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - await client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_big_query_export( - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_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].big_query_export - mock_val = bigquery_export.BigQueryExport(name='name_value') - assert arg == mock_val - arg = args[0].big_query_export_id - mock_val = 'big_query_export_id_value' - assert arg == mock_val - - -def test_create_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.CreateBigQueryExportRequest(), - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_id_value', - ) - -@pytest.mark.asyncio -async def test_create_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_big_query_export( - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_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].big_query_export - mock_val = bigquery_export.BigQueryExport(name='name_value') - assert arg == mock_val - arg = args[0].big_query_export_id - mock_val = 'big_query_export_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_big_query_export( - securitycenter_service.CreateBigQueryExportRequest(), - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteBigQueryExportRequest, - dict, -]) -def test_delete_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() - - -def test_delete_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteBigQueryExportRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteBigQueryExportRequest( - name='name_value', - ) - -def test_delete_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - request = {} - client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_big_query_export(request) - - # Establish that a new wrapper 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_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_delete_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_big_query_export] = mock_object - - request = {} - await client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteBigQueryExportRequest() - 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_big_query_export_async_from_dict(): - await test_delete_big_query_export_async(request_type=dict) - - -def test_delete_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value = None - client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__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_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.DeleteBigQueryExportRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__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_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_big_query_export( - securitycenter_service.DeleteBigQueryExportRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateBigQueryExportRequest, - dict, -]) -def test_update_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - response = client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -def test_update_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() - - -def test_update_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateBigQueryExportRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateBigQueryExportRequest( - ) - -def test_update_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc - request = {} - client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_big_query_export(request) - - # Establish that a new wrapper 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_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.update_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_update_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_big_query_export] = mock_object - - request = {} - await client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -@pytest.mark.asyncio -async def test_update_big_query_export_async_from_dict(): - await test_update_big_query_export_async(request_type=dict) - - -def test_update_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateBigQueryExportRequest() - - request.big_query_export.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value = bigquery_export.BigQueryExport() - client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'big_query_export.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateBigQueryExportRequest() - - request.big_query_export.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - await client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'big_query_export.name=name_value', - ) in kw['metadata'] - - -def test_update_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_big_query_export( - big_query_export=bigquery_export.BigQueryExport(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].big_query_export - mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.UpdateBigQueryExportRequest(), - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_big_query_export( - big_query_export=bigquery_export.BigQueryExport(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].big_query_export - mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_big_query_export( - securitycenter_service.UpdateBigQueryExportRequest(), - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListBigQueryExportsRequest, - dict, -]) -def test_list_big_query_exports(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListBigQueryExportsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryExportsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_big_query_exports_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_big_query_exports() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListBigQueryExportsRequest() - - -def test_list_big_query_exports_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListBigQueryExportsRequest( - 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_big_query_exports), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_big_query_exports(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListBigQueryExportsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_big_query_exports_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_big_query_exports in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc - request = {} - client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_big_query_exports(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_big_query_exports_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_big_query_exports() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListBigQueryExportsRequest() - -@pytest.mark.asyncio -async def test_list_big_query_exports_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_exports in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_big_query_exports] = mock_object - - request = {} - await client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_big_query_exports(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_big_query_exports_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListBigQueryExportsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListBigQueryExportsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryExportsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_big_query_exports_async_from_dict(): - await test_list_big_query_exports_async(request_type=dict) - - -def test_list_big_query_exports_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListBigQueryExportsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - call.return_value = securitycenter_service.ListBigQueryExportsResponse() - client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_exports_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListBigQueryExportsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) - await client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_exports_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListBigQueryExportsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_big_query_exports( - 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_big_query_exports_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_exports( - securitycenter_service.ListBigQueryExportsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_big_query_exports_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListBigQueryExportsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_big_query_exports( - 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_big_query_exports_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_big_query_exports( - securitycenter_service.ListBigQueryExportsRequest(), - parent='parent_value', - ) - - -def test_list_big_query_exports_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_big_query_exports(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, bigquery_export.BigQueryExport) - for i in results) -def test_list_big_query_exports_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - RuntimeError, - ) - pages = list(client.list_big_query_exports(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_big_query_exports_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_big_query_exports(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, bigquery_export.BigQueryExport) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_big_query_exports_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - 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_big_query_exports(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", [ - securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_create_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - ) - response = client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - - -def test_create_event_threat_detection_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - - -def test_create_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_event_threat_detection_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateEventThreatDetectionCustomModuleRequest( - parent='parent_value', - ) - -def test_create_event_threat_detection_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc - request = {} - client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_event_threat_detection_custom_module(request) - - # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - )) - response = await client.create_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - -@pytest.mark.asyncio -async def test_create_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_event_threat_detection_custom_module] = mock_object - - request = {} - await client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - )) - response = await client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - - -@pytest.mark.asyncio -async def test_create_event_threat_detection_custom_module_async_from_dict(): - await test_create_event_threat_detection_custom_module_async(request_type=dict) - - -def test_create_event_threat_detection_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_event_threat_detection_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - await client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_event_threat_detection_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_event_threat_detection_custom_module( - parent='parent_value', - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - ) - - # Establish that the 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].event_threat_detection_custom_module - mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value') - assert arg == mock_val - - -def test_create_event_threat_detection_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_event_threat_detection_custom_module( - securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(), - parent='parent_value', - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_event_threat_detection_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_event_threat_detection_custom_module( - parent='parent_value', - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - ) - - # Establish that 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].event_threat_detection_custom_module - mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_event_threat_detection_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_event_threat_detection_custom_module( - securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(), - parent='parent_value', - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_delete_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_event_threat_detection_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - - -def test_delete_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_event_threat_detection_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest( - name='name_value', - ) - -def test_delete_event_threat_detection_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc - request = {} - client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_event_threat_detection_custom_module(request) - - # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - -@pytest.mark.asyncio -async def test_delete_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_event_threat_detection_custom_module] = mock_object - - request = {} - await client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - 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_event_threat_detection_custom_module_async_from_dict(): - await test_delete_event_threat_detection_custom_module_async(request_type=dict) - - -def test_delete_event_threat_detection_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = None - client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_event_threat_detection_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_event_threat_detection_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__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_event_threat_detection_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_event_threat_detection_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_event_threat_detection_custom_module( - securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_event_threat_detection_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__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_event_threat_detection_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_event_threat_detection_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_event_threat_detection_custom_module( - securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_get_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - ) - response = client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - - -def test_get_event_threat_detection_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - - -def test_get_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_event_threat_detection_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEventThreatDetectionCustomModuleRequest( - name='name_value', - ) - -def test_get_event_threat_detection_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_event_threat_detection_custom_module] = mock_rpc - request = {} - client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_event_threat_detection_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - )) - response = await client.get_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - -@pytest.mark.asyncio -async def test_get_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_event_threat_detection_custom_module] = mock_object - - request = {} - await client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetEventThreatDetectionCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - )) - response = await client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - - -@pytest.mark.asyncio -async def test_get_event_threat_detection_custom_module_async_from_dict(): - await test_get_event_threat_detection_custom_module_async(request_type=dict) - - -def test_get_event_threat_detection_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_event_threat_detection_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - await client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_event_threat_detection_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_event_threat_detection_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_event_threat_detection_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_event_threat_detection_custom_module( - securitycenter_service.GetEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_event_threat_detection_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_event_threat_detection_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_event_threat_detection_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_event_threat_detection_custom_module( - securitycenter_service.GetEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, - dict, -]) -def test_list_descendant_event_threat_detection_custom_modules(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDescendantEventThreatDetectionCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_descendant_event_threat_detection_custom_modules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_descendant_event_threat_detection_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - - -def test_list_descendant_event_threat_detection_custom_modules_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest( - 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_descendant_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_descendant_event_threat_detection_custom_modules(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_descendant_event_threat_detection_custom_modules_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_descendant_event_threat_detection_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_descendant_event_threat_detection_custom_modules] = mock_rpc - request = {} - client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_descendant_event_threat_detection_custom_modules_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_descendant_event_threat_detection_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - -@pytest.mark.asyncio -async def test_list_descendant_event_threat_detection_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_descendant_event_threat_detection_custom_modules in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_descendant_event_threat_detection_custom_modules] = mock_object - - request = {} - await client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_descendant_event_threat_detection_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_descendant_event_threat_detection_custom_modules_async_from_dict(): - await test_list_descendant_event_threat_detection_custom_modules_async(request_type=dict) - - -def test_list_descendant_event_threat_detection_custom_modules_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_descendant_event_threat_detection_custom_modules_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse()) - await client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_descendant_event_threat_detection_custom_modules_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_descendant_event_threat_detection_custom_modules( - 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_descendant_event_threat_detection_custom_modules_flattened_error(): - client = SecurityCenterClient( - credentials=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_descendant_event_threat_detection_custom_modules( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_descendant_event_threat_detection_custom_modules_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_descendant_event_threat_detection_custom_modules( - 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_descendant_event_threat_detection_custom_modules_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_descendant_event_threat_detection_custom_modules( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_descendant_event_threat_detection_custom_modules_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_descendant_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - for i in results) -def test_list_descendant_event_threat_detection_custom_modules_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_descendant_event_threat_detection_custom_modules(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_descendant_event_threat_detection_custom_modules_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_descendant_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_descendant_event_threat_detection_custom_modules_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - 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_descendant_event_threat_detection_custom_modules(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", [ - securitycenter_service.ListEventThreatDetectionCustomModulesRequest, - dict, -]) -def test_list_event_threat_detection_custom_modules(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEventThreatDetectionCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_event_threat_detection_custom_modules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_event_threat_detection_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - - -def test_list_event_threat_detection_custom_modules_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest( - 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_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_event_threat_detection_custom_modules(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEventThreatDetectionCustomModulesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_event_threat_detection_custom_modules_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_event_threat_detection_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_event_threat_detection_custom_modules] = mock_rpc - request = {} - client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_event_threat_detection_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_event_threat_detection_custom_modules_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_event_threat_detection_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - -@pytest.mark.asyncio -async def test_list_event_threat_detection_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_event_threat_detection_custom_modules in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_event_threat_detection_custom_modules] = mock_object - - request = {} - await client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_event_threat_detection_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_event_threat_detection_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListEventThreatDetectionCustomModulesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEventThreatDetectionCustomModulesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_event_threat_detection_custom_modules_async_from_dict(): - await test_list_event_threat_detection_custom_modules_async(request_type=dict) - - -def test_list_event_threat_detection_custom_modules_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_event_threat_detection_custom_modules_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse()) - await client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_event_threat_detection_custom_modules_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_event_threat_detection_custom_modules( - 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_event_threat_detection_custom_modules_flattened_error(): - client = SecurityCenterClient( - credentials=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_event_threat_detection_custom_modules( - securitycenter_service.ListEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_event_threat_detection_custom_modules_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_event_threat_detection_custom_modules( - 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_event_threat_detection_custom_modules_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_event_threat_detection_custom_modules( - securitycenter_service.ListEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_event_threat_detection_custom_modules_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - for i in results) -def test_list_event_threat_detection_custom_modules_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_event_threat_detection_custom_modules(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_event_threat_detection_custom_modules_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_event_threat_detection_custom_modules_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - 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_event_threat_detection_custom_modules(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", [ - securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_update_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - ) - response = client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - - -def test_update_event_threat_detection_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - - -def test_update_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_event_threat_detection_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest( - ) - -def test_update_event_threat_detection_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_event_threat_detection_custom_module] = mock_rpc - request = {} - client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_event_threat_detection_custom_module(request) - - # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - )) - response = await client.update_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - -@pytest.mark.asyncio -async def test_update_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_event_threat_detection_custom_module] = mock_object - - request = {} - await client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - )) - response = await client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - - -@pytest.mark.asyncio -async def test_update_event_threat_detection_custom_module_async_from_dict(): - await test_update_event_threat_detection_custom_module_async(request_type=dict) - - -def test_update_event_threat_detection_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - - request.event_threat_detection_custom_module.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'event_threat_detection_custom_module.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_event_threat_detection_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - - request.event_threat_detection_custom_module.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - await client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'event_threat_detection_custom_module.name=name_value', - ) in kw['metadata'] - - -def test_update_event_threat_detection_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_event_threat_detection_custom_module( - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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].event_threat_detection_custom_module - mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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_event_threat_detection_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_event_threat_detection_custom_module( - securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(), - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_event_threat_detection_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_event_threat_detection_custom_module( - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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].event_threat_detection_custom_module - mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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_event_threat_detection_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_event_threat_detection_custom_module( - securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(), - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_validate_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( - ) - response = client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) - - -def test_validate_event_threat_detection_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.validate_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - - -def test_validate_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest( - parent='parent_value', - raw_text='raw_text_value', - type_='type__value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.validate_event_threat_detection_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest( - parent='parent_value', - raw_text='raw_text_value', - type_='type__value', - ) - -def test_validate_event_threat_detection_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc - request = {} - client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.validate_event_threat_detection_custom_module(request) - - # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( - )) - response = await client.validate_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - -@pytest.mark.asyncio -async def test_validate_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.validate_event_threat_detection_custom_module] = mock_object - - request = {} - await client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.validate_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_validate_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( - )) - response = await client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) - - -@pytest.mark.asyncio -async def test_validate_event_threat_detection_custom_module_async_from_dict(): - await test_validate_event_threat_detection_custom_module_async(request_type=dict) - - -def test_validate_event_threat_detection_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() - client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_validate_event_threat_detection_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse()) - await client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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", [ - securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_get_effective_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( - name='name_value', - enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - ) - response = client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.enablement_state == effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_get_effective_event_threat_detection_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_effective_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - - -def test_get_effective_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_effective_event_threat_detection_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest( - name='name_value', - ) - -def test_get_effective_event_threat_detection_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_effective_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_effective_event_threat_detection_custom_module] = mock_rpc - request = {} - client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_effective_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_effective_event_threat_detection_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( - name='name_value', - enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_effective_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - -@pytest.mark.asyncio -async def test_get_effective_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_effective_event_threat_detection_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_effective_event_threat_detection_custom_module] = mock_object - - request = {} - await client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_effective_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_effective_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( - name='name_value', - enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.enablement_state == effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_get_effective_event_threat_detection_custom_module_async_from_dict(): - await test_get_effective_event_threat_detection_custom_module_async(request_type=dict) - - -def test_get_effective_event_threat_detection_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_effective_event_threat_detection_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule()) - await client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_effective_event_threat_detection_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_effective_event_threat_detection_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_effective_event_threat_detection_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_effective_event_threat_detection_custom_module( - securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_effective_event_threat_detection_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_effective_event_threat_detection_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_effective_event_threat_detection_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_effective_event_threat_detection_custom_module( - securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, - dict, -]) -def test_list_effective_event_threat_detection_custom_modules(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEffectiveEventThreatDetectionCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_effective_event_threat_detection_custom_modules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_effective_event_threat_detection_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - - -def test_list_effective_event_threat_detection_custom_modules_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest( - 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_effective_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_effective_event_threat_detection_custom_modules(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_effective_event_threat_detection_custom_modules_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_effective_event_threat_detection_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_effective_event_threat_detection_custom_modules] = mock_rpc - request = {} - client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_effective_event_threat_detection_custom_modules_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_effective_event_threat_detection_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - -@pytest.mark.asyncio -async def test_list_effective_event_threat_detection_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_effective_event_threat_detection_custom_modules in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_effective_event_threat_detection_custom_modules] = mock_object - - request = {} - await client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_effective_event_threat_detection_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEffectiveEventThreatDetectionCustomModulesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_effective_event_threat_detection_custom_modules_async_from_dict(): - await test_list_effective_event_threat_detection_custom_modules_async(request_type=dict) - - -def test_list_effective_event_threat_detection_custom_modules_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_effective_event_threat_detection_custom_modules_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse()) - await client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_effective_event_threat_detection_custom_modules_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_effective_event_threat_detection_custom_modules( - 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_effective_event_threat_detection_custom_modules_flattened_error(): - client = SecurityCenterClient( - credentials=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_effective_event_threat_detection_custom_modules( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_effective_event_threat_detection_custom_modules_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_effective_event_threat_detection_custom_modules( - 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_effective_event_threat_detection_custom_modules_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_effective_event_threat_detection_custom_modules( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_effective_event_threat_detection_custom_modules_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_effective_event_threat_detection_custom_modules(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, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) - for i in results) -def test_list_effective_event_threat_detection_custom_modules_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_effective_event_threat_detection_custom_modules(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_effective_event_threat_detection_custom_modules_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_effective_event_threat_detection_custom_modules(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, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_effective_event_threat_detection_custom_modules_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - ), - 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_effective_event_threat_detection_custom_modules(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", [ - securitycenter_service.BatchCreateResourceValueConfigsRequest, - dict, -]) -def test_batch_create_resource_value_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse( - ) - response = client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) - - -def test_batch_create_resource_value_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_create_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() - - -def test_batch_create_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.BatchCreateResourceValueConfigsRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_create_resource_value_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest( - parent='parent_value', - ) - -def test_batch_create_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc - request = {} - client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_resource_value_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_batch_create_resource_value_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( - )) - response = await client.batch_create_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() - -@pytest.mark.asyncio -async def test_batch_create_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.batch_create_resource_value_configs] = mock_object - - request = {} - await client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.batch_create_resource_value_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( - )) - response = await client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) - - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_async_from_dict(): - await test_batch_create_resource_value_configs_async(request_type=dict) - - -def test_batch_create_resource_value_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - client.batch_create_resource_value_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_batch_create_resource_value_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) - await client.batch_create_resource_value_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_batch_create_resource_value_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.batch_create_resource_value_configs( - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(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 - arg = args[0].requests - mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] - assert arg == mock_val - - -def test_batch_create_resource_value_configs_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_create_resource_value_configs( - securitycenter_service.BatchCreateResourceValueConfigsRequest(), - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], - ) - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_create_resource_value_configs( - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(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 - arg = args[0].requests - mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.batch_create_resource_value_configs( - securitycenter_service.BatchCreateResourceValueConfigsRequest(), - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteResourceValueConfigRequest, - dict, -]) -def test_delete_resource_value_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_resource_value_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() - - -def test_delete_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteResourceValueConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_resource_value_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest( - name='name_value', - ) - -def test_delete_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - request = {} - client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_resource_value_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_resource_value_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() - -@pytest.mark.asyncio -async def test_delete_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_resource_value_config] = mock_object - - request = {} - await client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_resource_value_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteResourceValueConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteResourceValueConfigRequest() - 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_resource_value_config_async_from_dict(): - await test_delete_resource_value_config_async(request_type=dict) - - -def test_delete_resource_value_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value = None - client.delete_resource_value_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_resource_value_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_resource_value_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_resource_value_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_config( - securitycenter_service.DeleteResourceValueConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_resource_value_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_resource_value_config( - securitycenter_service.DeleteResourceValueConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetResourceValueConfigRequest, - dict, -]) -def test_get_resource_value_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - response = client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -def test_get_resource_value_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetResourceValueConfigRequest() - - -def test_get_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetResourceValueConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_resource_value_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetResourceValueConfigRequest( - name='name_value', - ) - -def test_get_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc - request = {} - client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_resource_value_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_resource_value_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetResourceValueConfigRequest() - -@pytest.mark.asyncio -async def test_get_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_resource_value_config] = mock_object - - request = {} - await client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_resource_value_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetResourceValueConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -@pytest.mark.asyncio -async def test_get_resource_value_config_async_from_dict(): - await test_get_resource_value_config_async(request_type=dict) - - -def test_get_resource_value_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value = resource_value_config.ResourceValueConfig() - client.get_resource_value_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_resource_value_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) - await client.get_resource_value_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_resource_value_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resource_value_config.ResourceValueConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_resource_value_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_resource_value_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_config( - securitycenter_service.GetResourceValueConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_resource_value_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resource_value_config.ResourceValueConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_resource_value_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_resource_value_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_resource_value_config( - securitycenter_service.GetResourceValueConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListResourceValueConfigsRequest, - dict, -]) -def test_list_resource_value_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceValueConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_resource_value_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() - - -def test_list_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListResourceValueConfigsRequest( - 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_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_resource_value_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListResourceValueConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc - request = {} - client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_resource_value_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_resource_value_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() - -@pytest.mark.asyncio -async def test_list_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_resource_value_configs] = mock_object - - request = {} - await client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_resource_value_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListResourceValueConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceValueConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_resource_value_configs_async_from_dict(): - await test_list_resource_value_configs_async(request_type=dict) - - -def test_list_resource_value_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListResourceValueConfigsResponse() - client.list_resource_value_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_resource_value_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) - await client.list_resource_value_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_resource_value_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListResourceValueConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_resource_value_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_resource_value_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_configs( - securitycenter_service.ListResourceValueConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_resource_value_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListResourceValueConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_resource_value_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_resource_value_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_resource_value_configs( - securitycenter_service.ListResourceValueConfigsRequest(), - parent='parent_value', - ) - - -def test_list_resource_value_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_resource_value_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, resource_value_config.ResourceValueConfig) - for i in results) -def test_list_resource_value_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_resource_value_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_resource_value_configs_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_resource_value_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, resource_value_config.ResourceValueConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_resource_value_configs_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - 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_resource_value_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", [ - securitycenter_service.UpdateResourceValueConfigRequest, - dict, -]) -def test_update_resource_value_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - response = client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -def test_update_resource_value_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() - - -def test_update_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateResourceValueConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_resource_value_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest( - ) - -def test_update_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - request = {} - client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_resource_value_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_resource_value_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.update_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() - -@pytest.mark.asyncio -async def test_update_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_resource_value_config] = mock_object - - request = {} - await client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_resource_value_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateResourceValueConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -@pytest.mark.asyncio -async def test_update_resource_value_config_async_from_dict(): - await test_update_resource_value_config_async(request_type=dict) - - -def test_update_resource_value_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateResourceValueConfigRequest() - - request.resource_value_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value = gcs_resource_value_config.ResourceValueConfig() - client.update_resource_value_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', - 'resource_value_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_resource_value_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateResourceValueConfigRequest() - - request.resource_value_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) - await client.update_resource_value_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', - 'resource_value_config.name=name_value', - ) in kw['metadata'] - - -def test_update_resource_value_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_resource_value_config.ResourceValueConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_resource_value_config( - resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config - mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_config( - securitycenter_service.UpdateResourceValueConfigRequest(), - resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_resource_value_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_resource_value_config.ResourceValueConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_resource_value_config( - resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config - mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_resource_value_config( - securitycenter_service.UpdateResourceValueConfigRequest(), - resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListValuedResourcesRequest, - dict, -]) -def test_list_valued_resources(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListValuedResourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListValuedResourcesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_valued_resources_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_valued_resources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListValuedResourcesRequest() - - -def test_list_valued_resources_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListValuedResourcesRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_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_valued_resources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_valued_resources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListValuedResourcesRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_value', - order_by='order_by_value', - ) - -def test_list_valued_resources_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_valued_resources in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc - request = {} - client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_valued_resources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_valued_resources_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_valued_resources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListValuedResourcesRequest() - -@pytest.mark.asyncio -async def test_list_valued_resources_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_valued_resources in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_valued_resources] = mock_object - - request = {} - await client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_valued_resources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_valued_resources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListValuedResourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListValuedResourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListValuedResourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_valued_resources_async_from_dict(): - await test_list_valued_resources_async(request_type=dict) - - -def test_list_valued_resources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListValuedResourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - call.return_value = securitycenter_service.ListValuedResourcesResponse() - client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_valued_resources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListValuedResourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) - await client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_valued_resources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListValuedResourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_valued_resources( - 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_valued_resources_flattened_error(): - client = SecurityCenterClient( - credentials=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_valued_resources( - securitycenter_service.ListValuedResourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_valued_resources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListValuedResourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_valued_resources( - 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_valued_resources_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_valued_resources( - securitycenter_service.ListValuedResourcesRequest(), - parent='parent_value', - ) - - -def test_list_valued_resources_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_valued_resources(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, valued_resource.ValuedResource) - for i in results) -def test_list_valued_resources_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - RuntimeError, - ) - pages = list(client.list_valued_resources(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_valued_resources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_valued_resources(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, valued_resource.ValuedResource) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_valued_resources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - 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_valued_resources(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", [ - securitycenter_service.ListAttackPathsRequest, - dict, -]) -def test_list_attack_paths(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAttackPathsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttackPathsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_attack_paths_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_attack_paths() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAttackPathsRequest() - - -def test_list_attack_paths_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListAttackPathsRequest( - 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_attack_paths), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_attack_paths(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAttackPathsRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_value', - ) - -def test_list_attack_paths_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_attack_paths in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc - request = {} - client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_attack_paths(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_attack_paths_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_attack_paths() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAttackPathsRequest() - -@pytest.mark.asyncio -async def test_list_attack_paths_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_attack_paths in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_attack_paths] = mock_object - - request = {} - await client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_attack_paths(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_attack_paths_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAttackPathsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAttackPathsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttackPathsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_attack_paths_async_from_dict(): - await test_list_attack_paths_async(request_type=dict) - - -def test_list_attack_paths_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAttackPathsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - call.return_value = securitycenter_service.ListAttackPathsResponse() - client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_attack_paths_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAttackPathsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) - await client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_attack_paths_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAttackPathsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_attack_paths( - 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_attack_paths_flattened_error(): - client = SecurityCenterClient( - credentials=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_attack_paths( - securitycenter_service.ListAttackPathsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_attack_paths_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAttackPathsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_attack_paths( - 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_attack_paths_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_attack_paths( - securitycenter_service.ListAttackPathsRequest(), - parent='parent_value', - ) - - -def test_list_attack_paths_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_attack_paths(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, attack_path.AttackPath) - for i in results) -def test_list_attack_paths_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - RuntimeError, - ) - pages = list(client.list_attack_paths(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_attack_paths_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_attack_paths(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, attack_path.AttackPath) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_attack_paths_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - 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_attack_paths(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", [ - securitycenter_service.BulkMuteFindingsRequest, - dict, -]) -def test_bulk_mute_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') - - # 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 - response = client.bulk_mute_findings(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_bulk_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc - - request = {} - client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_rest_required_fields(request_type=securitycenter_service.BulkMuteFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).bulk_mute_findings._get_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()).bulk_mute_findings._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 = SecurityCenterClient( - 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.bulk_mute_findings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_bulk_mute_findings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.bulk_mute_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_bulk_mute_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_bulk_mute_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_bulk_mute_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.BulkMuteFindingsRequest.pb(securitycenter_service.BulkMuteFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = securitycenter_service.BulkMuteFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.bulk_mute_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_bulk_mute_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BulkMuteFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.bulk_mute_findings(request) - - -def test_bulk_mute_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.bulk_mute_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/v1/{parent=organizations/*}/findings:bulkMute" % client.transport._host, args[1]) - - -def test_bulk_mute_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.bulk_mute_findings( - securitycenter_service.BulkMuteFindingsRequest(), - parent='parent_value', - ) - - -def test_bulk_mute_findings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_create_security_health_analytics_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request_init["security_health_analytics_custom_module"] = {'name': 'name_value', 'display_name': 'display_name_value', 'enablement_state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_value', 'ancestor_module': 'ancestor_module_value', 'custom_config': {'predicate': {'expression': 'expression_value', 'title': 'title_value', 'description': 'description_value', 'location': 'location_value'}, 'custom_output': {'properties': [{'name': 'name_value', 'value_expression': {}}]}, 'resource_selector': {'resource_types': ['resource_types_value1', 'resource_types_value2']}, 'severity': 1, 'description': 'description_value', 'recommendation': 'recommendation_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 = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.meta.fields["security_health_analytics_custom_module"] - - 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["security_health_analytics_custom_module"].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["security_health_analytics_custom_module"][field])): - del request_init["security_health_analytics_custom_module"][field][i][subfield] - else: - del request_init["security_health_analytics_custom_module"][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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) - 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_security_health_analytics_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - -def test_create_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc - - request = {} - client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_security_health_analytics_custom_module(request) - - # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_security_health_analytics_custom_module._get_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_security_health_analytics_custom_module._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) - 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_security_health_analytics_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_security_health_analytics_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_security_health_analytics_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "securityHealthAnalyticsCustomModule", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_security_health_analytics_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_security_health_analytics_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_security_health_analytics_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.to_json(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - client.create_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_security_health_analytics_custom_module(request) - - -def test_create_security_health_analytics_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(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_security_health_analytics_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules" % client.transport._host, args[1]) - - -def test_create_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_health_analytics_custom_module( - securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(), - parent='parent_value', - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - ) - - -def test_create_security_health_analytics_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.CreateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_source(request) - - -def test_create_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_create_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -def test_create_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request_init["finding"] = {'name': 'name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_value', 'mute': 1, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.create_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.create_finding] = mock_rpc - - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["finding_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 "findingId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "findingId" in jsonified_request - assert jsonified_request["findingId"] == request_init["finding_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["findingId"] = 'finding_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request - assert jsonified_request["findingId"] == 'finding_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.create_finding(request) - - expected_params = [ - ( - "findingId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.CreateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_finding(request) - - -def test_create_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(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 = gcs_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.create_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/v1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) - - -def test_create_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_create_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateMuteConfigRequest, - dict, -]) -def test_create_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["mute_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_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 = securitycenter_service.CreateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): - del request_init["mute_config"][field][i][subfield] - else: - del request_init["mute_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 = gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - -def test_create_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - - request = {} - client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.CreateMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["mute_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 "muteConfigId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "muteConfigId" in jsonified_request - assert jsonified_request["muteConfigId"] == request_init["mute_config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["muteConfigId"] = 'mute_config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("mute_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 "muteConfigId" in jsonified_request - assert jsonified_request["muteConfigId"] == 'mute_config_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - expected_params = [ - ( - "muteConfigId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("muteConfigId", )) & set(("parent", "muteConfig", "muteConfigId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_mute_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_mute_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateMuteConfigRequest.pb(securitycenter_service.CreateMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) - - request = securitycenter_service.CreateMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_mute_config.MuteConfig() - - client.create_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_mute_config(request) - - -def test_create_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_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 = gcs_mute_config.MuteConfig.pb(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_mute_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=organizations/*}/muteConfigs" % client.transport._host, args[1]) - - -def test_create_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.CreateMuteConfigRequest(), - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_id_value', - ) - - -def test_create_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateNotificationConfigRequest, - dict, -]) -def test_create_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["notification_config"] = {'name': 'name_value', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.CreateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): - del request_init["notification_config"][field][i][subfield] - else: - del request_init["notification_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 = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.CreateNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["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 "configId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "configId" in jsonified_request - assert jsonified_request["configId"] == request_init["config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["configId"] = 'config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("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 "configId" in jsonified_request - assert jsonified_request["configId"] == 'config_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ( - "configId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("configId", )) & set(("parent", "configId", "notificationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateNotificationConfigRequest.pb(securitycenter_service.CreateNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) - - request = securitycenter_service.CreateNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_notification_config.NotificationConfig() - - client.create_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_notification_config(request) - - -def test_create_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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=organizations/*}/notificationConfigs" % client.transport._host, args[1]) - - -def test_create_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - -def test_create_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteMuteConfigRequest, - dict, -]) -def test_delete_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/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 = 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - - request = {} - client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.DeleteMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( - 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_mute_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_mute_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteMuteConfigRequest.pb(securitycenter_service.DeleteMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_mute_config(request) - - -def test_delete_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/muteConfigs/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_mute_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=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.DeleteMuteConfigRequest(), - name='name_value', - ) - - -def test_delete_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteNotificationConfigRequest, - dict, -]) -def test_delete_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/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 = 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_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.DeleteNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_notification_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteNotificationConfigRequest.pb(securitycenter_service.DeleteNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_notification_config(request) - - -def test_delete_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/notificationConfigs/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_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=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -def test_delete_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_delete_security_health_analytics_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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 = 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_security_health_analytics_custom_module(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc - - request = {} - client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_security_health_analytics_custom_module(request) - - # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - 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_security_health_analytics_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_security_health_analytics_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_security_health_analytics_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_security_health_analytics_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_security_health_analytics_custom_module") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_security_health_analytics_custom_module(request) - - -def test_delete_security_health_analytics_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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_security_health_analytics_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings/customModules/*}" % client.transport._host, args[1]) - - -def test_delete_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_health_analytics_custom_module( - securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - - -def test_delete_security_health_analytics_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSimulationRequest, - dict, -]) -def test_get_simulation_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = simulation.Simulation.pb(return_value) - 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_simulation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, simulation.Simulation) - assert response.name == 'name_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - -def test_get_simulation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_simulation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc - - request = {} - client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_simulation(request) - - # Establish 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_simulation_rest_required_fields(request_type=securitycenter_service.GetSimulationRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_simulation._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_simulation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = simulation.Simulation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = simulation.Simulation.pb(return_value) - 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_simulation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_simulation_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_simulation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_simulation_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_simulation") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_simulation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSimulationRequest.pb(securitycenter_service.GetSimulationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = simulation.Simulation.to_json(simulation.Simulation()) - - request = securitycenter_service.GetSimulationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = simulation.Simulation() - - client.get_simulation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_simulation_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSimulationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_simulation(request) - - -def test_get_simulation_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = simulation.Simulation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation.pb(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_simulation(**mock_args) - - # Establish that the underlying call 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=organizations/*/simulations/*}" % client.transport._host, args[1]) - - -def test_get_simulation_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_simulation( - securitycenter_service.GetSimulationRequest(), - name='name_value', - ) - - -def test_get_simulation_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetValuedResourceRequest, - dict, -]) -def test_get_valued_resource_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = valued_resource.ValuedResource.pb(return_value) - 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_valued_resource(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, valued_resource.ValuedResource) - assert response.name == 'name_value' - assert response.resource == 'resource_value' - assert response.resource_type == 'resource_type_value' - assert response.display_name == 'display_name_value' - assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW - assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) - -def test_get_valued_resource_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_valued_resource in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc - - request = {} - client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_valued_resource(request) - - # Establish 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_valued_resource_rest_required_fields(request_type=securitycenter_service.GetValuedResourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_valued_resource._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_valued_resource._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = valued_resource.ValuedResource() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = valued_resource.ValuedResource.pb(return_value) - 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_valued_resource(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_valued_resource_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_valued_resource._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_valued_resource_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_valued_resource") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_valued_resource") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetValuedResourceRequest.pb(securitycenter_service.GetValuedResourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = valued_resource.ValuedResource.to_json(valued_resource.ValuedResource()) - - request = securitycenter_service.GetValuedResourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = valued_resource.ValuedResource() - - client.get_valued_resource(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_valued_resource_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetValuedResourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_valued_resource(request) - - -def test_get_valued_resource_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = valued_resource.ValuedResource() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource.pb(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_valued_resource(**mock_args) - - # Establish that the underlying call 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=organizations/*/simulations/*/valuedResources/*}" % client.transport._host, args[1]) - - -def test_get_valued_resource_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_valued_resource( - securitycenter_service.GetValuedResourceRequest(), - name='name_value', - ) - - -def test_get_valued_resource_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetBigQueryExportRequest, - dict, -]) -def test_get_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/bigQueryExports/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 = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - -def test_get_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc - - request = {} - client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.GetBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_big_query_export") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_big_query_export") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetBigQueryExportRequest.pb(securitycenter_service.GetBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) - - request = securitycenter_service.GetBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = bigquery_export.BigQueryExport() - - client.get_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/bigQueryExports/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_big_query_export(request) - - -def test_get_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/bigQueryExports/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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) - - # Establish that the underlying call 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=organizations/*/bigQueryExports/*}" % client.transport._host, args[1]) - - -def test_get_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.GetBigQueryExportRequest(), - name='name_value', - ) - - -def test_get_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.get_iam_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/v1/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetMuteConfigRequest, - dict, -]) -def test_get_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - -def test_get_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_mute_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_mute_config] = mock_rpc - - request = {} - client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.GetMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = mute_config.MuteConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_mute_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_mute_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetMuteConfigRequest.pb(securitycenter_service.GetMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = mute_config.MuteConfig.to_json(mute_config.MuteConfig()) - - request = securitycenter_service.GetMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = mute_config.MuteConfig() - - client.get_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_mute_config(request) - - -def test_get_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = mute_config.MuteConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig.pb(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_mute_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=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) - - -def test_get_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.GetMuteConfigRequest(), - name='name_value', - ) - - -def test_get_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetNotificationConfigRequest, - dict, -]) -def test_get_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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_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_notification_config] = mock_rpc - - request = {} - client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.GetNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetNotificationConfigRequest.pb(securitycenter_service.GetNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = notification_config.NotificationConfig.to_json(notification_config.NotificationConfig()) - - request = securitycenter_service.GetNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = notification_config.NotificationConfig() - - client.get_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_notification_config(request) - - -def test_get_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig.pb(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_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=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_get_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -def test_get_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetOrganizationSettingsRequest, - dict, -]) -def test_get_organization_settings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/organizationSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_organization_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_organization_settings] = mock_rpc - - request = {} - client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.GetOrganizationSettingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_organization_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_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_organization_settings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_organization_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_organization_settings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_organization_settings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_organization_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetOrganizationSettingsRequest.pb(securitycenter_service.GetOrganizationSettingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = organization_settings.OrganizationSettings.to_json(organization_settings.OrganizationSettings()) - - request = securitycenter_service.GetOrganizationSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = organization_settings.OrganizationSettings() - - client.get_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/organizationSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_organization_settings(request) - - -def test_get_organization_settings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/organizationSettings'} - - # get truthy value for each flattened field - mock_args = dict( - 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 = organization_settings.OrganizationSettings.pb(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_organization_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/v1/{name=organizations/*/organizationSettings}" % client.transport._host, args[1]) - - -def test_get_organization_settings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -def test_get_organization_settings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_get_effective_security_health_analytics_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/effectiveCustomModules/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 = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( - name='name_value', - enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - display_name='display_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(return_value) - 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_effective_security_health_analytics_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.enablement_state == effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.display_name == 'display_name_value' - -def test_get_effective_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_effective_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_effective_security_health_analytics_custom_module] = mock_rpc - - request = {} - client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_effective_security_health_analytics_custom_module(request) - - # Establish 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_effective_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_effective_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_effective_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(return_value) - 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_effective_security_health_analytics_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_effective_security_health_analytics_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_effective_security_health_analytics_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_effective_security_health_analytics_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_effective_security_health_analytics_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_effective_security_health_analytics_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.to_json(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule()) - - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - - client.get_effective_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_effective_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/effectiveCustomModules/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_effective_security_health_analytics_custom_module(request) - - -def test_get_effective_security_health_analytics_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/effectiveCustomModules/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 = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(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_effective_security_health_analytics_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}" % client.transport._host, args[1]) - - -def test_get_effective_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_effective_security_health_analytics_custom_module( - securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - - -def test_get_effective_security_health_analytics_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_get_security_health_analytics_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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 = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) - 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_security_health_analytics_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - -def test_get_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_security_health_analytics_custom_module] = mock_rpc - - request = {} - client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_security_health_analytics_custom_module(request) - - # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) - 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_security_health_analytics_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_security_health_analytics_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_security_health_analytics_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_security_health_analytics_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_security_health_analytics_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_security_health_analytics_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.to_json(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - client.get_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_security_health_analytics_custom_module(request) - - -def test_get_security_health_analytics_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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 = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(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_security_health_analytics_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings/customModules/*}" % client.transport._host, args[1]) - - -def test_get_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_health_analytics_custom_module( - securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - - -def test_get_security_health_analytics_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/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 = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = source.Source.to_json(source.Source()) - - request = securitycenter_service.GetSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = source.Source() - - client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_source(request) - - -def test_get_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v1/{name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_get_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -def test_get_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupAssetsRequest, - dict, -]) -def test_group_assets_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_group_assets_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc - - request = {} - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_group_assets_rest_required_fields(request_type=securitycenter_service.GroupAssetsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupAssetsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_assets_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_assets_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_assets") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupAssetsRequest.pb(securitycenter_service.GroupAssetsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupAssetsResponse.to_json(securitycenter_service.GroupAssetsResponse()) - - request = securitycenter_service.GroupAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupAssetsResponse() - - client.group_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_assets(request) - - -def test_group_assets_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupAssetsResponse.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': 'organizations/sample1'} - - pager = client.group_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_findings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_findings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_findings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) - - request = securitycenter_service.GroupFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupFindingsResponse() - - client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_findings(request) - - -def test_group_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - group_by='group_by_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v1/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) - - -def test_group_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} - - pager = client.group_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_findings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListAssetsRequest, - dict, -]) -def test_list_assets_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListAssetsResponse.pb(return_value) - 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_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_list_assets_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc - - request = {} - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_assets(request) - - # Establish 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_assets_rest_required_fields(request_type=securitycenter_service.ListAssetsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_assets._get_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_assets._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) - jsonified_request.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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAssetsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListAssetsResponse.pb(return_value) - 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_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_assets_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_assets_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_assets") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListAssetsRequest.pb(securitycenter_service.ListAssetsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListAssetsResponse.to_json(securitycenter_service.ListAssetsResponse()) - - request = securitycenter_service.ListAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListAssetsResponse() - - client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_assets(request) - - -def test_list_assets_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListAssetsResponse.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': 'organizations/sample1'} - - pager = client.list_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) - - pages = list(client.list_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, - dict, -]) -def test_list_descendant_security_health_analytics_custom_modules_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) - 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_descendant_security_health_analytics_custom_modules(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_descendant_security_health_analytics_custom_modules_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_descendant_security_health_analytics_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_descendant_security_health_analytics_custom_modules] = mock_rpc - - request = {} - client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish 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_descendant_security_health_analytics_custom_modules_rest_required_fields(request_type=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_descendant_security_health_analytics_custom_modules._get_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_descendant_security_health_analytics_custom_modules._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) - 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_descendant_security_health_analytics_custom_modules(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_descendant_security_health_analytics_custom_modules_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_descendant_security_health_analytics_custom_modules._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_descendant_security_health_analytics_custom_modules_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_descendant_security_health_analytics_custom_modules") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_descendant_security_health_analytics_custom_modules") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.pb(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.to_json(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse()) - - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - - client.list_descendant_security_health_analytics_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_descendant_security_health_analytics_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_descendant_security_health_analytics_custom_modules(request) - - -def test_list_descendant_security_health_analytics_custom_modules_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - - # 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 = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(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_descendant_security_health_analytics_custom_modules(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules:listDescendant" % client.transport._host, args[1]) - - -def test_list_descendant_security_health_analytics_custom_modules_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_descendant_security_health_analytics_custom_modules( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_descendant_security_health_analytics_custom_modules_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.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': 'organizations/sample1/securityHealthAnalyticsSettings'} - - pager = client.list_descendant_security_health_analytics_custom_modules(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - for i in results) - - pages = list(client.list_descendant_security_health_analytics_custom_modules(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.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' - assert response.total_size == 1086 - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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=securitycenter_service.ListFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) - jsonified_request.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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.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 = securitycenter_service.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 = [ - ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) - - request = securitycenter_service.ListFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListFindingsResponse() - - client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_findings(request) - - -def test_list_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} - - pager = client.list_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) - 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 - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListMuteConfigsRequest, - dict, -]) -def test_list_mute_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) - 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_mute_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMuteConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_mute_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_mute_configs] = mock_rpc - - request = {} - client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_mute_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_mute_configs_rest_required_fields(request_type=securitycenter_service.ListMuteConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListMuteConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) - 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_mute_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_mute_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_mute_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_mute_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_mute_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_mute_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListMuteConfigsRequest.pb(securitycenter_service.ListMuteConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListMuteConfigsResponse.to_json(securitycenter_service.ListMuteConfigsResponse()) - - request = securitycenter_service.ListMuteConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListMuteConfigsResponse() - - client.list_mute_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_mute_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListMuteConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_mute_configs(request) - - -def test_list_mute_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListMuteConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse.pb(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_mute_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=organizations/*}/muteConfigs" % client.transport._host, args[1]) - - -def test_list_mute_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_configs( - securitycenter_service.ListMuteConfigsRequest(), - parent='parent_value', - ) - - -def test_list_mute_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListMuteConfigsResponse.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': 'organizations/sample1'} - - pager = client.list_mute_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, mute_config.MuteConfig) - for i in results) - - pages = list(client.list_mute_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListNotificationConfigsRequest, - dict, -]) -def test_list_notification_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) - 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_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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_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_notification_configs] = mock_rpc - - request = {} - client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_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_notification_configs_rest_required_fields(request_type=securitycenter_service.ListNotificationConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListNotificationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) - 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_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_notification_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_notification_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_notification_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_notification_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_notification_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListNotificationConfigsRequest.pb(securitycenter_service.ListNotificationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListNotificationConfigsResponse.to_json(securitycenter_service.ListNotificationConfigsResponse()) - - request = securitycenter_service.ListNotificationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListNotificationConfigsResponse() - - client.list_notification_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_notification_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_notification_configs(request) - - -def test_list_notification_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListNotificationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse.pb(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_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=organizations/*}/notificationConfigs" % client.transport._host, args[1]) - - -def test_list_notification_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListNotificationConfigsResponse.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': 'organizations/sample1'} - - pager = client.list_notification_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, notification_config.NotificationConfig) - for i in results) - - pages = list(client.list_notification_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, - dict, -]) -def test_list_effective_security_health_analytics_custom_modules_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) - 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_effective_security_health_analytics_custom_modules(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_effective_security_health_analytics_custom_modules_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_effective_security_health_analytics_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_effective_security_health_analytics_custom_modules] = mock_rpc - - request = {} - client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_effective_security_health_analytics_custom_modules(request) - - # Establish 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_effective_security_health_analytics_custom_modules_rest_required_fields(request_type=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_effective_security_health_analytics_custom_modules._get_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_effective_security_health_analytics_custom_modules._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) - 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_effective_security_health_analytics_custom_modules(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_effective_security_health_analytics_custom_modules_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_effective_security_health_analytics_custom_modules._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_effective_security_health_analytics_custom_modules_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_effective_security_health_analytics_custom_modules") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_effective_security_health_analytics_custom_modules") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.pb(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.to_json(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse()) - - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - - client.list_effective_security_health_analytics_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_effective_security_health_analytics_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_effective_security_health_analytics_custom_modules(request) - - -def test_list_effective_security_health_analytics_custom_modules_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - - # 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 = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(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_effective_security_health_analytics_custom_modules(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/effectiveCustomModules" % client.transport._host, args[1]) - - -def test_list_effective_security_health_analytics_custom_modules_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_effective_security_health_analytics_custom_modules( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_effective_security_health_analytics_custom_modules_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.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': 'organizations/sample1/securityHealthAnalyticsSettings'} - - pager = client.list_effective_security_health_analytics_custom_modules(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) - for i in results) - - pages = list(client.list_effective_security_health_analytics_custom_modules(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, - dict, -]) -def test_list_security_health_analytics_custom_modules_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) - 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_security_health_analytics_custom_modules(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSecurityHealthAnalyticsCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_security_health_analytics_custom_modules_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_security_health_analytics_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_security_health_analytics_custom_modules] = mock_rpc - - request = {} - client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_security_health_analytics_custom_modules(request) - - # Establish 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_security_health_analytics_custom_modules_rest_required_fields(request_type=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_security_health_analytics_custom_modules._get_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_security_health_analytics_custom_modules._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) - 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_security_health_analytics_custom_modules(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_security_health_analytics_custom_modules_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_security_health_analytics_custom_modules._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_security_health_analytics_custom_modules_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_security_health_analytics_custom_modules") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_security_health_analytics_custom_modules") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.pb(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.to_json(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse()) - - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - - client.list_security_health_analytics_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_security_health_analytics_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_security_health_analytics_custom_modules(request) - - -def test_list_security_health_analytics_custom_modules_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - - # 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 = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(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_security_health_analytics_custom_modules(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules" % client.transport._host, args[1]) - - -def test_list_security_health_analytics_custom_modules_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_health_analytics_custom_modules( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_security_health_analytics_custom_modules_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.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': 'organizations/sample1/securityHealthAnalyticsSettings'} - - pager = client.list_security_health_analytics_custom_modules(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - for i in results) - - pages = list(client.list_security_health_analytics_custom_modules(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_sources_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_sources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_sources_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) - - request = securitycenter_service.ListSourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListSourcesResponse() - - client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_sources(request) - - -def test_list_sources_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v1/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_list_sources_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} - - pager = client.list_sources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, source.Source) - for i in results) - - pages = list(client.list_sources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.RunAssetDiscoveryRequest, - dict, -]) -def test_run_asset_discovery_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') - - # 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 - response = client.run_asset_discovery(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_run_asset_discovery_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.run_asset_discovery in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc - - request = {} - client.run_asset_discovery(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.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_run_asset_discovery_rest_required_fields(request_type=securitycenter_service.RunAssetDiscoveryRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_asset_discovery._get_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()).run_asset_discovery._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 = SecurityCenterClient( - 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.run_asset_discovery(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_run_asset_discovery_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.run_asset_discovery._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_run_asset_discovery_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_run_asset_discovery") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_run_asset_discovery") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.RunAssetDiscoveryRequest.pb(securitycenter_service.RunAssetDiscoveryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = securitycenter_service.RunAssetDiscoveryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.run_asset_discovery(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_run_asset_discovery_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.run_asset_discovery(request) - - -def test_run_asset_discovery_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.run_asset_discovery(**mock_args) - - # Establish that the underlying call 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=organizations/*}/assets:runDiscovery" % client.transport._host, args[1]) - - -def test_run_asset_discovery_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -def test_run_asset_discovery_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # 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 - response = client.set_finding_state(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( - 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': "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 = 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.set_finding_state(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_finding_state_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_finding_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "state", "startTime", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_finding_state_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = finding.Finding.to_json(finding.Finding()) - - request = securitycenter_service.SetFindingStateRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_finding_state(request) - - -def test_set_finding_state_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - mock_args.update(sample_request) - - # 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.set_finding_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/v1/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) - - -def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -def test_set_finding_state_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetMuteRequest, - dict, -]) -def test_set_mute_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # 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 - response = client.set_mute(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_set_mute_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_mute in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc - - request = {} - client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_mute(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_set_mute_rest_required_fields(request_type=securitycenter_service.SetMuteRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - 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': "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 = 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.set_mute(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_mute_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_mute._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "mute", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_mute_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_mute") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_mute") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SetMuteRequest.pb(securitycenter_service.SetMuteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = finding.Finding.to_json(finding.Finding()) - - request = securitycenter_service.SetMuteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.set_mute(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_mute_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetMuteRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_mute(request) - - -def test_set_mute_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - mock_args.update(sample_request) - - # 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.set_mute(**mock_args) - - # Establish that the underlying call 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=organizations/*/sources/*/findings/*}:setMute" % client.transport._host, args[1]) - - -def test_set_mute_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_mute( - securitycenter_service.SetMuteRequest(), - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - -def test_set_mute_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.set_iam_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/v1/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # 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 - response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_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.test_iam_permissions(**mock_args) - - # Establish that the underlying call 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/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_simulate_security_health_analytics_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.simulate_security_health_analytics_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) - -def test_simulate_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.simulate_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.simulate_security_health_analytics_custom_module] = mock_rpc - - request = {} - client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.simulate_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_simulate_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).simulate_security_health_analytics_custom_module._get_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()).simulate_security_health_analytics_custom_module._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.simulate_security_health_analytics_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_simulate_security_health_analytics_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.simulate_security_health_analytics_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "customConfig", "resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_simulate_security_health_analytics_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_simulate_security_health_analytics_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_simulate_security_health_analytics_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.to_json(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse()) - - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - - client.simulate_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_simulate_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.simulate_security_health_analytics_custom_module(request) - - -def test_simulate_security_health_analytics_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), - resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(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.simulate_security_health_analytics_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules:simulate" % client.transport._host, args[1]) - - -def test_simulate_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.simulate_security_health_analytics_custom_module( - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(), - parent='parent_value', - custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), - resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), - ) - - -def test_simulate_security_health_analytics_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateExternalSystemRequest, - dict, -]) -def test_update_external_system_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} - request_init["external_system"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4', 'assignees': ['assignees_value1', 'assignees_value2'], 'external_uid': 'external_uid_value', 'status': 'status_value', 'external_system_update_time': {'seconds': 751, 'nanos': 543}, 'case_uri': 'case_uri_value', 'case_priority': 'case_priority_value', 'case_sla': {}, 'case_create_time': {}, 'case_close_time': {}, 'ticket_info': {'id': 'id_value', 'assignee': 'assignee_value', 'description': 'description_value', 'uri': 'uri_value', 'status': 'status_value', 'update_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 = securitycenter_service.UpdateExternalSystemRequest.meta.fields["external_system"] - - 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["external_system"].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["external_system"][field])): - del request_init["external_system"][field][i][subfield] - else: - del request_init["external_system"][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 = gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_external_system.ExternalSystem.pb(return_value) - 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_external_system(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_external_system.ExternalSystem) - assert response.name == 'name_value' - assert response.assignees == ['assignees_value'] - assert response.external_uid == 'external_uid_value' - assert response.status == 'status_value' - assert response.case_uri == 'case_uri_value' - assert response.case_priority == 'case_priority_value' - -def test_update_external_system_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_external_system in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc - - request = {} - client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_external_system(request) - - # Establish 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_external_system_rest_required_fields(request_type=securitycenter_service.UpdateExternalSystemRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_external_system._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_external_system._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_external_system.ExternalSystem() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_external_system.ExternalSystem.pb(return_value) - 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_external_system(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_external_system_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_external_system._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("externalSystem", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_external_system_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_external_system") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_external_system") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateExternalSystemRequest.pb(securitycenter_service.UpdateExternalSystemRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_external_system.ExternalSystem.to_json(gcs_external_system.ExternalSystem()) - - request = securitycenter_service.UpdateExternalSystemRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_external_system.ExternalSystem() - - client.update_external_system(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_external_system_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateExternalSystemRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_external_system(request) - - -def test_update_external_system_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_external_system.ExternalSystem() - - # get arguments that satisfy an http rule for this method - sample_request = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - external_system=gcs_external_system.ExternalSystem(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 = gcs_external_system.ExternalSystem.pb(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_external_system(**mock_args) - - # Establish that the underlying call 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/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}" % client.transport._host, args[1]) - - -def test_update_external_system_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_external_system( - securitycenter_service.UpdateExternalSystemRequest(), - external_system=gcs_external_system.ExternalSystem(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_external_system_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_value', 'mute': 1, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.update_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.update_finding] = mock_rpc - - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_finding._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_finding._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.update_finding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.UpdateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_finding(request) - - -def test_update_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - finding=gcs_finding.Finding(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 = gcs_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.update_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/v1/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) - - -def test_update_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_update_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateMuteConfigRequest, - dict, -]) -def test_update_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} - request_init["mute_config"] = {'name': 'organizations/sample1/muteConfigs/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_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 = securitycenter_service.UpdateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): - del request_init["mute_config"][field][i][subfield] - else: - del request_init["mute_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 = gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - -def test_update_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - - request = {} - client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.UpdateMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_mute_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_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("muteConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_mute_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_mute_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateMuteConfigRequest.pb(securitycenter_service.UpdateMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) - - request = securitycenter_service.UpdateMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_mute_config.MuteConfig() - - client.update_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_mute_config(request) - - -def test_update_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - mute_config=gcs_mute_config.MuteConfig(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 = gcs_mute_config.MuteConfig.pb(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_mute_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/{mute_config.name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) - - -def test_update_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.UpdateMuteConfigRequest(), - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateNotificationConfigRequest, - dict, -]) -def test_update_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} - request_init["notification_config"] = {'name': 'organizations/sample1/notificationConfigs/sample2', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.UpdateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): - del request_init["notification_config"][field][i][subfield] - else: - del request_init["notification_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 = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.UpdateNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("notificationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateNotificationConfigRequest.pb(securitycenter_service.UpdateNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) - - request = securitycenter_service.UpdateNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_notification_config.NotificationConfig() - - client.update_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_notification_config(request) - - -def test_update_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/{notification_config.name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_update_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateOrganizationSettingsRequest, - dict, -]) -def test_update_organization_settings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - request_init["organization_settings"] = {'name': 'organizations/sample1/organizationSettings', 'enable_asset_discovery': True, 'asset_discovery_config': {'project_ids': ['project_ids_value1', 'project_ids_value2'], 'inclusion_mode': 1, 'folder_ids': ['folder_ids_value1', 'folder_ids_value2']}} - # The version of a generated dependency at test runtime may differ from the version used 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 = securitycenter_service.UpdateOrganizationSettingsRequest.meta.fields["organization_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["organization_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["organization_settings"][field])): - del request_init["organization_settings"][field][i][subfield] - else: - del request_init["organization_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 = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_organization_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_organization_settings] = mock_rpc - - request = {} - client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_organization_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_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_organization_settings.OrganizationSettings() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_organization_settings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_organization_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("organizationSettings", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_organization_settings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_organization_settings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_organization_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateOrganizationSettingsRequest.pb(securitycenter_service.UpdateOrganizationSettingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_organization_settings.OrganizationSettings.to_json(gcs_organization_settings.OrganizationSettings()) - - request = securitycenter_service.UpdateOrganizationSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_organization_settings.OrganizationSettings() - - client.update_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_organization_settings(request) - - -def test_update_organization_settings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_organization_settings.OrganizationSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - - # get truthy value for each flattened field - mock_args = dict( - organization_settings=gcs_organization_settings.OrganizationSettings(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 = gcs_organization_settings.OrganizationSettings.pb(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_organization_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/v1/{organization_settings.name=organizations/*/organizationSettings}" % client.transport._host, args[1]) - - -def test_update_organization_settings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -def test_update_organization_settings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_update_security_health_analytics_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'security_health_analytics_custom_module': {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'}} - request_init["security_health_analytics_custom_module"] = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2', 'display_name': 'display_name_value', 'enablement_state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_value', 'ancestor_module': 'ancestor_module_value', 'custom_config': {'predicate': {'expression': 'expression_value', 'title': 'title_value', 'description': 'description_value', 'location': 'location_value'}, 'custom_output': {'properties': [{'name': 'name_value', 'value_expression': {}}]}, 'resource_selector': {'resource_types': ['resource_types_value1', 'resource_types_value2']}, 'severity': 1, 'description': 'description_value', 'recommendation': 'recommendation_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 = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.meta.fields["security_health_analytics_custom_module"] - - 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["security_health_analytics_custom_module"].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["security_health_analytics_custom_module"][field])): - del request_init["security_health_analytics_custom_module"][field][i][subfield] - else: - del request_init["security_health_analytics_custom_module"][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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) - 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_security_health_analytics_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - -def test_update_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_health_analytics_custom_module] = mock_rpc - - request = {} - client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_health_analytics_custom_module(request) - - # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_security_health_analytics_custom_module._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_security_health_analytics_custom_module._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) - 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_security_health_analytics_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_security_health_analytics_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_security_health_analytics_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("securityHealthAnalyticsCustomModule", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_security_health_analytics_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_health_analytics_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_health_analytics_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.to_json(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - client.update_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'security_health_analytics_custom_module': {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_security_health_analytics_custom_module(request) - - -def test_update_security_health_analytics_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'security_health_analytics_custom_module': {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(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_security_health_analytics_custom_module(**mock_args) - - # Establish that the underlying call 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/{security_health_analytics_custom_module.name=organizations/*/securityHealthAnalyticsSettings/customModules/*}" % client.transport._host, args[1]) - - -def test_update_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_health_analytics_custom_module( - securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(), - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_security_health_analytics_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.UpdateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_source(request) - - -def test_update_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_update_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - - -def test_update_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - request_init["security_marks"] = {'name': 'organizations/sample1/assets/sample2/securityMarks', 'marks': {}, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] - - 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["security_marks"].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["security_marks"][field])): - del request_init["security_marks"][field][i][subfield] - else: - del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - -def test_update_security_marks_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_security_marks._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_security_marks._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("start_time", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_security_marks_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_security_marks._get_unset_required_fields({}) - assert set(unset_fields) == (set(("startTime", "updateMask", )) & set(("securityMarks", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_security_marks_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) - - request = securitycenter_service.UpdateSecurityMarksRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_security_marks.SecurityMarks() - - client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_security_marks(request) - - -def test_update_security_marks_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - - # get arguments that satisfy an http rule for this method - sample_request = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - - # get truthy value for each flattened field - mock_args = dict( - security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) - - # Establish that the underlying call 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/{security_marks.name=organizations/*/assets/*/securityMarks}" % client.transport._host, args[1]) - - -def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - -def test_update_security_marks_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateBigQueryExportRequest, - dict, -]) -def test_create_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["big_query_export"] = {'name': 'name_value', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.CreateBigQueryExportRequest.meta.fields["big_query_export"] - - 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["big_query_export"].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["big_query_export"][field])): - del request_init["big_query_export"][field][i][subfield] - else: - del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - -def test_create_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - - request = {} - client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.CreateBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["big_query_export_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 "bigQueryExportId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "bigQueryExportId" in jsonified_request - assert jsonified_request["bigQueryExportId"] == request_init["big_query_export_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["bigQueryExportId"] = 'big_query_export_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("big_query_export_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 "bigQueryExportId" in jsonified_request - assert jsonified_request["bigQueryExportId"] == 'big_query_export_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - expected_params = [ - ( - "bigQueryExportId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(("bigQueryExportId", )) & set(("parent", "bigQueryExport", "bigQueryExportId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_big_query_export") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_big_query_export") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateBigQueryExportRequest.pb(securitycenter_service.CreateBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) - - request = securitycenter_service.CreateBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = bigquery_export.BigQueryExport() - - client.create_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_big_query_export(request) - - -def test_create_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) - - # Establish that the underlying call 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=organizations/*}/bigQueryExports" % client.transport._host, args[1]) - - -def test_create_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.CreateBigQueryExportRequest(), - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_id_value', - ) - - -def test_create_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteBigQueryExportRequest, - dict, -]) -def test_delete_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/bigQueryExports/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 = 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - - request = {} - client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.DeleteBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - 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_big_query_export(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_big_query_export") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteBigQueryExportRequest.pb(securitycenter_service.DeleteBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/bigQueryExports/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_big_query_export(request) - - -def test_delete_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/bigQueryExports/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_big_query_export(**mock_args) - - # Establish that the underlying call 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=organizations/*/bigQueryExports/*}" % client.transport._host, args[1]) - - -def test_delete_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.DeleteBigQueryExportRequest(), - name='name_value', - ) - - -def test_delete_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateBigQueryExportRequest, - dict, -]) -def test_update_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'big_query_export': {'name': 'organizations/sample1/bigQueryExports/sample2'}} - request_init["big_query_export"] = {'name': 'organizations/sample1/bigQueryExports/sample2', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.UpdateBigQueryExportRequest.meta.fields["big_query_export"] - - 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["big_query_export"].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["big_query_export"][field])): - del request_init["big_query_export"][field][i][subfield] - else: - del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - -def test_update_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc - - request = {} - client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.UpdateBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_big_query_export._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_big_query_export._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("bigQueryExport", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_big_query_export") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_big_query_export") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateBigQueryExportRequest.pb(securitycenter_service.UpdateBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) - - request = securitycenter_service.UpdateBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = bigquery_export.BigQueryExport() - - client.update_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'big_query_export': {'name': 'organizations/sample1/bigQueryExports/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_big_query_export(request) - - -def test_update_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - - # get arguments that satisfy an http rule for this method - sample_request = {'big_query_export': {'name': 'organizations/sample1/bigQueryExports/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - big_query_export=bigquery_export.BigQueryExport(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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) - - # Establish that the underlying call 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/{big_query_export.name=organizations/*/bigQueryExports/*}" % client.transport._host, args[1]) - - -def test_update_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.UpdateBigQueryExportRequest(), - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListBigQueryExportsRequest, - dict, -]) -def test_list_big_query_exports_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) - 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_big_query_exports(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryExportsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_big_query_exports_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_big_query_exports in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc - - request = {} - client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_big_query_exports(request) - - # Establish 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_big_query_exports_rest_required_fields(request_type=securitycenter_service.ListBigQueryExportsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_big_query_exports._get_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_big_query_exports._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListBigQueryExportsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) - 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_big_query_exports(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_big_query_exports_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_big_query_exports._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_big_query_exports_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_big_query_exports") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_big_query_exports") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListBigQueryExportsRequest.pb(securitycenter_service.ListBigQueryExportsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListBigQueryExportsResponse.to_json(securitycenter_service.ListBigQueryExportsResponse()) - - request = securitycenter_service.ListBigQueryExportsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListBigQueryExportsResponse() - - client.list_big_query_exports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_big_query_exports_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListBigQueryExportsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_big_query_exports(request) - - -def test_list_big_query_exports_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListBigQueryExportsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse.pb(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_big_query_exports(**mock_args) - - # Establish that the underlying call 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=organizations/*}/bigQueryExports" % client.transport._host, args[1]) - - -def test_list_big_query_exports_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_exports( - securitycenter_service.ListBigQueryExportsRequest(), - parent='parent_value', - ) - - -def test_list_big_query_exports_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListBigQueryExportsResponse.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': 'organizations/sample1'} - - pager = client.list_big_query_exports(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, bigquery_export.BigQueryExport) - for i in results) - - pages = list(client.list_big_query_exports(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_create_event_threat_detection_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request_init["event_threat_detection_custom_module"] = {'name': 'name_value', 'config': {'fields': {}}, 'ancestor_module': 'ancestor_module_value', 'enablement_state': 1, 'type_': 'type__value', 'display_name': 'display_name_value', 'description': 'description_value', 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_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 = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.meta.fields["event_threat_detection_custom_module"] - - 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["event_threat_detection_custom_module"].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["event_threat_detection_custom_module"][field])): - del request_init["event_threat_detection_custom_module"][field][i][subfield] - else: - del request_init["event_threat_detection_custom_module"][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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) - 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_event_threat_detection_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - -def test_create_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc - - request = {} - client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_event_threat_detection_custom_module(request) - - # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_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_event_threat_detection_custom_module._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) - 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_event_threat_detection_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_event_threat_detection_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_event_threat_detection_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "eventThreatDetectionCustomModule", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_event_threat_detection_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_event_threat_detection_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_event_threat_detection_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.CreateEventThreatDetectionCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.to_json(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - client.create_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_event_threat_detection_custom_module(request) - - -def test_create_event_threat_detection_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(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_event_threat_detection_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/customModules" % client.transport._host, args[1]) - - -def test_create_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_event_threat_detection_custom_module( - securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(), - parent='parent_value', - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - ) - - -def test_create_event_threat_detection_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_delete_event_threat_detection_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/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 = 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_event_threat_detection_custom_module(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc - - request = {} - client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_event_threat_detection_custom_module(request) - - # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - 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_event_threat_detection_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_event_threat_detection_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_event_threat_detection_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_event_threat_detection_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_event_threat_detection_custom_module") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_event_threat_detection_custom_module(request) - - -def test_delete_event_threat_detection_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/eventThreatDetectionSettings/customModules/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_event_threat_detection_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings/customModules/*}" % client.transport._host, args[1]) - - -def test_delete_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_event_threat_detection_custom_module( - securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - - -def test_delete_event_threat_detection_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_get_event_threat_detection_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/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 = event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) - 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_event_threat_detection_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - -def test_get_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_event_threat_detection_custom_module] = mock_rpc - - request = {} - client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_event_threat_detection_custom_module(request) - - # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.GetEventThreatDetectionCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) - 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_event_threat_detection_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_event_threat_detection_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_event_threat_detection_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_event_threat_detection_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_event_threat_detection_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_event_threat_detection_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.GetEventThreatDetectionCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = event_threat_detection_custom_module.EventThreatDetectionCustomModule.to_json(event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - client.get_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetEventThreatDetectionCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_event_threat_detection_custom_module(request) - - -def test_get_event_threat_detection_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/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 = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(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_event_threat_detection_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings/customModules/*}" % client.transport._host, args[1]) - - -def test_get_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_event_threat_detection_custom_module( - securitycenter_service.GetEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - - -def test_get_event_threat_detection_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, - dict, -]) -def test_list_descendant_event_threat_detection_custom_modules_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(return_value) - 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_descendant_event_threat_detection_custom_modules(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDescendantEventThreatDetectionCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_descendant_event_threat_detection_custom_modules_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_descendant_event_threat_detection_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_descendant_event_threat_detection_custom_modules] = mock_rpc - - request = {} - client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish 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_descendant_event_threat_detection_custom_modules_rest_required_fields(request_type=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_descendant_event_threat_detection_custom_modules._get_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_descendant_event_threat_detection_custom_modules._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(return_value) - 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_descendant_event_threat_detection_custom_modules(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_descendant_event_threat_detection_custom_modules_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_descendant_event_threat_detection_custom_modules._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_descendant_event_threat_detection_custom_modules_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_descendant_event_threat_detection_custom_modules") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_descendant_event_threat_detection_custom_modules") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.pb(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.to_json(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse()) - - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - - client.list_descendant_event_threat_detection_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_descendant_event_threat_detection_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_descendant_event_threat_detection_custom_modules(request) - - -def test_list_descendant_event_threat_detection_custom_modules_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - - # 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 = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(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_descendant_event_threat_detection_custom_modules(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/customModules:listDescendant" % client.transport._host, args[1]) - - -def test_list_descendant_event_threat_detection_custom_modules_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_descendant_event_threat_detection_custom_modules( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_descendant_event_threat_detection_custom_modules_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.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': 'organizations/sample1/eventThreatDetectionSettings'} - - pager = client.list_descendant_event_threat_detection_custom_modules(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - for i in results) - - pages = list(client.list_descendant_event_threat_detection_custom_modules(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListEventThreatDetectionCustomModulesRequest, - dict, -]) -def test_list_event_threat_detection_custom_modules_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(return_value) - 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_event_threat_detection_custom_modules(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEventThreatDetectionCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_event_threat_detection_custom_modules_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_event_threat_detection_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_event_threat_detection_custom_modules] = mock_rpc - - request = {} - client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_event_threat_detection_custom_modules(request) - - # Establish 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_event_threat_detection_custom_modules_rest_required_fields(request_type=securitycenter_service.ListEventThreatDetectionCustomModulesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_event_threat_detection_custom_modules._get_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_event_threat_detection_custom_modules._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(return_value) - 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_event_threat_detection_custom_modules(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_event_threat_detection_custom_modules_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_event_threat_detection_custom_modules._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_event_threat_detection_custom_modules_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_event_threat_detection_custom_modules") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_event_threat_detection_custom_modules") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListEventThreatDetectionCustomModulesRequest.pb(securitycenter_service.ListEventThreatDetectionCustomModulesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.to_json(securitycenter_service.ListEventThreatDetectionCustomModulesResponse()) - - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - - client.list_event_threat_detection_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_event_threat_detection_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListEventThreatDetectionCustomModulesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_event_threat_detection_custom_modules(request) - - -def test_list_event_threat_detection_custom_modules_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - - # 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 = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(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_event_threat_detection_custom_modules(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/customModules" % client.transport._host, args[1]) - - -def test_list_event_threat_detection_custom_modules_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_event_threat_detection_custom_modules( - securitycenter_service.ListEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_event_threat_detection_custom_modules_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListEventThreatDetectionCustomModulesResponse.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': 'organizations/sample1/eventThreatDetectionSettings'} - - pager = client.list_event_threat_detection_custom_modules(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - for i in results) - - pages = list(client.list_event_threat_detection_custom_modules(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_update_event_threat_detection_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'event_threat_detection_custom_module': {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'}} - request_init["event_threat_detection_custom_module"] = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2', 'config': {'fields': {}}, 'ancestor_module': 'ancestor_module_value', 'enablement_state': 1, 'type_': 'type__value', 'display_name': 'display_name_value', 'description': 'description_value', 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_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 = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.meta.fields["event_threat_detection_custom_module"] - - 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["event_threat_detection_custom_module"].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["event_threat_detection_custom_module"][field])): - del request_init["event_threat_detection_custom_module"][field][i][subfield] - else: - del request_init["event_threat_detection_custom_module"][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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) - 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_event_threat_detection_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - -def test_update_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_event_threat_detection_custom_module] = mock_rpc - - request = {} - client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_event_threat_detection_custom_module(request) - - # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_event_threat_detection_custom_module._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_event_threat_detection_custom_module._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) - 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_event_threat_detection_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_event_threat_detection_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_event_threat_detection_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("eventThreatDetectionCustomModule", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_event_threat_detection_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_event_threat_detection_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_event_threat_detection_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.to_json(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - client.update_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'event_threat_detection_custom_module': {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_event_threat_detection_custom_module(request) - - -def test_update_event_threat_detection_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'event_threat_detection_custom_module': {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(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_event_threat_detection_custom_module(**mock_args) - - # Establish that the underlying call 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/{event_threat_detection_custom_module.name=organizations/*/eventThreatDetectionSettings/customModules/*}" % client.transport._host, args[1]) - - -def test_update_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_event_threat_detection_custom_module( - securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(), - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_event_threat_detection_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_validate_event_threat_detection_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.pb(return_value) - 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_event_threat_detection_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) - -def test_validate_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc - - request = {} - client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.validate_event_threat_detection_custom_module(request) - - # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["raw_text"] = "" - request_init["type_"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["rawText"] = 'raw_text_value' - jsonified_request["type"] = 'type__value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).validate_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "rawText" in jsonified_request - assert jsonified_request["rawText"] == 'raw_text_value' - assert "type" in jsonified_request - assert jsonified_request["type"] == 'type__value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.pb(return_value) - 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_event_threat_detection_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_validate_event_threat_detection_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.validate_event_threat_detection_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "rawText", "type", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_validate_event_threat_detection_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_validate_event_threat_detection_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_validate_event_threat_detection_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.to_json(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse()) - - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() - - client.validate_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_validate_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.validate_event_threat_detection_custom_module(request) - - -def test_validate_event_threat_detection_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_get_effective_event_threat_detection_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/effectiveCustomModules/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 = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( - name='name_value', - enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(return_value) - 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_effective_event_threat_detection_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.enablement_state == effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - -def test_get_effective_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_effective_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_effective_event_threat_detection_custom_module] = mock_rpc - - request = {} - client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_effective_event_threat_detection_custom_module(request) - - # Establish 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_effective_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_effective_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_effective_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(return_value) - 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_effective_event_threat_detection_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_effective_event_threat_detection_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_effective_event_threat_detection_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_effective_event_threat_detection_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_effective_event_threat_detection_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_effective_event_threat_detection_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.to_json(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule()) - - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - - client.get_effective_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_effective_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/effectiveCustomModules/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_effective_event_threat_detection_custom_module(request) - - -def test_get_effective_event_threat_detection_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/eventThreatDetectionSettings/effectiveCustomModules/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 = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(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_effective_event_threat_detection_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings/effectiveCustomModules/*}" % client.transport._host, args[1]) - - -def test_get_effective_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_effective_event_threat_detection_custom_module( - securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - - -def test_get_effective_event_threat_detection_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, - dict, -]) -def test_list_effective_event_threat_detection_custom_modules_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(return_value) - 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_effective_event_threat_detection_custom_modules(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEffectiveEventThreatDetectionCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_effective_event_threat_detection_custom_modules_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_effective_event_threat_detection_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_effective_event_threat_detection_custom_modules] = mock_rpc - - request = {} - client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_effective_event_threat_detection_custom_modules(request) - - # Establish 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_effective_event_threat_detection_custom_modules_rest_required_fields(request_type=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_effective_event_threat_detection_custom_modules._get_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_effective_event_threat_detection_custom_modules._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(return_value) - 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_effective_event_threat_detection_custom_modules(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_effective_event_threat_detection_custom_modules_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_effective_event_threat_detection_custom_modules._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_effective_event_threat_detection_custom_modules_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_effective_event_threat_detection_custom_modules") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_effective_event_threat_detection_custom_modules") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.pb(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.to_json(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse()) - - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - - client.list_effective_event_threat_detection_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_effective_event_threat_detection_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_effective_event_threat_detection_custom_modules(request) - - -def test_list_effective_event_threat_detection_custom_modules_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - - # 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 = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(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_effective_event_threat_detection_custom_modules(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/effectiveCustomModules" % client.transport._host, args[1]) - - -def test_list_effective_event_threat_detection_custom_modules_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_effective_event_threat_detection_custom_modules( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_effective_event_threat_detection_custom_modules_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.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': 'organizations/sample1/eventThreatDetectionSettings'} - - pager = client.list_effective_event_threat_detection_custom_modules(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) - for i in results) - - pages = list(client.list_effective_event_threat_detection_custom_modules(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.BatchCreateResourceValueConfigsRequest, - dict, -]) -def test_batch_create_resource_value_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.BatchCreateResourceValueConfigsResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) - -def test_batch_create_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc - - request = {} - client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_resource_value_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_batch_create_resource_value_configs_rest_required_fields(request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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()).batch_create_resource_value_configs._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_create_resource_value_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_create_resource_value_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_resource_value_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_batch_create_resource_value_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_batch_create_resource_value_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(securitycenter_service.BatchCreateResourceValueConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.BatchCreateResourceValueConfigsResponse.to_json(securitycenter_service.BatchCreateResourceValueConfigsResponse()) - - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - - client.batch_create_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_create_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_create_resource_value_configs(request) - - -def test_batch_create_resource_value_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(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.batch_create_resource_value_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=organizations/*}/resourceValueConfigs:batchCreate" % client.transport._host, args[1]) - - -def test_batch_create_resource_value_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_create_resource_value_configs( - securitycenter_service.BatchCreateResourceValueConfigsRequest(), - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], - ) - - -def test_batch_create_resource_value_configs_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteResourceValueConfigRequest, - dict, -]) -def test_delete_resource_value_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = 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_resource_value_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - - request = {} - client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.DeleteResourceValueConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( - 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_resource_value_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_resource_value_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_resource_value_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_resource_value_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_resource_value_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteResourceValueConfigRequest.pb(securitycenter_service.DeleteResourceValueConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteResourceValueConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteResourceValueConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_resource_value_config(request) - - -def test_delete_resource_value_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/resourceValueConfigs/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_resource_value_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=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_resource_value_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_config( - securitycenter_service.DeleteResourceValueConfigRequest(), - name='name_value', - ) - - -def test_delete_resource_value_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetResourceValueConfigRequest, - dict, -]) -def test_get_resource_value_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - -def test_get_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc - - request = {} - client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.GetResourceValueConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resource_value_config.ResourceValueConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_resource_value_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_resource_value_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_resource_value_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_resource_value_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_resource_value_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetResourceValueConfigRequest.pb(securitycenter_service.GetResourceValueConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resource_value_config.ResourceValueConfig.to_json(resource_value_config.ResourceValueConfig()) - - request = securitycenter_service.GetResourceValueConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resource_value_config.ResourceValueConfig() - - client.get_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetResourceValueConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_resource_value_config(request) - - -def test_get_resource_value_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resource_value_config.ResourceValueConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig.pb(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_resource_value_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=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) - - -def test_get_resource_value_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_config( - securitycenter_service.GetResourceValueConfigRequest(), - name='name_value', - ) - - -def test_get_resource_value_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListResourceValueConfigsRequest, - dict, -]) -def test_list_resource_value_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceValueConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc - - request = {} - client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_resource_value_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_resource_value_configs_rest_required_fields(request_type=securitycenter_service.ListResourceValueConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListResourceValueConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_resource_value_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_resource_value_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_resource_value_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_resource_value_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_resource_value_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListResourceValueConfigsRequest.pb(securitycenter_service.ListResourceValueConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListResourceValueConfigsResponse.to_json(securitycenter_service.ListResourceValueConfigsResponse()) - - request = securitycenter_service.ListResourceValueConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListResourceValueConfigsResponse() - - client.list_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListResourceValueConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_resource_value_configs(request) - - -def test_list_resource_value_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListResourceValueConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse.pb(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_resource_value_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=organizations/*}/resourceValueConfigs" % client.transport._host, args[1]) - - -def test_list_resource_value_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_configs( - securitycenter_service.ListResourceValueConfigsRequest(), - parent='parent_value', - ) - - -def test_list_resource_value_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListResourceValueConfigsResponse.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': 'organizations/sample1'} - - pager = client.list_resource_value_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resource_value_config.ResourceValueConfig) - for i in results) - - pages = list(client.list_resource_value_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateResourceValueConfigRequest, - dict, -]) -def test_update_resource_value_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} - request_init["resource_value_config"] = {'name': 'organizations/sample1/resourceValueConfigs/sample2', 'resource_value': 1, 'tag_values': ['tag_values_value1', 'tag_values_value2'], 'resource_type': 'resource_type_value', 'scope': 'scope_value', 'resource_labels_selector': {}, 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'cloud_provider': 1, 'sensitive_data_protection_mapping': {'high_sensitivity_mapping': 1, 'medium_sensitivity_mapping': 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 = securitycenter_service.UpdateResourceValueConfigRequest.meta.fields["resource_value_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["resource_value_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["resource_value_config"][field])): - del request_init["resource_value_config"][field][i][subfield] - else: - del request_init["resource_value_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 = gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - -def test_update_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - - request = {} - client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.UpdateResourceValueConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_resource_value_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_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_resource_value_config.ResourceValueConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_resource_value_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_resource_value_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("resourceValueConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_resource_value_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_resource_value_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_resource_value_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateResourceValueConfigRequest.pb(securitycenter_service.UpdateResourceValueConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_resource_value_config.ResourceValueConfig.to_json(gcs_resource_value_config.ResourceValueConfig()) - - request = securitycenter_service.UpdateResourceValueConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_resource_value_config.ResourceValueConfig() - - client.update_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateResourceValueConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_resource_value_config(request) - - -def test_update_resource_value_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_resource_value_config.ResourceValueConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - resource_value_config=gcs_resource_value_config.ResourceValueConfig(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 = gcs_resource_value_config.ResourceValueConfig.pb(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_resource_value_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/{resource_value_config.name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) - - -def test_update_resource_value_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_config( - securitycenter_service.UpdateResourceValueConfigRequest(), - resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_resource_value_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListValuedResourcesRequest, - dict, -]) -def test_list_valued_resources_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) - 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_valued_resources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListValuedResourcesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_list_valued_resources_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_valued_resources in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc - - request = {} - client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_valued_resources(request) - - # Establish 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_valued_resources_rest_required_fields(request_type=securitycenter_service.ListValuedResourcesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_valued_resources._get_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_valued_resources._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListValuedResourcesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) - 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_valued_resources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_valued_resources_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_valued_resources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_valued_resources_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_valued_resources") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_valued_resources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListValuedResourcesRequest.pb(securitycenter_service.ListValuedResourcesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListValuedResourcesResponse.to_json(securitycenter_service.ListValuedResourcesResponse()) - - request = securitycenter_service.ListValuedResourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListValuedResourcesResponse() - - client.list_valued_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_valued_resources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListValuedResourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_valued_resources(request) - - -def test_list_valued_resources_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListValuedResourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse.pb(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_valued_resources(**mock_args) - - # Establish that the underlying call 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=organizations/*/simulations/*}/valuedResources" % client.transport._host, args[1]) - - -def test_list_valued_resources_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_valued_resources( - securitycenter_service.ListValuedResourcesRequest(), - parent='parent_value', - ) - - -def test_list_valued_resources_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListValuedResourcesResponse.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': 'organizations/sample1/simulations/sample2'} - - pager = client.list_valued_resources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, valued_resource.ValuedResource) - for i in results) - - pages = list(client.list_valued_resources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListAttackPathsRequest, - dict, -]) -def test_list_attack_paths_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) - 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_attack_paths(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttackPathsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_attack_paths_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_attack_paths in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc - - request = {} - client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_attack_paths(request) - - # Establish 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_attack_paths_rest_required_fields(request_type=securitycenter_service.ListAttackPathsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_attack_paths._get_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_attack_paths._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAttackPathsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) - 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_attack_paths(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_attack_paths_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_attack_paths._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_attack_paths_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_attack_paths") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_attack_paths") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListAttackPathsRequest.pb(securitycenter_service.ListAttackPathsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListAttackPathsResponse.to_json(securitycenter_service.ListAttackPathsResponse()) - - request = securitycenter_service.ListAttackPathsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListAttackPathsResponse() - - client.list_attack_paths(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_attack_paths_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAttackPathsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_attack_paths(request) - - -def test_list_attack_paths_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAttackPathsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse.pb(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_attack_paths(**mock_args) - - # Establish that the underlying call 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=organizations/*/simulations/*}/attackPaths" % client.transport._host, args[1]) - - -def test_list_attack_paths_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_attack_paths( - securitycenter_service.ListAttackPathsRequest(), - parent='parent_value', - ) - - -def test_list_attack_paths_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListAttackPathsResponse.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': 'organizations/sample1/simulations/sample2'} - - pager = client.list_attack_paths(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, attack_path.AttackPath) - for i in results) - - pages = list(client.list_attack_paths(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.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SecurityCenterClient( - 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 = SecurityCenterClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SecurityCenterClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SecurityCenterClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SecurityCenterGrpcTransport, - ) - -def test_security_center_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_security_center_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.securitycenter_v1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'bulk_mute_findings', - 'create_security_health_analytics_custom_module', - 'create_source', - 'create_finding', - 'create_mute_config', - 'create_notification_config', - 'delete_mute_config', - 'delete_notification_config', - 'delete_security_health_analytics_custom_module', - 'get_simulation', - 'get_valued_resource', - 'get_big_query_export', - 'get_iam_policy', - 'get_mute_config', - 'get_notification_config', - 'get_organization_settings', - 'get_effective_security_health_analytics_custom_module', - 'get_security_health_analytics_custom_module', - 'get_source', - 'group_assets', - 'group_findings', - 'list_assets', - 'list_descendant_security_health_analytics_custom_modules', - 'list_findings', - 'list_mute_configs', - 'list_notification_configs', - 'list_effective_security_health_analytics_custom_modules', - 'list_security_health_analytics_custom_modules', - 'list_sources', - 'run_asset_discovery', - 'set_finding_state', - 'set_mute', - 'set_iam_policy', - 'test_iam_permissions', - 'simulate_security_health_analytics_custom_module', - 'update_external_system', - 'update_finding', - 'update_mute_config', - 'update_notification_config', - 'update_organization_settings', - 'update_security_health_analytics_custom_module', - 'update_source', - 'update_security_marks', - 'create_big_query_export', - 'delete_big_query_export', - 'update_big_query_export', - 'list_big_query_exports', - 'create_event_threat_detection_custom_module', - 'delete_event_threat_detection_custom_module', - 'get_event_threat_detection_custom_module', - 'list_descendant_event_threat_detection_custom_modules', - 'list_event_threat_detection_custom_modules', - 'update_event_threat_detection_custom_module', - 'validate_event_threat_detection_custom_module', - 'get_effective_event_threat_detection_custom_module', - 'list_effective_event_threat_detection_custom_modules', - 'batch_create_resource_value_configs', - 'delete_resource_value_config', - 'get_resource_value_config', - 'list_resource_value_configs', - 'update_resource_value_config', - 'list_valued_resources', - 'list_attack_paths', - '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_security_center_base_transport_with_credentials_file(): - # Instantiate the 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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - 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_security_center_base_transport_with_adc(): - # Test the default 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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport() - adc.assert_called_once() - - -def test_security_center_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) - SecurityCenterClient() - 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -def test_security_center_transport_auth_adc(transport_class): - # If 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, - ], -) -def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), - (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_security_center_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host 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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_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.SecurityCenterRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_security_center_rest_lro_client(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a 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 - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_no_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_with_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_security_center_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SecurityCenterClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SecurityCenterClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.bulk_mute_findings._session - session2 = client2.transport.bulk_mute_findings._session - assert session1 != session2 - session1 = client1.transport.create_security_health_analytics_custom_module._session - session2 = client2.transport.create_security_health_analytics_custom_module._session - assert session1 != session2 - session1 = client1.transport.create_source._session - session2 = client2.transport.create_source._session - assert session1 != session2 - session1 = client1.transport.create_finding._session - session2 = client2.transport.create_finding._session - assert session1 != session2 - session1 = client1.transport.create_mute_config._session - session2 = client2.transport.create_mute_config._session - assert session1 != session2 - session1 = client1.transport.create_notification_config._session - session2 = client2.transport.create_notification_config._session - assert session1 != session2 - session1 = client1.transport.delete_mute_config._session - session2 = client2.transport.delete_mute_config._session - assert session1 != session2 - session1 = client1.transport.delete_notification_config._session - session2 = client2.transport.delete_notification_config._session - assert session1 != session2 - session1 = client1.transport.delete_security_health_analytics_custom_module._session - session2 = client2.transport.delete_security_health_analytics_custom_module._session - assert session1 != session2 - session1 = client1.transport.get_simulation._session - session2 = client2.transport.get_simulation._session - assert session1 != session2 - session1 = client1.transport.get_valued_resource._session - session2 = client2.transport.get_valued_resource._session - assert session1 != session2 - session1 = client1.transport.get_big_query_export._session - session2 = client2.transport.get_big_query_export._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.get_mute_config._session - session2 = client2.transport.get_mute_config._session - assert session1 != session2 - session1 = client1.transport.get_notification_config._session - session2 = client2.transport.get_notification_config._session - assert session1 != session2 - session1 = client1.transport.get_organization_settings._session - session2 = client2.transport.get_organization_settings._session - assert session1 != session2 - session1 = client1.transport.get_effective_security_health_analytics_custom_module._session - session2 = client2.transport.get_effective_security_health_analytics_custom_module._session - assert session1 != session2 - session1 = client1.transport.get_security_health_analytics_custom_module._session - session2 = client2.transport.get_security_health_analytics_custom_module._session - assert session1 != session2 - session1 = client1.transport.get_source._session - session2 = client2.transport.get_source._session - assert session1 != session2 - session1 = client1.transport.group_assets._session - session2 = client2.transport.group_assets._session - assert session1 != session2 - session1 = client1.transport.group_findings._session - session2 = client2.transport.group_findings._session - assert session1 != session2 - session1 = client1.transport.list_assets._session - session2 = client2.transport.list_assets._session - assert session1 != session2 - session1 = client1.transport.list_descendant_security_health_analytics_custom_modules._session - session2 = client2.transport.list_descendant_security_health_analytics_custom_modules._session - assert session1 != session2 - session1 = client1.transport.list_findings._session - session2 = client2.transport.list_findings._session - assert session1 != session2 - session1 = client1.transport.list_mute_configs._session - session2 = client2.transport.list_mute_configs._session - assert session1 != session2 - session1 = client1.transport.list_notification_configs._session - session2 = client2.transport.list_notification_configs._session - assert session1 != session2 - session1 = client1.transport.list_effective_security_health_analytics_custom_modules._session - session2 = client2.transport.list_effective_security_health_analytics_custom_modules._session - assert session1 != session2 - session1 = client1.transport.list_security_health_analytics_custom_modules._session - session2 = client2.transport.list_security_health_analytics_custom_modules._session - assert session1 != session2 - session1 = client1.transport.list_sources._session - session2 = client2.transport.list_sources._session - assert session1 != session2 - session1 = client1.transport.run_asset_discovery._session - session2 = client2.transport.run_asset_discovery._session - assert session1 != session2 - session1 = client1.transport.set_finding_state._session - session2 = client2.transport.set_finding_state._session - assert session1 != session2 - session1 = client1.transport.set_mute._session - session2 = client2.transport.set_mute._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 - session1 = client1.transport.simulate_security_health_analytics_custom_module._session - session2 = client2.transport.simulate_security_health_analytics_custom_module._session - assert session1 != session2 - session1 = client1.transport.update_external_system._session - session2 = client2.transport.update_external_system._session - assert session1 != session2 - session1 = client1.transport.update_finding._session - session2 = client2.transport.update_finding._session - assert session1 != session2 - session1 = client1.transport.update_mute_config._session - session2 = client2.transport.update_mute_config._session - assert session1 != session2 - session1 = client1.transport.update_notification_config._session - session2 = client2.transport.update_notification_config._session - assert session1 != session2 - session1 = client1.transport.update_organization_settings._session - session2 = client2.transport.update_organization_settings._session - assert session1 != session2 - session1 = client1.transport.update_security_health_analytics_custom_module._session - session2 = client2.transport.update_security_health_analytics_custom_module._session - assert session1 != session2 - session1 = client1.transport.update_source._session - session2 = client2.transport.update_source._session - assert session1 != session2 - session1 = client1.transport.update_security_marks._session - session2 = client2.transport.update_security_marks._session - assert session1 != session2 - session1 = client1.transport.create_big_query_export._session - session2 = client2.transport.create_big_query_export._session - assert session1 != session2 - session1 = client1.transport.delete_big_query_export._session - session2 = client2.transport.delete_big_query_export._session - assert session1 != session2 - session1 = client1.transport.update_big_query_export._session - session2 = client2.transport.update_big_query_export._session - assert session1 != session2 - session1 = client1.transport.list_big_query_exports._session - session2 = client2.transport.list_big_query_exports._session - assert session1 != session2 - session1 = client1.transport.create_event_threat_detection_custom_module._session - session2 = client2.transport.create_event_threat_detection_custom_module._session - assert session1 != session2 - session1 = client1.transport.delete_event_threat_detection_custom_module._session - session2 = client2.transport.delete_event_threat_detection_custom_module._session - assert session1 != session2 - session1 = client1.transport.get_event_threat_detection_custom_module._session - session2 = client2.transport.get_event_threat_detection_custom_module._session - assert session1 != session2 - session1 = client1.transport.list_descendant_event_threat_detection_custom_modules._session - session2 = client2.transport.list_descendant_event_threat_detection_custom_modules._session - assert session1 != session2 - session1 = client1.transport.list_event_threat_detection_custom_modules._session - session2 = client2.transport.list_event_threat_detection_custom_modules._session - assert session1 != session2 - session1 = client1.transport.update_event_threat_detection_custom_module._session - session2 = client2.transport.update_event_threat_detection_custom_module._session - assert session1 != session2 - session1 = client1.transport.validate_event_threat_detection_custom_module._session - session2 = client2.transport.validate_event_threat_detection_custom_module._session - assert session1 != session2 - session1 = client1.transport.get_effective_event_threat_detection_custom_module._session - session2 = client2.transport.get_effective_event_threat_detection_custom_module._session - assert session1 != session2 - session1 = client1.transport.list_effective_event_threat_detection_custom_modules._session - session2 = client2.transport.list_effective_event_threat_detection_custom_modules._session - assert session1 != session2 - session1 = client1.transport.batch_create_resource_value_configs._session - session2 = client2.transport.batch_create_resource_value_configs._session - assert session1 != session2 - session1 = client1.transport.delete_resource_value_config._session - session2 = client2.transport.delete_resource_value_config._session - assert session1 != session2 - session1 = client1.transport.get_resource_value_config._session - session2 = client2.transport.get_resource_value_config._session - assert session1 != session2 - session1 = client1.transport.list_resource_value_configs._session - session2 = client2.transport.list_resource_value_configs._session - assert session1 != session2 - session1 = client1.transport.update_resource_value_config._session - session2 = client2.transport.update_resource_value_config._session - assert session1 != session2 - session1 = client1.transport.list_valued_resources._session - session2 = client2.transport.list_valued_resources._session - assert session1 != session2 - session1 = client1.transport.list_attack_paths._session - session2 = client2.transport.list_attack_paths._session - assert session1 != session2 -def test_security_center_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcTransport( - 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_security_center_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcAsyncIOTransport( - 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(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_security_center_grpc_lro_client(): - client = SecurityCenterClient( - 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_security_center_grpc_lro_async_client(): - client = SecurityCenterAsyncClient( - 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_asset_path(): - organization = "squid" - asset = "clam" - expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.asset_path(organization, asset) - assert expected == actual - - -def test_parse_asset_path(): - expected = { - "organization": "whelk", - "asset": "octopus", - } - path = SecurityCenterClient.asset_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_asset_path(path) - assert expected == actual - -def test_attack_path_path(): - organization = "oyster" - simulation = "nudibranch" - valued_resource = "cuttlefish" - attack_path = "mussel" - expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) - actual = SecurityCenterClient.attack_path_path(organization, simulation, valued_resource, attack_path) - assert expected == actual - - -def test_parse_attack_path_path(): - expected = { - "organization": "winkle", - "simulation": "nautilus", - "valued_resource": "scallop", - "attack_path": "abalone", - } - path = SecurityCenterClient.attack_path_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_attack_path_path(path) - assert expected == actual - -def test_big_query_export_path(): - organization = "squid" - export = "clam" - expected = "organizations/{organization}/bigQueryExports/{export}".format(organization=organization, export=export, ) - actual = SecurityCenterClient.big_query_export_path(organization, export) - assert expected == actual - - -def test_parse_big_query_export_path(): - expected = { - "organization": "whelk", - "export": "octopus", - } - path = SecurityCenterClient.big_query_export_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_big_query_export_path(path) - assert expected == actual - -def test_dlp_job_path(): - project = "oyster" - dlp_job = "nudibranch" - expected = "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) - actual = SecurityCenterClient.dlp_job_path(project, dlp_job) - assert expected == actual - - -def test_parse_dlp_job_path(): - expected = { - "project": "cuttlefish", - "dlp_job": "mussel", - } - path = SecurityCenterClient.dlp_job_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_dlp_job_path(path) - assert expected == actual - -def test_effective_event_threat_detection_custom_module_path(): - organization = "winkle" - module = "nautilus" - expected = "organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}".format(organization=organization, module=module, ) - actual = SecurityCenterClient.effective_event_threat_detection_custom_module_path(organization, module) - assert expected == actual - - -def test_parse_effective_event_threat_detection_custom_module_path(): - expected = { - "organization": "scallop", - "module": "abalone", - } - path = SecurityCenterClient.effective_event_threat_detection_custom_module_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_effective_event_threat_detection_custom_module_path(path) - assert expected == actual - -def test_effective_security_health_analytics_custom_module_path(): - organization = "squid" - effective_custom_module = "clam" - expected = "organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{effective_custom_module}".format(organization=organization, effective_custom_module=effective_custom_module, ) - actual = SecurityCenterClient.effective_security_health_analytics_custom_module_path(organization, effective_custom_module) - assert expected == actual - - -def test_parse_effective_security_health_analytics_custom_module_path(): - expected = { - "organization": "whelk", - "effective_custom_module": "octopus", - } - path = SecurityCenterClient.effective_security_health_analytics_custom_module_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_effective_security_health_analytics_custom_module_path(path) - assert expected == actual - -def test_event_threat_detection_custom_module_path(): - organization = "oyster" - module = "nudibranch" - expected = "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}".format(organization=organization, module=module, ) - actual = SecurityCenterClient.event_threat_detection_custom_module_path(organization, module) - assert expected == actual - - -def test_parse_event_threat_detection_custom_module_path(): - expected = { - "organization": "cuttlefish", - "module": "mussel", - } - path = SecurityCenterClient.event_threat_detection_custom_module_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_event_threat_detection_custom_module_path(path) - assert expected == actual - -def test_external_system_path(): - organization = "winkle" - source = "nautilus" - finding = "scallop" - externalsystem = "abalone" - expected = "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) - actual = SecurityCenterClient.external_system_path(organization, source, finding, externalsystem) - assert expected == actual - - -def test_parse_external_system_path(): - expected = { - "organization": "squid", - "source": "clam", - "finding": "whelk", - "externalsystem": "octopus", - } - path = SecurityCenterClient.external_system_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_external_system_path(path) - assert expected == actual - -def test_finding_path(): - organization = "oyster" - source = "nudibranch" - finding = "cuttlefish" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - actual = SecurityCenterClient.finding_path(organization, source, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "organization": "mussel", - "source": "winkle", - "finding": "nautilus", - } - path = SecurityCenterClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_finding_path(path) - assert expected == actual - -def test_mute_config_path(): - organization = "scallop" - mute_config = "abalone" - expected = "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) - actual = SecurityCenterClient.mute_config_path(organization, mute_config) - assert expected == actual - - -def test_parse_mute_config_path(): - expected = { - "organization": "squid", - "mute_config": "clam", - } - path = SecurityCenterClient.mute_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_mute_config_path(path) - assert expected == actual - -def test_notification_config_path(): - organization = "whelk" - notification_config = "octopus" - expected = "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) - actual = SecurityCenterClient.notification_config_path(organization, notification_config) - assert expected == actual - - -def test_parse_notification_config_path(): - expected = { - "organization": "oyster", - "notification_config": "nudibranch", - } - path = SecurityCenterClient.notification_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_notification_config_path(path) - assert expected == actual - -def test_organization_settings_path(): - organization = "cuttlefish" - expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) - actual = SecurityCenterClient.organization_settings_path(organization) - assert expected == actual - - -def test_parse_organization_settings_path(): - expected = { - "organization": "mussel", - } - path = SecurityCenterClient.organization_settings_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_organization_settings_path(path) - assert expected == actual - -def test_policy_path(): - organization = "winkle" - constraint_name = "nautilus" - expected = "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) - actual = SecurityCenterClient.policy_path(organization, constraint_name) - assert expected == actual - - -def test_parse_policy_path(): - expected = { - "organization": "scallop", - "constraint_name": "abalone", - } - path = SecurityCenterClient.policy_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_policy_path(path) - assert expected == actual - -def test_resource_value_config_path(): - organization = "squid" - resource_value_config = "clam" - expected = "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) - actual = SecurityCenterClient.resource_value_config_path(organization, resource_value_config) - assert expected == actual - - -def test_parse_resource_value_config_path(): - expected = { - "organization": "whelk", - "resource_value_config": "octopus", - } - path = SecurityCenterClient.resource_value_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_resource_value_config_path(path) - assert expected == actual - -def test_security_health_analytics_custom_module_path(): - organization = "oyster" - custom_module = "nudibranch" - expected = "organizations/{organization}/securityHealthAnalyticsSettings/customModules/{custom_module}".format(organization=organization, custom_module=custom_module, ) - actual = SecurityCenterClient.security_health_analytics_custom_module_path(organization, custom_module) - assert expected == actual - - -def test_parse_security_health_analytics_custom_module_path(): - expected = { - "organization": "cuttlefish", - "custom_module": "mussel", - } - path = SecurityCenterClient.security_health_analytics_custom_module_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_security_health_analytics_custom_module_path(path) - assert expected == actual - -def test_security_marks_path(): - organization = "winkle" - asset = "nautilus" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.security_marks_path(organization, asset) - assert expected == actual - - -def test_parse_security_marks_path(): - expected = { - "organization": "scallop", - "asset": "abalone", - } - path = SecurityCenterClient.security_marks_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_security_marks_path(path) - assert expected == actual - -def test_simulation_path(): - organization = "squid" - simulation = "clam" - expected = "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) - actual = SecurityCenterClient.simulation_path(organization, simulation) - assert expected == actual - - -def test_parse_simulation_path(): - expected = { - "organization": "whelk", - "simulation": "octopus", - } - path = SecurityCenterClient.simulation_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_simulation_path(path) - assert expected == actual - -def test_source_path(): - organization = "oyster" - source = "nudibranch" - expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - actual = SecurityCenterClient.source_path(organization, source) - assert expected == actual - - -def test_parse_source_path(): - expected = { - "organization": "cuttlefish", - "source": "mussel", - } - path = SecurityCenterClient.source_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_source_path(path) - assert expected == actual - -def test_table_data_profile_path(): - project = "winkle" - table_profile = "nautilus" - expected = "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) - actual = SecurityCenterClient.table_data_profile_path(project, table_profile) - assert expected == actual - - -def test_parse_table_data_profile_path(): - expected = { - "project": "scallop", - "table_profile": "abalone", - } - path = SecurityCenterClient.table_data_profile_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_table_data_profile_path(path) - assert expected == actual - -def test_topic_path(): - project = "squid" - topic = "clam" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = SecurityCenterClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "whelk", - "topic": "octopus", - } - path = SecurityCenterClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_topic_path(path) - assert expected == actual - -def test_valued_resource_path(): - organization = "oyster" - simulation = "nudibranch" - valued_resource = "cuttlefish" - expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) - actual = SecurityCenterClient.valued_resource_path(organization, simulation, valued_resource) - assert expected == actual - - -def test_parse_valued_resource_path(): - expected = { - "organization": "mussel", - "simulation": "winkle", - "valued_resource": "nautilus", - } - path = SecurityCenterClient.valued_resource_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_valued_resource_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SecurityCenterClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = SecurityCenterClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = SecurityCenterClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = SecurityCenterClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SecurityCenterClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = SecurityCenterClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = SecurityCenterClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = SecurityCenterClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SecurityCenterClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = SecurityCenterClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - transport_class = SecurityCenterClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations/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 = 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.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations/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 = 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_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations/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() - - # 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 - - 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(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations'}, 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() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations'} - request = request_type(**request_init) - # Mock the http request call within the method and 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.ListOperationsResponse() - - # 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 - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), -]) -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-securitycenter/v1beta1/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v1beta1/.coveragerc deleted file mode 100644 index 45cb273f8f7c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/securitycenter/__init__.py - google/cloud/securitycenter/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-securitycenter/v1beta1/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v1beta1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/.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-securitycenter/v1beta1/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v1beta1/MANIFEST.in deleted file mode 100644 index 328e3b8929b0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/securitycenter *.py -recursive-include google/cloud/securitycenter_v1beta1 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst deleted file mode 100644 index f8c63f4cb48a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v1beta1/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/conf.py deleted file mode 100644 index 8e92d2319721..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter 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-securitycenter" -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-securitycenter-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-securitycenter.tex", - u"google-cloud-securitycenter 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-securitycenter", - u"Google Cloud Securitycenter 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-securitycenter", - u"google-cloud-securitycenter Documentation", - author, - "google-cloud-securitycenter", - "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v1beta1/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/index.rst deleted file mode 100644 index 883606269b5e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - securitycenter_v1beta1/services - securitycenter_v1beta1/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst deleted file mode 100644 index 304849ecc112..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst +++ /dev/null @@ -1,10 +0,0 @@ -SecurityCenter --------------------------------- - -.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center - :members: - :inherited-members: - -.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst deleted file mode 100644 index a09a4b86906d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Securitycenter v1beta1 API -==================================================== -.. toctree:: - :maxdepth: 2 - - security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst deleted file mode 100644 index 0bbeba064657..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Securitycenter v1beta1 API -================================================= - -.. automodule:: google.cloud.securitycenter_v1beta1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__init__.py deleted file mode 100644 index 34bcf9197d85..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__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.cloud.securitycenter import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.securitycenter_v1beta1.services.security_center.client import SecurityCenterClient -from google.cloud.securitycenter_v1beta1.services.security_center.async_client import SecurityCenterAsyncClient - -from google.cloud.securitycenter_v1beta1.types.asset import Asset -from google.cloud.securitycenter_v1beta1.types.finding import Finding -from google.cloud.securitycenter_v1beta1.types.organization_settings import OrganizationSettings -from google.cloud.securitycenter_v1beta1.types.run_asset_discovery_response import RunAssetDiscoveryResponse -from google.cloud.securitycenter_v1beta1.types.security_marks import SecurityMarks -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import CreateFindingRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import CreateSourceRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GetOrganizationSettingsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GetSourceRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupAssetsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupAssetsResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupFindingsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupFindingsResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupResult -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListAssetsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListAssetsResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListFindingsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListFindingsResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListSourcesRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListSourcesResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import RunAssetDiscoveryRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import SetFindingStateRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateFindingRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateOrganizationSettingsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateSecurityMarksRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateSourceRequest -from google.cloud.securitycenter_v1beta1.types.source import Source - -__all__ = ('SecurityCenterClient', - 'SecurityCenterAsyncClient', - 'Asset', - 'Finding', - 'OrganizationSettings', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateSourceRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/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-securitycenter/v1beta1/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py deleted file mode 100644 index 4f049ee47efe..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__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.cloud.securitycenter_v1beta1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.security_center import SecurityCenterClient -from .services.security_center import SecurityCenterAsyncClient - -from .types.asset import Asset -from .types.finding import Finding -from .types.organization_settings import OrganizationSettings -from .types.run_asset_discovery_response import RunAssetDiscoveryResponse -from .types.security_marks import SecurityMarks -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import GetOrganizationSettingsRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GroupAssetsRequest -from .types.securitycenter_service import GroupAssetsResponse -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAssetsRequest -from .types.securitycenter_service import ListAssetsResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import RunAssetDiscoveryRequest -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateOrganizationSettingsRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.source import Source - -__all__ = ( - 'SecurityCenterAsyncClient', -'Asset', -'CreateFindingRequest', -'CreateSourceRequest', -'Finding', -'GetOrganizationSettingsRequest', -'GetSourceRequest', -'GroupAssetsRequest', -'GroupAssetsResponse', -'GroupFindingsRequest', -'GroupFindingsResponse', -'GroupResult', -'ListAssetsRequest', -'ListAssetsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListSourcesRequest', -'ListSourcesResponse', -'OrganizationSettings', -'RunAssetDiscoveryRequest', -'RunAssetDiscoveryResponse', -'SecurityCenterClient', -'SecurityMarks', -'SetFindingStateRequest', -'Source', -'UpdateFindingRequest', -'UpdateOrganizationSettingsRequest', -'UpdateSecurityMarksRequest', -'UpdateSourceRequest', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json deleted file mode 100644 index afd9dcb019c2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json +++ /dev/null @@ -1,298 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.securitycenter_v1beta1", - "protoPackage": "google.cloud.securitycenter.v1beta1", - "schema": "1.0", - "services": { - "SecurityCenter": { - "clients": { - "grpc": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SecurityCenterAsyncClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "rest": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/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-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/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-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py deleted file mode 100644 index bffcff5da306..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - 'SecurityCenterClient', - 'SecurityCenterAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py deleted file mode 100644 index 6e93123eb92f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.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. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.securitycenter_v1beta1 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.securitycenter_v1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V1 Beta APIs for Security Center service.""" - - _client: SecurityCenterClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE - - asset_path = staticmethod(SecurityCenterClient.asset_path) - parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) - parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) - organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) - parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) - source_path = staticmethod(SecurityCenterClient.source_path) - parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) - common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) - parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) - common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) - parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) - parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) - parse_common_location_path = staticmethod(SecurityCenterClient.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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v1beta1 - - async def sample_create_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.CreateSourceRequest, dict]]): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = 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_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding_id: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_create_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.CreateFindingRequest, dict]]): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 get_organization_settings(self, - request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest, dict]]): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_organization_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 get_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v1beta1 - - async def sample_get_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GetSourceRequest, dict]]): - The request object. Request message for getting a source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 group_assets(self, - request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsAsyncPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_group_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest, dict]]): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsAsyncPager: - Response message for grouping by - assets. - 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, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.GroupAssetsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_group_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest, dict]]): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state``). The string value - should follow SQL syntax: comma separated list of - fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_assets(self, - request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsAsyncPager: - r"""Lists an organization's assets. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_list_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.ListAssetsRequest, dict]]): - The request object. Request message for listing assets. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsAsyncPager: - Response message for listing assets. - - 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, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(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_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListAssetsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings(self, - request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_list_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListFindingsRequest( - parent="parent_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.securitycenter_v1beta1.types.ListFindingsRequest, dict]]): - The request object. Request message for listing findings. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.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_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_list_sources(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.ListSourcesRequest, dict]]): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id]". - - 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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesAsyncPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_asset_discovery(self, - request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), - ) -> operation_async.AsyncOperation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS 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 securitycenter_v1beta1 - - async def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest, dict]]): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.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([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, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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, - empty_pb2.Empty, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - async def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - start_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of 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 securitycenter_v1beta1 - - async def sample_set_finding_state(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest, dict]]): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`google.cloud.securitycenter_v1beta1.types.Finding.State`): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 update_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_update_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest, dict]]): - The request object. Request message for updating or - creating a finding. - finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe domain. - self._client._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_organization_settings(self, - request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, - *, - organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = await client.update_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest, dict]]): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`google.cloud.securitycenter_v1beta1.types.OrganizationSettings`): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_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 update_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v1beta1 - - async def sample_update_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest, dict]]): - The request object. Request message for updating a - source. - source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): - Required. The source resource to - update. - - This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_update_security_marks(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest, dict]]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`google.cloud.securitycenter_v1beta1.types.SecurityMarks`): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe domain. - self._client._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) -> "SecurityCenterAsyncClient": - 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__ = ( - "SecurityCenterAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py deleted file mode 100644 index 72d03d765968..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py +++ /dev/null @@ -1,2755 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_v1beta1 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.securitycenter_v1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .transports.rest import SecurityCenterRestTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - _transport_registry["rest"] = SecurityCenterRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SecurityCenterTransport]: - """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V1 Beta APIs for Security Center 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 = "securitycenter.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: - SecurityCenterClient: 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: - SecurityCenterClient: 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) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def asset_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified asset string.""" - return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_asset_path(path: str) -> Dict[str,str]: - """Parses a asset path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def finding_path(organization: str,source: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def organization_settings_path(organization: str,) -> str: - """Returns a fully-qualified organization_settings string.""" - return "organizations/{organization}/organizationSettings".format(organization=organization, ) - - @staticmethod - def parse_organization_settings_path(path: str) -> Dict[str,str]: - """Parses a organization_settings path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str,str]: - """Parses a security_marks path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str,source: str,) -> str: - """Returns a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str,str]: - """Parses a source path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 - SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient._read_environment_variables() - self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) - if transport_provided: - # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( - type(self).get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., SecurityCenterTransport], 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_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v1beta1 - - def sample_create_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.CreateSourceRequest, dict]): - The request object. Request message for creating a - source. - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (google.cloud.securitycenter_v1beta1.types.Source): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding_id: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_create_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.CreateFindingRequest, dict]): - The request object. Request message for creating a - finding. - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (google.cloud.securitycenter_v1beta1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 get_organization_settings(self, - request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest, dict]): - The request object. Request message for getting - organization settings. - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_organization_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 get_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v1beta1 - - def sample_get_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.GetSourceRequest, dict]): - The request object. Request message for getting a source. - name (str): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 group_assets(self, - request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_group_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest, dict]): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsPager: - Response message for grouping by - assets. - 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, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.GroupAssetsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_group_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest, dict]): - The request object. Request message for grouping by - findings. - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (str): - Required. Expression that defines what assets fields to - use for grouping (including ``state``). The string value - should follow SQL syntax: comma separated list of - fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_assets(self, - request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsPager: - r"""Lists an organization's assets. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_list_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.ListAssetsRequest, dict]): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsPager: - Response message for listing assets. - - 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, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListAssetsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings(self, - request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_list_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListFindingsRequest( - parent="parent_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.securitycenter_v1beta1.types.ListFindingsRequest, dict]): - The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsPager: - Response message for listing - findings. - 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.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_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_list_sources(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.ListSourcesRequest, dict]): - The request object. Request message for listing sources. - parent (str): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id]". - - 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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_asset_discovery(self, - request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), - ) -> operation.Operation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS 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 securitycenter_v1beta1 - - def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest, dict]): - The request object. Request message for running asset - discovery for an organization. - parent (str): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.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([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, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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, - empty_pb2.Empty, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - start_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of 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 securitycenter_v1beta1 - - def sample_set_finding_state(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest, dict]): - The request object. Request message for updating a - finding's state. - name (str): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (google.cloud.securitycenter_v1beta1.types.Finding.State): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # 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 - - def update_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_update_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest, dict]): - The request object. Request message for updating or - creating a finding. - finding (google.cloud.securitycenter_v1beta1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe 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_organization_settings(self, - request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, - *, - organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = client.update_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest, dict]): - The request object. Request message for updating an - organization's settings. - organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_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 update_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v1beta1 - - def sample_update_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest, dict]): - The request object. Request message for updating a - source. - source (google.cloud.securitycenter_v1beta1.types.Source): - Required. The source resource to - update. - - This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_update_security_marks(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest, dict]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe 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) -> "SecurityCenterClient": - 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__ = ( - "SecurityCenterClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py deleted file mode 100644 index 51807c4b0d79..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.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 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.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source - - -class GroupAssetsPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupAssetsResponse], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1beta1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - 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[securitycenter_service.GroupAssetsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupAssetsAsyncPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` - attributes are available on the 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[securitycenter_service.GroupAssetsResponse]], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1beta1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - 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[securitycenter_service.GroupAssetsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1beta1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` - attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1beta1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListAssetsResponse], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - 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[securitycenter_service.ListAssetsResponse]: - 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - for page in self.pages: - yield from page.list_assets_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` - attributes are available on the 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[securitycenter_service.ListAssetsResponse]], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - 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[securitycenter_service.ListAssetsResponse]: - 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_assets_results: - 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.securitycenter_v1beta1.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.securitycenter_v1beta1.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[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v1beta1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.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 = securitycenter_service.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[securitycenter_service.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.securitycenter_v1beta1.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.securitycenter_v1beta1.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[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v1beta1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.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 = securitycenter_service.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[securitycenter_service.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) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1beta1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` - attributes are available on the 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[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1beta1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.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-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py deleted file mode 100644 index 9d36139c1a9b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/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 SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .rest import SecurityCenterRestTransport -from .rest import SecurityCenterRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry['grpc'] = SecurityCenterGrpcTransport -_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport -_transport_registry['rest'] = SecurityCenterRestTransport - -__all__ = ( - 'SecurityCenterTransport', - 'SecurityCenterGrpcTransport', - 'SecurityCenterGrpcAsyncIOTransport', - 'SecurityCenterRestTransport', - 'SecurityCenterRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py deleted file mode 100644 index 9c83124b6382..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py +++ /dev/null @@ -1,498 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.securitycenter_v1beta1 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.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -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 SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'securitycenter.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.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: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_source: gapic_v1.method.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_organization_settings: gapic_v1.method.wrap_method( - self.get_organization_settings, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_source: gapic_v1.method.wrap_method( - self.get_source, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.group_assets: gapic_v1.method.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_sources: gapic_v1.method.wrap_method( - self.list_sources, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.run_asset_discovery: gapic_v1.method.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_finding: gapic_v1.method.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=480.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 operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - 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 get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Union[ - organization_settings.OrganizationSettings, - Awaitable[organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Union[ - source.Source, - Awaitable[source.Source] - ]]: - raise NotImplementedError() - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Union[ - securitycenter_service.GroupAssetsResponse, - Awaitable[securitycenter_service.GroupAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Union[ - securitycenter_service.GroupFindingsResponse, - Awaitable[securitycenter_service.GroupFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Union[ - securitycenter_service.ListAssetsResponse, - Awaitable[securitycenter_service.ListAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Union[ - securitycenter_service.ListFindingsResponse, - Awaitable[securitycenter_service.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Union[ - securitycenter_service.ListSourcesResponse, - Awaitable[securitycenter_service.ListSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - 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 test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Union[ - gcs_organization_settings.OrganizationSettings, - Awaitable[gcs_organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Union[ - gcs_security_marks.SecurityMarks, - Awaitable[gcs_security_marks.SecurityMarks] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SecurityCenterTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py deleted file mode 100644 index bd93a5f13210..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.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. -# -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.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -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 SecurityCenterTransport, DEFAULT_CLIENT_INFO - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V1 Beta APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: 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 create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - ~.GroupAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - 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.securitycenter.v1beta1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - operations_pb2.Operation]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - ~.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 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - ~.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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SecurityCenterGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index 47e586023e58..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,945 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -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 SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V1 Beta APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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._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 create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - 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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Awaitable[organization_settings.OrganizationSettings]]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Awaitable[securitycenter_service.GroupAssetsResponse]]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - Awaitable[~.GroupAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse]]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Awaitable[securitycenter_service.ListAssetsResponse]]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - 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.securitycenter.v1beta1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse]]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - 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 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - 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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.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.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - 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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Awaitable[gcs_organization_settings.OrganizationSettings]]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks]]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - 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_source: gapic_v1.method_async.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method_async.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( - self.get_iam_policy, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_organization_settings: gapic_v1.method_async.wrap_method( - self.get_organization_settings, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_source: gapic_v1.method_async.wrap_method( - self.get_source, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.group_assets: gapic_v1.method_async.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method_async.wrap_method( - self.group_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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method_async.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method_async.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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_sources: gapic_v1.method_async.wrap_method( - self.list_sources, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.run_asset_discovery: gapic_v1.method_async.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method_async.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( - self.test_iam_permissions, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_finding: gapic_v1.method_async.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method_async.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method_async.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method_async.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py deleted file mode 100644 index a44f2b2a1487..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py +++ /dev/null @@ -1,2542 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # 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 path_template -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 -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -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.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -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 SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SecurityCenterRestInterceptor: - """Interceptor for SecurityCenter. - - 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 SecurityCenterRestTransport. - - .. code-block:: python - class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): - def pre_create_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_organization_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_organization_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_assets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_assets(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_sources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_sources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_run_asset_discovery(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_run_asset_discovery(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_finding_state(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_finding_state(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_organization_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_organization_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_security_marks(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_security_marks(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_source(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) - client = SecurityCenterClient(transport=transport) - - - """ - def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for create_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for create_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_organization_settings(self, request: securitycenter_service.GetOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_organization_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_organization_settings(self, response: organization_settings.OrganizationSettings) -> organization_settings.OrganizationSettings: - """Post-rpc interceptor for get_organization_settings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_source(self, response: source.Source) -> source.Source: - """Post-rpc interceptor for get_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_assets(self, request: securitycenter_service.GroupAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_assets(self, response: securitycenter_service.GroupAssetsResponse) -> securitycenter_service.GroupAssetsResponse: - """Post-rpc interceptor for group_assets - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: - """Post-rpc interceptor for group_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_assets(self, request: securitycenter_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_assets(self, response: securitycenter_service.ListAssetsResponse) -> securitycenter_service.ListAssetsResponse: - """Post-rpc interceptor for list_assets - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. - """ - return request, metadata - - def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: - """Post-rpc interceptor for list_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_sources - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: - """Post-rpc interceptor for list_sources - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_run_asset_discovery(self, request: securitycenter_service.RunAssetDiscoveryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.RunAssetDiscoveryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for run_asset_discovery - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_run_asset_discovery(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for run_asset_discovery - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for update_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_organization_settings(self, request: securitycenter_service.UpdateOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_organization_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_organization_settings(self, response: gcs_organization_settings.OrganizationSettings) -> gcs_organization_settings.OrganizationSettings: - """Post-rpc interceptor for update_organization_settings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: - """Post-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for update_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SecurityCenterRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SecurityCenterRestInterceptor - - -class SecurityCenterRestTransport(SecurityCenterTransport): - """REST backend transport for SecurityCenter. - - V1 Beta APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SecurityCenterRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 - 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 - ) - 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 SecurityCenterRestInterceptor() - 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': '/v1beta1/{name=organizations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1beta1/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta1/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta1/{name=organizations/*/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="v1beta1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "findingId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the create finding method over HTTP. - - Args: - request (~.securitycenter_service.CreateFindingRequest): - The request object. Request message for creating a - finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=organizations/*/sources/*}/findings', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_create_finding(request, metadata) - pb_request = securitycenter_service.CreateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_finding(resp) - return resp - - class _CreateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the create source method over HTTP. - - Args: - request (~.securitycenter_service.CreateSourceRequest): - The request object. Request message for creating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=organizations/*}/sources', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_create_source(request, metadata) - pb_request = securitycenter_service.CreateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_source(resp) - return resp - - class _GetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{resource=organizations/*/sources/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _GetOrganizationSettings(SecurityCenterRestStub): - def __hash__(self): - return hash("GetOrganizationSettings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetOrganizationSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> organization_settings.OrganizationSettings: - r"""Call the get organization settings method over HTTP. - - Args: - request (~.securitycenter_service.GetOrganizationSettingsRequest): - The request object. Request message for getting - organization 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: - ~.organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{name=organizations/*/organizationSettings}', - }, - ] - request, metadata = self._interceptor.pre_get_organization_settings(request, metadata) - pb_request = securitycenter_service.GetOrganizationSettingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = organization_settings.OrganizationSettings() - pb_resp = organization_settings.OrganizationSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_organization_settings(resp) - return resp - - class _GetSource(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> source.Source: - r"""Call the get source method over HTTP. - - Args: - request (~.securitycenter_service.GetSourceRequest): - The request object. Request message for getting a source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{name=organizations/*/sources/*}', - }, - ] - request, metadata = self._interceptor.pre_get_source(request, metadata) - pb_request = securitycenter_service.GetSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = source.Source() - pb_resp = source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_source(resp) - return resp - - class _GroupAssets(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupAssets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupAssetsResponse: - r"""Call the group assets method over HTTP. - - Args: - request (~.securitycenter_service.GroupAssetsRequest): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupAssetsResponse: - Response message for grouping by - assets. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=organizations/*}/assets:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_assets(request, metadata) - pb_request = securitycenter_service.GroupAssetsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupAssetsResponse() - pb_resp = securitycenter_service.GroupAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_assets(resp) - return resp - - class _GroupFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupFindingsResponse: - r"""Call the group findings method over HTTP. - - Args: - request (~.securitycenter_service.GroupFindingsRequest): - The request object. Request message for grouping by - findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupFindingsResponse: - Response message for group by - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=organizations/*/sources/*}/findings:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_findings(request, metadata) - pb_request = securitycenter_service.GroupFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupFindingsResponse() - pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_findings(resp) - return resp - - class _ListAssets(SecurityCenterRestStub): - def __hash__(self): - return hash("ListAssets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListAssetsResponse: - r"""Call the list assets method over HTTP. - - Args: - request (~.securitycenter_service.ListAssetsRequest): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListAssetsResponse: - Response message for listing assets. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{parent=organizations/*}/assets', - }, - ] - request, metadata = self._interceptor.pre_list_assets(request, metadata) - pb_request = securitycenter_service.ListAssetsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListAssetsResponse() - pb_resp = securitycenter_service.ListAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_assets(resp) - return resp - - class _ListFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("ListFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListFindingsResponse: - r"""Call the list findings method over HTTP. - - Args: - request (~.securitycenter_service.ListFindingsRequest): - The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListFindingsResponse: - Response message for listing - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{parent=organizations/*/sources/*}/findings', - }, - ] - request, metadata = self._interceptor.pre_list_findings(request, metadata) - pb_request = securitycenter_service.ListFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListFindingsResponse() - pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_findings(resp) - return resp - - class _ListSources(SecurityCenterRestStub): - def __hash__(self): - return hash("ListSources") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListSourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListSourcesResponse: - r"""Call the list sources method over HTTP. - - Args: - request (~.securitycenter_service.ListSourcesRequest): - The request object. Request message for listing sources. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListSourcesResponse: - Response message for listing sources. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{parent=organizations/*}/sources', - }, - ] - request, metadata = self._interceptor.pre_list_sources(request, metadata) - pb_request = securitycenter_service.ListSourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListSourcesResponse() - pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_sources(resp) - return resp - - class _RunAssetDiscovery(SecurityCenterRestStub): - def __hash__(self): - return hash("RunAssetDiscovery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.RunAssetDiscoveryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the run asset discovery method over HTTP. - - Args: - request (~.securitycenter_service.RunAssetDiscoveryRequest): - The request object. Request message for running asset - discovery for an organization. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=organizations/*}/assets:runDiscovery', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_run_asset_discovery(request, metadata) - pb_request = securitycenter_service.RunAssetDiscoveryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_run_asset_discovery(resp) - return resp - - class _SetFindingState(SecurityCenterRestStub): - def __hash__(self): - return hash("SetFindingState") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SetFindingStateRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the set finding state method over HTTP. - - Args: - request (~.securitycenter_service.SetFindingStateRequest): - The request object. Request message for updating a - finding's state. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{name=organizations/*/sources/*/findings/*}:setState', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_finding_state(request, metadata) - pb_request = securitycenter_service.SetFindingStateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_set_finding_state(resp) - return resp - - class _SetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{resource=organizations/*/sources/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _TestIamPermissions(SecurityCenterRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{resource=organizations/*/sources/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UpdateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the update finding method over HTTP. - - Args: - request (~.securitycenter_service.UpdateFindingRequest): - The request object. Request message for updating or - creating a finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta1/{finding.name=organizations/*/sources/*/findings/*}', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_update_finding(request, metadata) - pb_request = securitycenter_service.UpdateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_finding(resp) - return resp - - class _UpdateOrganizationSettings(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateOrganizationSettings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateOrganizationSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Call the update organization - settings method over HTTP. - - Args: - request (~.securitycenter_service.UpdateOrganizationSettingsRequest): - The request object. Request message for updating an - organization's 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: - ~.gcs_organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta1/{organization_settings.name=organizations/*/organizationSettings}', - 'body': 'organization_settings', - }, - ] - request, metadata = self._interceptor.pre_update_organization_settings(request, metadata) - pb_request = securitycenter_service.UpdateOrganizationSettingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_organization_settings.OrganizationSettings() - pb_resp = gcs_organization_settings.OrganizationSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_organization_settings(resp) - return resp - - class _UpdateSecurityMarks(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSecurityMarks") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSecurityMarksRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_security_marks.SecurityMarks: - r"""Call the update security marks method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSecurityMarksRequest): - The request object. Request message for updating a - SecurityMarks resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1beta1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, - ] - request, metadata = self._interceptor.pre_update_security_marks(request, metadata) - pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_security_marks.SecurityMarks() - pb_resp = gcs_security_marks.SecurityMarks.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_security_marks(resp) - return resp - - class _UpdateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the update source method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSourceRequest): - The request object. Request message for updating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta1/{source.name=organizations/*/sources/*}', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_update_source(request, metadata) - pb_request = securitycenter_service.UpdateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_source(resp) - return resp - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.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_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSources(self._session, self._host, self._interceptor) # type: ignore - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - 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._RunAssetDiscovery(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SecurityCenterRestTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py deleted file mode 100644 index d3d5b965f804..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py +++ /dev/null @@ -1,86 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .asset import ( - Asset, -) -from .finding import ( - Finding, -) -from .organization_settings import ( - OrganizationSettings, -) -from .run_asset_discovery_response import ( - RunAssetDiscoveryResponse, -) -from .security_marks import ( - SecurityMarks, -) -from .securitycenter_service import ( - CreateFindingRequest, - CreateSourceRequest, - GetOrganizationSettingsRequest, - GetSourceRequest, - GroupAssetsRequest, - GroupAssetsResponse, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListAssetsRequest, - ListAssetsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListSourcesRequest, - ListSourcesResponse, - RunAssetDiscoveryRequest, - SetFindingStateRequest, - UpdateFindingRequest, - UpdateOrganizationSettingsRequest, - UpdateSecurityMarksRequest, - UpdateSourceRequest, -) -from .source import ( - Source, -) - -__all__ = ( - 'Asset', - 'Finding', - 'OrganizationSettings', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateSourceRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py deleted file mode 100644 index 16ad84206b64..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py +++ /dev/null @@ -1,155 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'Asset', - }, -) - - -class Asset(proto.Message): - r"""Security Command Center representation of a Google Cloud - resource. - - The Asset is a Security Command Center resource that captures - information about a single Google Cloud resource. All - modifications to an Asset are only within the context of - Security Command Center and don't affect the referenced Google - Cloud resource. - - Attributes: - name (str): - The relative resource name of this asset. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (google.cloud.securitycenter_v1beta1.types.Asset.SecurityCenterProperties): - Security Command Center managed properties. - These properties are managed by Security Command - Center and cannot be modified by the user. - resource_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Resource managed properties. These properties - are managed and defined by the Google Cloud - resource and cannot be modified by the user. - security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): - User specified security marks. These marks - are entirely managed by the user and come from - the SecurityMarks resource that belongs to the - asset. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was created in - Security Command Center. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was last updated, - added, or deleted in Security Command Center. - """ - - class SecurityCenterProperties(proto.Message): - r"""Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified by - the user. - - Attributes: - resource_name (str): - Immutable. The full resource name of the Google Cloud - resource this asset represents. This field is immutable - after create time. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_type (str): - The type of the Google Cloud resource. - Examples include: APPLICATION, PROJECT, and - ORGANIZATION. This is a case insensitive field - defined by Security Command Center and/or the - producer of the resource and is immutable after - create time. - resource_parent (str): - The full resource name of the immediate parent of the - resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_project (str): - The full resource name of the project the resource belongs - to. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_owners (MutableSequence[str]): - Owners of the Google Cloud resource. - """ - - resource_name: str = proto.Field( - proto.STRING, - number=1, - ) - resource_type: str = proto.Field( - proto.STRING, - number=2, - ) - resource_parent: str = proto.Field( - proto.STRING, - number=3, - ) - resource_project: str = proto.Field( - proto.STRING, - number=4, - ) - resource_owners: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - security_center_properties: SecurityCenterProperties = proto.Field( - proto.MESSAGE, - number=2, - message=SecurityCenterProperties, - ) - resource_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py deleted file mode 100644 index 15d2a4ec1ee5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.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.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - - A finding is a record of assessment data (security, risk, health - or privacy) ingested into Security Command Center for - presentation, notification, analysis, policy testing, and - enforcement. For example, an XSS vulnerability in an App Engine - application is a finding. - - Attributes: - name (str): - The relative resource name of this finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". - parent (str): - Immutable. The relative resource name of the source the - finding belongs to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. For example: - "organizations/{organization_id}/sources/{source_id}". - resource_name (str): - For findings on Google Cloud resources, the full resource - name of the Google Cloud resource this finding is for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - This field is immutable after creation time. - state (google.cloud.securitycenter_v1beta1.types.Finding.State): - The state of the finding. - category (str): - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. - Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the event took place, or - when an update to the finding occurred. For - example, if the finding represents an open - firewall it would capture the time the detector - believes the firewall became open. The accuracy - is determined by the detector. If the finding - were to be resolved afterward, this time would - reflect when the finding was resolved. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the finding was created in - Security Command Center. - """ - class State(proto.Enum): - r"""The state of the finding. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - ACTIVE (1): - The finding requires attention and has not - been addressed yet. - INACTIVE (2): - The finding has been fixed, triaged as a - non-issue or otherwise addressed and is no - longer active. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - resource_name: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - category: str = proto.Field( - proto.STRING, - number=5, - ) - external_uri: str = proto.Field( - proto.STRING, - number=6, - ) - source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py deleted file mode 100644 index e94e037fd61a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py +++ /dev/null @@ -1,115 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'OrganizationSettings', - }, -) - - -class OrganizationSettings(proto.Message): - r"""User specified settings that are attached to the Security - Command Center organization. - - Attributes: - name (str): - The relative resource name of the settings. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/organizationSettings". - enable_asset_discovery (bool): - A flag that indicates if Asset Discovery should be enabled. - If the flag is set to ``true``, then discovery of assets - will occur. If it is set to \`false, all historical assets - will remain, but discovery of future assets will not occur. - asset_discovery_config (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig): - The configuration used for Asset Discovery - runs. - """ - - class AssetDiscoveryConfig(proto.Message): - r"""The configuration used for Asset Discovery runs. - - Attributes: - project_ids (MutableSequence[str]): - The project ids to use for filtering asset - discovery. - inclusion_mode (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): - The mode to use for filtering asset - discovery. - """ - class InclusionMode(proto.Enum): - r"""The mode of inclusion when running Asset Discovery. Asset discovery - can be limited by explicitly identifying projects to be included or - excluded. If INCLUDE_ONLY is set, then only those projects within - the organization and their children are discovered during asset - discovery. If EXCLUDE is set, then projects that don't match those - projects are discovered during asset discovery. If neither are set, - then all projects within the organization are discovered during - asset discovery. - - Values: - INCLUSION_MODE_UNSPECIFIED (0): - Unspecified. Setting the mode with this value - will disable inclusion/exclusion filtering for - Asset Discovery. - INCLUDE_ONLY (1): - Asset Discovery will capture only the - resources within the projects specified. All - other resources will be ignored. - EXCLUDE (2): - Asset Discovery will ignore all resources - under the projects specified. All other - resources will be retrieved. - """ - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - project_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - inclusion_mode: 'OrganizationSettings.AssetDiscoveryConfig.InclusionMode' = proto.Field( - proto.ENUM, - number=2, - enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - enable_asset_discovery: bool = proto.Field( - proto.BOOL, - number=2, - ) - asset_discovery_config: AssetDiscoveryConfig = proto.Field( - proto.MESSAGE, - number=3, - message=AssetDiscoveryConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py deleted file mode 100644 index c5bccb3dd7f2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.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 - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'RunAssetDiscoveryResponse', - }, -) - - -class RunAssetDiscoveryResponse(proto.Message): - r"""Response of asset discovery run - - Attributes: - state (google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryResponse.State): - The state of an asset discovery run. - duration (google.protobuf.duration_pb2.Duration): - The duration between asset discovery run - start and end - """ - class State(proto.Enum): - r"""The state of an asset discovery run. - - Values: - STATE_UNSPECIFIED (0): - Asset discovery run state was unspecified. - COMPLETED (1): - Asset discovery run completed successfully. - SUPERSEDED (2): - Asset discovery run was cancelled with tasks - still pending, as another run for the same - organization was started with a higher priority. - TERMINATED (3): - Asset discovery run was killed and - terminated. - """ - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py deleted file mode 100644 index f2b762a6f2ec..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'SecurityMarks', - }, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (MutableMapping[str, str]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - marks: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py deleted file mode 100644 index dd7fedfd6122..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py +++ /dev/null @@ -1,1053 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1beta1.types import asset as gcs_asset -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'CreateFindingRequest', - 'CreateSourceRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'SetFindingStateRequest', - 'RunAssetDiscoveryRequest', - 'UpdateFindingRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSourceRequest', - 'UpdateSecurityMarksRequest', - }, -) - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - - Attributes: - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - alphanumeric and less than or equal to 32 - characters and greater than 0 characters in - length. - finding (google.cloud.securitycenter_v1beta1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - finding_id: str = proto.Field( - proto.STRING, - number=2, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_finding.Finding, - ) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - source (google.cloud.securitycenter_v1beta1.types.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_source.Source, - ) - - -class GetOrganizationSettingsRequest(proto.Message): - r"""Request message for getting organization settings. - - Attributes: - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is "organizations/[organization_id]/source/[source_id]". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GroupAssetsRequest(proto.Message): - r"""Request message for grouping by assets. - - Attributes: - parent (str): - Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``resource_properties.size = 100`` is a valid - filter string. - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is - not set: - - - security_center_properties.resource_project - - security_center_properties.resource_type - - security_center_properties.resource_parent - - The following fields are supported when compare_duration is - set: - - - security_center_properties.resource_type - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the Asset's "state" property - is updated to indicate whether the asset was added, removed, - or remained present during the compare_duration period of - time that precedes the read_time. This is the time between - (read_time - compare_duration) and read_time. - - The state value is derived based on the presence of the - asset at the two points in time. Intermediate state changes - between the two times don't affect the result. For example, - the results aren't affected if the asset is removed and - re-created again. - - Possible "state" values when compare_duration is specified: - - - "ADDED": indicates that the asset was not present before - compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at - reference_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and reference_time. - - This field is ignored if ``state`` is not a field in - ``group_by``. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupAssetsResponse``; - indicates that this is a continuation of a prior - ``GroupAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - page_size: int = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupAssetsResponse(proto.Message): - r"""Response message for grouping by assets. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - - Attributes: - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". To - groupBy across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``source_properties.size = 100`` is a valid - filter string. - group_by (str): - Required. Expression that defines what assets fields to use - for grouping (including ``state``). The string value should - follow SQL syntax: comma separated list of fields. For - example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - page_size: int = proto.Field( - proto.INT32, - number=6, - ) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message=struct_pb2.Value, - ) - count: int = proto.Field( - proto.INT64, - number=2, - ) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be "organizations/[organization_id]". - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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=7, - ) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - - Attributes: - sources (MutableSequence[google.cloud.securitycenter_v1beta1.types.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListAssetsRequest(proto.Message): - r"""Request message for listing assets. - - Attributes: - parent (str): - Required. Name of the organization assets should belong to. - Its format is "organizations/[organization_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``resource_properties.size = 100`` is a valid - filter string. - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,resource_properties.a_property". - Redundant space characters in the syntax are insignificant. - "name desc,resource_properties.a_property" and " name desc , - resource_properties.a_property " are equivalent. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListAssetResult's "state" - attribute is updated to indicate whether the asset was - added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state value is derived based on the presence of the - asset at the two points in time. Intermediate state changes - between the two times don't affect the result. For example, - the results aren't affected if the asset is removed and - re-created again. - - Possible "state" values when compare_duration is specified: - - - "ADDED": indicates that the asset was not present before - compare_duration, but present at read_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at read_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and read_time. - - If compare_duration is not specified, then the only possible - state is "UNUSED", which indicates that the asset is present - at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. A field mask to specify the - ListAssetsResult fields to be listed in the - response. An empty field mask will list all - fields. - page_token (str): - The value returned by the last ``ListAssetsResponse``; - indicates that this is a continuation of a prior - ``ListAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=8, - ) - page_size: int = proto.Field( - proto.INT32, - number=9, - ) - - -class ListAssetsResponse(proto.Message): - r"""Response message for listing assets. - - Attributes: - list_assets_results (MutableSequence[google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult]): - Assets matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of assets matching the - query. - """ - - class ListAssetsResult(proto.Message): - r"""Result containing the Asset and its State. - - Attributes: - asset (google.cloud.securitycenter_v1beta1.types.Asset): - Asset matching the search request. - state (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult.State): - State of the asset. - """ - class State(proto.Enum): - r"""State of the asset. - - When querying across two points in time this describes the change - between the two points: ADDED, REMOVED, or ACTIVE. If there was no - compare_duration supplied in the request the state should be: UNUSED - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - UNUSED (1): - Request did not specify use of this field in - the result. - ADDED (2): - Asset was added between the points in time. - REMOVED (3): - Asset was removed between the points in time. - ACTIVE (4): - Asset was active at both point(s) in time. - """ - STATE_UNSPECIFIED = 0 - UNUSED = 1 - ADDED = 2 - REMOVED = 3 - ACTIVE = 4 - - asset: gcs_asset.Asset = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_asset.Asset, - ) - state: 'ListAssetsResponse.ListAssetsResult.State' = proto.Field( - proto.ENUM, - number=2, - enum='ListAssetsResponse.ListAssetsResult.State', - ) - - @property - def raw_page(self): - return self - - list_assets_results: MutableSequence[ListAssetsResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListAssetsResult, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - - Attributes: - parent (str): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id]". To - list across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``source_properties.size = 100`` is a valid - filter string. - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,source_properties.a_property". Redundant - space characters in the syntax are insignificant. "name - desc,source_properties.a_property" and " name desc , - source_properties.a_property " are equivalent. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. A field mask to specify the Finding - fields to be listed in the response. An empty - field mask will list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=6, - ) - page_size: int = proto.Field( - proto.INT32, - number=7, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - - Attributes: - findings (MutableSequence[google.cloud.securitycenter_v1beta1.types.Finding]): - Findings matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - @property - def raw_page(self): - return self - - findings: MutableSequence[gcs_finding.Finding] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - - Attributes: - name (str): - Required. The relative resource name of the finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - state (google.cloud.securitycenter_v1beta1.types.Finding.State): - Required. The desired State of the finding. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the updated state - takes effect. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: gcs_finding.Finding.State = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.State, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class RunAssetDiscoveryRequest(proto.Message): - r"""Request message for running asset discovery for an - organization. - - Attributes: - parent (str): - Required. Name of the organization to run asset discovery - for. Its format is "organizations/[organization_id]". - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - - Attributes: - finding (google.cloud.securitycenter_v1beta1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - finding resource. This field should not be - specified when creating a finding. - """ - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateOrganizationSettingsRequest(proto.Message): - r"""Request message for updating an organization's settings. - - Attributes: - organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): - Required. The organization settings resource - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - settings resource. - """ - - organization_settings: gcs_organization_settings.OrganizationSettings = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_organization_settings.OrganizationSettings, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - - Attributes: - source (google.cloud.securitycenter_v1beta1.types.Source): - Required. The source resource to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the source - resource. - """ - - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - - Attributes: - security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): - Required. The security marks resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - security marks resource. - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the updated SecurityMarks - take effect. - """ - - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_security_marks.SecurityMarks, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - start_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-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py deleted file mode 100644 index 761384a9c28f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py +++ /dev/null @@ -1,77 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v1beta1', - manifest={ - 'Source', - }, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, etc. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and - outdated/insecure libraries.". - """ - - 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, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/noxfile.py deleted file mode 100644 index 09f9f6872402..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-securitycenter' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -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"): - 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/securitycenter_v1beta1/', - '--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"): - 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", - "grpcio", - "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/securitycenter_v1beta1/', - '--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( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): - # Ignore release of mypy 1.11.0 which may have a regression - 'mypy!=1.11.0', - '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-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_async.py deleted file mode 100644 index e2ccd162023c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_create_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_sync.py deleted file mode 100644 index 8a6cd38a65ea..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_create_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_async.py deleted file mode 100644 index b705b58ee221..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_CreateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_create_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_sync.py deleted file mode 100644 index ed1f60c4c944..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_CreateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_create_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py deleted file mode 100644 index 8f5186953423..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py deleted file mode 100644 index 74daec484fa2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py deleted file mode 100644 index e21dbe268313..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_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 GetOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py deleted file mode 100644 index 40c62b6f158e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_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 GetOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_async.py deleted file mode 100644 index 92eeeb159eb1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GetSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_get_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_sync.py deleted file mode 100644 index 4432d6697cb8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GetSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_get_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_async.py deleted file mode 100644 index 7bc11cd58a3d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_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 GroupAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_group_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_sync.py deleted file mode 100644 index b5a0c8f1322b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_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 GroupAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_group_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_async.py deleted file mode 100644 index 367437acd112..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_group_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_sync.py deleted file mode 100644 index 2b3cdac52e46..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_group_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_async.py deleted file mode 100644 index 80d46cf5ce6f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_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 ListAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_ListAssets_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_list_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_sync.py deleted file mode 100644 index 6f45a7b22700..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_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 ListAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_ListAssets_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_list_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_async.py deleted file mode 100644 index 3ee6027b07d6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_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 securitycenter_v1beta1 - - -async def sample_list_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_sync.py deleted file mode 100644 index 6a9a7c526574..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_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 securitycenter_v1beta1 - - -def sample_list_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_async.py deleted file mode 100644 index ced7ea701eeb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_ListSources_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_list_sources(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_sync.py deleted file mode 100644 index 3eff727dc701..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_ListSources_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_list_sources(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py deleted file mode 100644 index 7ec0a72a67a5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py deleted file mode 100644 index 7efbac655d2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_async.py deleted file mode 100644 index f9245b6f398e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_set_finding_state(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py deleted file mode 100644 index a2b160db84a8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_set_finding_state(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py deleted file mode 100644 index 9863d798d645..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py deleted file mode 100644 index ddac6e4fadb8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py deleted file mode 100644 index f1ecc97a8e8c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py deleted file mode 100644 index 87f3b0ee6c7b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_async.py deleted file mode 100644 index 8f8e6f58f99f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_update_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_sync.py deleted file mode 100644 index 9c214219e880..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_update_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py deleted file mode 100644 index 8174ebf4f93b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = await client.update_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py deleted file mode 100644 index b587f61c0ce3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = client.update_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_async.py deleted file mode 100644 index 230075087471..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_update_security_marks(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py deleted file mode 100644 index f041a1b1fa1a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_update_security_marks(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_async.py deleted file mode 100644 index 3afe218c0c83..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_update_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_sync.py deleted file mode 100644 index 0ff7573f017d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_update_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json deleted file mode 100644 index a4c1295eaf99..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json +++ /dev/null @@ -1,2945 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.securitycenter.v1beta1", - "version": "v1beta1" - } - ], - "language": "PYTHON", - "name": "google-cloud-securitycenter", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1beta1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v1beta1_generated_security_center_create_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1beta1_generated_security_center_create_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1beta1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v1beta1_generated_security_center_create_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1beta1_generated_security_center_create_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1beta1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v1beta1_generated_security_center_create_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_create_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1beta1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v1beta1_generated_security_center_create_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_create_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.get_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest" - }, - { - "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.securitycenter_v1beta1.types.OrganizationSettings", - "shortName": "get_organization_settings" - }, - "description": "Sample for GetOrganizationSettings", - "file": "securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.get_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest" - }, - { - "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.securitycenter_v1beta1.types.OrganizationSettings", - "shortName": "get_organization_settings" - }, - "description": "Sample for GetOrganizationSettings", - "file": "securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GetSourceRequest" - }, - { - "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.securitycenter_v1beta1.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v1beta1_generated_security_center_get_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_get_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GetSourceRequest" - }, - { - "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.securitycenter_v1beta1.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v1beta1_generated_security_center_get_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_get_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.group_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsAsyncPager", - "shortName": "group_assets" - }, - "description": "Sample for GroupAssets", - "file": "securitycenter_v1beta1_generated_security_center_group_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1beta1_generated_security_center_group_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.group_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsPager", - "shortName": "group_assets" - }, - "description": "Sample for GroupAssets", - "file": "securitycenter_v1beta1_generated_security_center_group_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1beta1_generated_security_center_group_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsAsyncPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v1beta1_generated_security_center_group_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1beta1_generated_security_center_group_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v1beta1_generated_security_center_group_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1beta1_generated_security_center_group_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.list_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.ListAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsAsyncPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "securitycenter_v1beta1_generated_security_center_list_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1beta1_generated_security_center_list_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.list_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.ListAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "securitycenter_v1beta1_generated_security_center_list_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1beta1_generated_security_center_list_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.ListFindingsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsAsyncPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v1beta1_generated_security_center_list_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1beta1_generated_security_center_list_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.ListFindingsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v1beta1_generated_security_center_list_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1beta1_generated_security_center_list_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.ListSourcesRequest" - }, - { - "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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesAsyncPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v1beta1_generated_security_center_list_sources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1beta1_generated_security_center_list_sources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.ListSourcesRequest" - }, - { - "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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v1beta1_generated_security_center_list_sources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1beta1_generated_security_center_list_sources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.run_asset_discovery", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.RunAssetDiscovery", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "RunAssetDiscovery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "run_asset_discovery" - }, - "description": "Sample for RunAssetDiscovery", - "file": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.run_asset_discovery", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.RunAssetDiscovery", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "RunAssetDiscovery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "run_asset_discovery" - }, - "description": "Sample for RunAssetDiscovery", - "file": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v1beta1.types.Finding.State" - }, - { - "name": "start_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v1beta1_generated_security_center_set_finding_state_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1beta1_generated_security_center_set_finding_state_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v1beta1.types.Finding.State" - }, - { - "name": "start_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1beta1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v1beta1_generated_security_center_update_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1beta1_generated_security_center_update_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1beta1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v1beta1_generated_security_center_update_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1beta1_generated_security_center_update_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest" - }, - { - "name": "organization_settings", - "type": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings", - "shortName": "update_organization_settings" - }, - "description": "Sample for UpdateOrganizationSettings", - "file": "securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest" - }, - { - "name": "organization_settings", - "type": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings", - "shortName": "update_organization_settings" - }, - "description": "Sample for UpdateOrganizationSettings", - "file": "securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v1beta1.types.SecurityMarks" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v1beta1_generated_security_center_update_security_marks_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1beta1_generated_security_center_update_security_marks_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v1beta1.types.SecurityMarks" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1beta1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v1beta1_generated_security_center_update_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1beta1_generated_security_center_update_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1beta1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v1beta1_generated_security_center_update_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1beta1_generated_security_center_update_source_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py deleted file mode 100644 index e4b81a3218c2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py +++ /dev/null @@ -1,193 +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 securitycenterCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_source': ('parent', 'source', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_organization_settings': ('name', ), - 'get_source': ('name', ), - 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), - 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'page_token', 'page_size', ), - 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'field_mask', 'page_token', 'page_size', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'run_asset_discovery': ('parent', ), - 'set_finding_state': ('name', 'state', 'start_time', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_organization_settings': ('organization_settings', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), - 'update_source': ('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=securitycenterCallTransformer(), -): - """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 securitycenter 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-securitycenter/v1beta1/setup.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/setup.py deleted file mode 100644 index c4538ec101f3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/setup.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. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-securitycenter' - - -description = "Google Cloud Securitycenter API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/securitycenter/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", - "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", -] -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" - -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__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-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py deleted file mode 100644 index 1ba9f20c0bed..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py +++ /dev/null @@ -1,14372 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -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 - -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.securitycenter_v1beta1.services.security_center import SecurityCenterAsyncClient -from google.cloud.securitycenter_v1beta1.services.security_center import SecurityCenterClient -from google.cloud.securitycenter_v1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1beta1.services.security_center import transports -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -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 duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None - assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert SecurityCenterClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SecurityCenterGrpcTransport, "grpc"), - (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - 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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -def test_security_center_client_get_transport_class(): - transport = SecurityCenterClient.get_transport_class() - available_transports = [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterRestTransport, - ] - assert transport in available_transports - - transport = SecurityCenterClient.get_transport_class("grpc") - assert transport == transports.SecurityCenterGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, 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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), -]) -def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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_security_center_client_client_options_from_dict(): - with mock.patch('google.cloud.securitycenter_v1beta1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_create_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object - - request = {} - await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_create_source_async_from_dict(): - await test_create_source_async(request_type=dict) - - -def test_create_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.create_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - - -def test_create_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - response = client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -def test_create_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.create_finding] = mock_rpc - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object - - request = {} - await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -@pytest.mark.asyncio -async def test_create_finding_async_from_dict(): - await test_create_finding_async(request_type=dict) - - -def test_create_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - arg = args[0].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - - -def test_create_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - arg = args[0].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.GetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest( - resource='resource_value', - ) - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object - - request = {} - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_get_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetOrganizationSettingsRequest, - dict, -]) -def test_get_organization_settings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_get_organization_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetOrganizationSettingsRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_organization_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest( - name='name_value', - ) - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_organization_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_organization_settings] = mock_rpc - request = {} - client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_organization_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_organization_settings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - -@pytest.mark.asyncio -async def test_get_organization_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_organization_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_organization_settings] = mock_object - - request = {} - await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_organization_settings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_get_organization_settings_async_from_dict(): - await test_get_organization_settings_async(request_type=dict) - - -def test_get_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = organization_settings.OrganizationSettings() - client.get_organization_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_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - await client.get_organization_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_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_organization_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_organization_settings_flattened_error(): - client = SecurityCenterClient( - credentials=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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_organization_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_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_get_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest( - name='name_value', - ) - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - -@pytest.mark.asyncio -async def test_get_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object - - request = {} - await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_get_source_async_from_dict(): - await test_get_source_async(request_type=dict) - - -def test_get_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = source.Source() - client.get_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_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_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_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_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupAssetsRequest, - dict, -]) -def test_group_assets(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - ) - response = client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_group_assets_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - -def test_group_assets_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupAssetsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_assets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_assets_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc - request = {} - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_group_assets_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - )) - response = await client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - -@pytest.mark.asyncio -async def test_group_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_assets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_assets] = mock_object - - request = {} - await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - )) - response = await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_group_assets_async_from_dict(): - await test_group_assets_async(request_type=dict) - - -def test_group_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = securitycenter_service.GroupAssetsResponse() - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_group_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) - await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_group_assets_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_assets(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, securitycenter_service.GroupResult) - for i in results) -def test_group_assets_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_assets(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_group_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_assets(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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_assets(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", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - ) - response = client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_group_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - -@pytest.mark.asyncio -async def test_group_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_findings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object - - request = {} - await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_findings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_group_findings_async_from_dict(): - await test_group_findings_async(request_type=dict) - - -def test_group_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_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_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - await client.group_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_group_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that the 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - - -def test_group_findings_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - -@pytest.mark.asyncio -async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_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, securitycenter_service.GroupResult) - for i in results) -def test_group_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_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_group_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_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", [ - securitycenter_service.ListAssetsRequest, - dict, -]) -def test_list_assets(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_assets_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - -def test_list_assets_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListAssetsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_assets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_value', - page_token='page_token_value', - ) - -def test_list_assets_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc - request = {} - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_assets_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - -@pytest.mark.asyncio -async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_assets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object - - request = {} - await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_assets_async_from_dict(): - await test_list_assets_async(request_type=dict) - - -def test_list_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = securitycenter_service.ListAssetsResponse() - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) - await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_assets_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) -def test_list_assets_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_assets(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_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - 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_assets(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", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -def test_list_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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] == securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - -@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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object - - request = {} - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -@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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.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 = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.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 = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.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 = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.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", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_sources_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListSourcesRequest( - 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_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - -@pytest.mark.asyncio -async def test_list_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_sources in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object - - request = {} - await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_sources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_sources_async_from_dict(): - await test_list_sources_async(request_type=dict) - - -def test_list_sources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = securitycenter_service.ListSourcesResponse() - client.list_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_sources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - await client.list_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_sources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_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_sources_flattened_error(): - client = SecurityCenterClient( - credentials=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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_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_sources_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_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, source.Source) - for i in results) -def test_list_sources_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = list(client.list_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_sources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_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, source.Source) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - 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_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", [ - securitycenter_service.RunAssetDiscoveryRequest, - dict, -]) -def test_run_asset_discovery(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.RunAssetDiscoveryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_run_asset_discovery_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - -def test_run_asset_discovery_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.RunAssetDiscoveryRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.run_asset_discovery(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest( - parent='parent_value', - ) - -def test_run_asset_discovery_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.run_asset_discovery in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc - request = {} - client.run_asset_discovery(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.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_run_asset_discovery_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - -@pytest.mark.asyncio -async def test_run_asset_discovery_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.run_asset_discovery in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.run_asset_discovery] = mock_object - - request = {} - await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.RunAssetDiscoveryRequest() - 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_run_asset_discovery_async_from_dict(): - await test_run_asset_discovery_async(request_type=dict) - - -def test_run_asset_discovery_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_run_asset_discovery_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_run_asset_discovery_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery( - 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_run_asset_discovery_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_run_asset_discovery_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery( - 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_run_asset_discovery_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - response = client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -def test_set_finding_state_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - -@pytest.mark.asyncio -async def test_set_finding_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object - - request = {} - await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_finding_state(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -@pytest.mark.asyncio -async def test_set_finding_state_async_from_dict(): - await test_set_finding_state_async(request_type=dict) - - -def test_set_finding_state_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = finding.Finding() - client.set_finding_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_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_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_set_finding_state_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - - -def test_set_finding_state_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.SetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest( - resource='resource_value', - ) - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object - - request = {} - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = SecurityCenterClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.TestIamPermissionsRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( - resource='resource_value', - ) - -def test_test_iam_permissions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object - - request = {} - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - response = client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -def test_update_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateFindingRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.update_finding] = mock_rpc - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object - - request = {} - await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -@pytest.mark.asyncio -async def test_update_finding_async_from_dict(): - await test_update_finding_async(request_type=dict) - - -def test_update_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -def test_update_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_finding( - finding=gcs_finding.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].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - - -def test_update_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_finding( - finding=gcs_finding.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].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateOrganizationSettingsRequest, - dict, -]) -def test_update_organization_settings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_update_organization_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateOrganizationSettingsRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_organization_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest( - ) - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_organization_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_organization_settings] = mock_rpc - request = {} - client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_organization_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_organization_settings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - -@pytest.mark.asyncio -async def test_update_organization_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_organization_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_organization_settings] = mock_object - - request = {} - await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_organization_settings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_update_organization_settings_async_from_dict(): - await test_update_organization_settings_async(request_type=dict) - - -def test_update_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = gcs_organization_settings.OrganizationSettings() - client.update_organization_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', - 'organization_settings.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - await client.update_organization_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', - 'organization_settings.name=name_value', - ) in kw['metadata'] - - -def test_update_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].organization_settings - mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') - assert arg == mock_val - - -def test_update_organization_settings_flattened_error(): - client = SecurityCenterClient( - credentials=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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].organization_settings - mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_update_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSourceRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object - - request = {} - await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_update_source_async_from_dict(): - await test_update_source_async(request_type=dict) - - -def test_update_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -def test_update_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_source( - source=gcs_source.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].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - - -def test_update_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_source( - source=gcs_source.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].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks( - name='name_value', - ) - response = client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - - -def test_update_security_marks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - -def test_update_security_marks_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSecurityMarksRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( - ) - -def test_update_security_marks_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish that a new wrapper 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_security_marks_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - )) - response = await client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - -@pytest.mark.asyncio -async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_marks in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object - - request = {} - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_security_marks(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - )) - response = await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_update_security_marks_async_from_dict(): - await test_update_security_marks_async(request_type=dict) - - -def test_update_security_marks_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -def test_update_security_marks_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].security_marks - mock_val = gcs_security_marks.SecurityMarks(name='name_value') - assert arg == mock_val - - -def test_update_security_marks_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].security_marks - mock_val = gcs_security_marks.SecurityMarks(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': '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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.CreateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_source(request) - - -def test_create_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_create_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -def test_create_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request_init["finding"] = {'name': 'name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.create_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.create_finding] = mock_rpc - - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["finding_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 "findingId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "findingId" in jsonified_request - assert jsonified_request["findingId"] == request_init["finding_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["findingId"] = 'finding_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request - assert jsonified_request["findingId"] == 'finding_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.create_finding(request) - - expected_params = [ - ( - "findingId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.CreateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_finding(request) - - -def test_create_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(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 = gcs_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.create_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/v1beta1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) - - -def test_create_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_create_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.get_iam_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/v1beta1/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetOrganizationSettingsRequest, - dict, -]) -def test_get_organization_settings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/organizationSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_organization_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_organization_settings] = mock_rpc - - request = {} - client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.GetOrganizationSettingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_organization_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_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_organization_settings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_organization_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_organization_settings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_organization_settings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_organization_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetOrganizationSettingsRequest.pb(securitycenter_service.GetOrganizationSettingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = organization_settings.OrganizationSettings.to_json(organization_settings.OrganizationSettings()) - - request = securitycenter_service.GetOrganizationSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = organization_settings.OrganizationSettings() - - client.get_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/organizationSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_organization_settings(request) - - -def test_get_organization_settings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/organizationSettings'} - - # get truthy value for each flattened field - mock_args = dict( - 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 = organization_settings.OrganizationSettings.pb(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_organization_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/v1beta1/{name=organizations/*/organizationSettings}" % client.transport._host, args[1]) - - -def test_get_organization_settings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -def test_get_organization_settings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/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 = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = source.Source.to_json(source.Source()) - - request = securitycenter_service.GetSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = source.Source() - - client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_source(request) - - -def test_get_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v1beta1/{name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_get_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -def test_get_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupAssetsRequest, - dict, -]) -def test_group_assets_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_group_assets_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc - - request = {} - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_group_assets_rest_required_fields(request_type=securitycenter_service.GroupAssetsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupAssetsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_assets_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_assets_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_assets") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupAssetsRequest.pb(securitycenter_service.GroupAssetsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupAssetsResponse.to_json(securitycenter_service.GroupAssetsResponse()) - - request = securitycenter_service.GroupAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupAssetsResponse() - - client.group_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_assets(request) - - -def test_group_assets_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupAssetsResponse.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': 'organizations/sample1'} - - pager = client.group_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_findings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_findings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_findings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) - - request = securitycenter_service.GroupFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupFindingsResponse() - - client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_findings(request) - - -def test_group_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - group_by='group_by_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v1beta1/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) - - -def test_group_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} - - pager = client.group_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_findings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListAssetsRequest, - dict, -]) -def test_list_assets_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListAssetsResponse.pb(return_value) - 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_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_list_assets_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc - - request = {} - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_assets(request) - - # Establish 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_assets_rest_required_fields(request_type=securitycenter_service.ListAssetsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_assets._get_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_assets._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) - jsonified_request.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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAssetsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListAssetsResponse.pb(return_value) - 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_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_assets_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_assets_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_assets") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListAssetsRequest.pb(securitycenter_service.ListAssetsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListAssetsResponse.to_json(securitycenter_service.ListAssetsResponse()) - - request = securitycenter_service.ListAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListAssetsResponse() - - client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_assets(request) - - -def test_list_assets_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListAssetsResponse.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': 'organizations/sample1'} - - pager = client.list_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) - - pages = list(client.list_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.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' - assert response.total_size == 1086 - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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=securitycenter_service.ListFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) - jsonified_request.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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.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 = securitycenter_service.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 = [ - ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) - - request = securitycenter_service.ListFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListFindingsResponse() - - client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_findings(request) - - -def test_list_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} - - 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 - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_sources_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_sources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_sources_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) - - request = securitycenter_service.ListSourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListSourcesResponse() - - client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_sources(request) - - -def test_list_sources_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_list_sources_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} - - pager = client.list_sources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, source.Source) - for i in results) - - pages = list(client.list_sources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.RunAssetDiscoveryRequest, - dict, -]) -def test_run_asset_discovery_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') - - # 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 - response = client.run_asset_discovery(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_run_asset_discovery_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.run_asset_discovery in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc - - request = {} - client.run_asset_discovery(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.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_run_asset_discovery_rest_required_fields(request_type=securitycenter_service.RunAssetDiscoveryRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_asset_discovery._get_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()).run_asset_discovery._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 = SecurityCenterClient( - 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.run_asset_discovery(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_run_asset_discovery_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.run_asset_discovery._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_run_asset_discovery_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_run_asset_discovery") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_run_asset_discovery") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.RunAssetDiscoveryRequest.pb(securitycenter_service.RunAssetDiscoveryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = securitycenter_service.RunAssetDiscoveryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.run_asset_discovery(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_run_asset_discovery_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.run_asset_discovery(request) - - -def test_run_asset_discovery_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.run_asset_discovery(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{parent=organizations/*}/assets:runDiscovery" % client.transport._host, args[1]) - - -def test_run_asset_discovery_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -def test_run_asset_discovery_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - - # 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 - response = client.set_finding_state(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( - 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': "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 = 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.set_finding_state(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_finding_state_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_finding_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "state", "startTime", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_finding_state_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = finding.Finding.to_json(finding.Finding()) - - request = securitycenter_service.SetFindingStateRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_finding_state(request) - - -def test_set_finding_state_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - mock_args.update(sample_request) - - # 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.set_finding_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/v1beta1/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) - - -def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -def test_set_finding_state_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.set_iam_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/v1beta1/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # 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 - response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_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.test_iam_permissions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.update_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.update_finding] = mock_rpc - - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_finding._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_finding._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.update_finding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.UpdateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_finding(request) - - -def test_update_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - finding=gcs_finding.Finding(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 = gcs_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.update_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/v1beta1/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) - - -def test_update_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_update_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateOrganizationSettingsRequest, - dict, -]) -def test_update_organization_settings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - request_init["organization_settings"] = {'name': 'organizations/sample1/organizationSettings', 'enable_asset_discovery': True, 'asset_discovery_config': {'project_ids': ['project_ids_value1', 'project_ids_value2'], 'inclusion_mode': 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 = securitycenter_service.UpdateOrganizationSettingsRequest.meta.fields["organization_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["organization_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["organization_settings"][field])): - del request_init["organization_settings"][field][i][subfield] - else: - del request_init["organization_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 = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_organization_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_organization_settings] = mock_rpc - - request = {} - client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_organization_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_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_organization_settings.OrganizationSettings() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_organization_settings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_organization_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("organizationSettings", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_organization_settings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_organization_settings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_organization_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateOrganizationSettingsRequest.pb(securitycenter_service.UpdateOrganizationSettingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_organization_settings.OrganizationSettings.to_json(gcs_organization_settings.OrganizationSettings()) - - request = securitycenter_service.UpdateOrganizationSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_organization_settings.OrganizationSettings() - - client.update_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_organization_settings(request) - - -def test_update_organization_settings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_organization_settings.OrganizationSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - - # get truthy value for each flattened field - mock_args = dict( - organization_settings=gcs_organization_settings.OrganizationSettings(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 = gcs_organization_settings.OrganizationSettings.pb(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_organization_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/v1beta1/{organization_settings.name=organizations/*/organizationSettings}" % client.transport._host, args[1]) - - -def test_update_organization_settings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -def test_update_organization_settings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': '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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.UpdateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_source(request) - - -def test_update_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1beta1/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_update_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - - -def test_update_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - request_init["security_marks"] = {'name': 'organizations/sample1/assets/sample2/securityMarks', 'marks': {}} - # The version of a generated dependency at test runtime may differ from the version used 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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] - - 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["security_marks"].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["security_marks"][field])): - del request_init["security_marks"][field][i][subfield] - else: - del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( - name='name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - -def test_update_security_marks_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_security_marks._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_security_marks._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("start_time", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_security_marks_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_security_marks._get_unset_required_fields({}) - assert set(unset_fields) == (set(("startTime", "updateMask", )) & set(("securityMarks", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_security_marks_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) - - request = securitycenter_service.UpdateSecurityMarksRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_security_marks.SecurityMarks() - - client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_security_marks(request) - - -def test_update_security_marks_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - - # get arguments that satisfy an http rule for this method - sample_request = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - - # get truthy value for each flattened field - mock_args = dict( - security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}" % client.transport._host, args[1]) - - -def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - -def test_update_security_marks_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SecurityCenterClient( - 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 = SecurityCenterClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SecurityCenterClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SecurityCenterClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SecurityCenterGrpcTransport, - ) - -def test_security_center_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_security_center_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_source', - 'create_finding', - 'get_iam_policy', - 'get_organization_settings', - 'get_source', - 'group_assets', - 'group_findings', - 'list_assets', - 'list_findings', - 'list_sources', - 'run_asset_discovery', - 'set_finding_state', - 'set_iam_policy', - 'test_iam_permissions', - 'update_finding', - 'update_organization_settings', - 'update_source', - 'update_security_marks', - ) - 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_security_center_base_transport_with_credentials_file(): - # Instantiate the 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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - 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_security_center_base_transport_with_adc(): - # Test the default 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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport() - adc.assert_called_once() - - -def test_security_center_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) - SecurityCenterClient() - 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -def test_security_center_transport_auth_adc(transport_class): - # If 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, - ], -) -def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), - (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_security_center_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host 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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_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.SecurityCenterRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_security_center_rest_lro_client(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a 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 - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_no_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_with_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_security_center_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SecurityCenterClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SecurityCenterClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_source._session - session2 = client2.transport.create_source._session - assert session1 != session2 - session1 = client1.transport.create_finding._session - session2 = client2.transport.create_finding._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.get_organization_settings._session - session2 = client2.transport.get_organization_settings._session - assert session1 != session2 - session1 = client1.transport.get_source._session - session2 = client2.transport.get_source._session - assert session1 != session2 - session1 = client1.transport.group_assets._session - session2 = client2.transport.group_assets._session - assert session1 != session2 - session1 = client1.transport.group_findings._session - session2 = client2.transport.group_findings._session - assert session1 != session2 - session1 = client1.transport.list_assets._session - session2 = client2.transport.list_assets._session - assert session1 != session2 - session1 = client1.transport.list_findings._session - session2 = client2.transport.list_findings._session - assert session1 != session2 - session1 = client1.transport.list_sources._session - session2 = client2.transport.list_sources._session - assert session1 != session2 - session1 = client1.transport.run_asset_discovery._session - session2 = client2.transport.run_asset_discovery._session - assert session1 != session2 - session1 = client1.transport.set_finding_state._session - session2 = client2.transport.set_finding_state._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 - session1 = client1.transport.update_finding._session - session2 = client2.transport.update_finding._session - assert session1 != session2 - session1 = client1.transport.update_organization_settings._session - session2 = client2.transport.update_organization_settings._session - assert session1 != session2 - session1 = client1.transport.update_source._session - session2 = client2.transport.update_source._session - assert session1 != session2 - session1 = client1.transport.update_security_marks._session - session2 = client2.transport.update_security_marks._session - assert session1 != session2 -def test_security_center_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcTransport( - 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_security_center_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcAsyncIOTransport( - 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(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_security_center_grpc_lro_client(): - client = SecurityCenterClient( - 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_security_center_grpc_lro_async_client(): - client = SecurityCenterAsyncClient( - 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_asset_path(): - organization = "squid" - asset = "clam" - expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.asset_path(organization, asset) - assert expected == actual - - -def test_parse_asset_path(): - expected = { - "organization": "whelk", - "asset": "octopus", - } - path = SecurityCenterClient.asset_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_asset_path(path) - assert expected == actual - -def test_finding_path(): - organization = "oyster" - source = "nudibranch" - finding = "cuttlefish" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - actual = SecurityCenterClient.finding_path(organization, source, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "organization": "mussel", - "source": "winkle", - "finding": "nautilus", - } - path = SecurityCenterClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_finding_path(path) - assert expected == actual - -def test_organization_settings_path(): - organization = "scallop" - expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) - actual = SecurityCenterClient.organization_settings_path(organization) - assert expected == actual - - -def test_parse_organization_settings_path(): - expected = { - "organization": "abalone", - } - path = SecurityCenterClient.organization_settings_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_organization_settings_path(path) - assert expected == actual - -def test_security_marks_path(): - organization = "squid" - asset = "clam" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.security_marks_path(organization, asset) - assert expected == actual - - -def test_parse_security_marks_path(): - expected = { - "organization": "whelk", - "asset": "octopus", - } - path = SecurityCenterClient.security_marks_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_security_marks_path(path) - assert expected == actual - -def test_source_path(): - organization = "oyster" - source = "nudibranch" - expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - actual = SecurityCenterClient.source_path(organization, source) - assert expected == actual - - -def test_parse_source_path(): - expected = { - "organization": "cuttlefish", - "source": "mussel", - } - path = SecurityCenterClient.source_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_source_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SecurityCenterClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = SecurityCenterClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = SecurityCenterClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = SecurityCenterClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SecurityCenterClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = SecurityCenterClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = SecurityCenterClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = SecurityCenterClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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 = SecurityCenterClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = SecurityCenterClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - transport_class = SecurityCenterClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), -]) -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-securitycenter/v1p1beta1/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.coveragerc deleted file mode 100644 index 45cb273f8f7c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/securitycenter/__init__.py - google/cloud/securitycenter/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-securitycenter/v1p1beta1/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.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-securitycenter/v1p1beta1/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/MANIFEST.in deleted file mode 100644 index 57b563bd1a48..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/securitycenter *.py -recursive-include google/cloud/securitycenter_v1p1beta1 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst deleted file mode 100644 index f8c63f4cb48a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v1p1beta1/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/conf.py deleted file mode 100644 index 8e92d2319721..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter 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-securitycenter" -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-securitycenter-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-securitycenter.tex", - u"google-cloud-securitycenter 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-securitycenter", - u"Google Cloud Securitycenter 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-securitycenter", - u"google-cloud-securitycenter Documentation", - author, - "google-cloud-securitycenter", - "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v1p1beta1/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/index.rst deleted file mode 100644 index 45263147b433..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - securitycenter_v1p1beta1/services - securitycenter_v1p1beta1/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst deleted file mode 100644 index adab7f4a5e87..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst +++ /dev/null @@ -1,10 +0,0 @@ -SecurityCenter --------------------------------- - -.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center - :members: - :inherited-members: - -.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst deleted file mode 100644 index 7f537e851e63..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Securitycenter v1p1beta1 API -====================================================== -.. toctree:: - :maxdepth: 2 - - security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst deleted file mode 100644 index a68ac5c68cff..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Securitycenter v1p1beta1 API -=================================================== - -.. automodule:: google.cloud.securitycenter_v1p1beta1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py deleted file mode 100644 index fe0af04fb73b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py +++ /dev/null @@ -1,101 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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.securitycenter import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.securitycenter_v1p1beta1.services.security_center.client import SecurityCenterClient -from google.cloud.securitycenter_v1p1beta1.services.security_center.async_client import SecurityCenterAsyncClient - -from google.cloud.securitycenter_v1p1beta1.types.asset import Asset -from google.cloud.securitycenter_v1p1beta1.types.finding import Finding -from google.cloud.securitycenter_v1p1beta1.types.folder import Folder -from google.cloud.securitycenter_v1p1beta1.types.notification_config import NotificationConfig -from google.cloud.securitycenter_v1p1beta1.types.notification_message import NotificationMessage -from google.cloud.securitycenter_v1p1beta1.types.organization_settings import OrganizationSettings -from google.cloud.securitycenter_v1p1beta1.types.resource import Resource -from google.cloud.securitycenter_v1p1beta1.types.run_asset_discovery_response import RunAssetDiscoveryResponse -from google.cloud.securitycenter_v1p1beta1.types.security_marks import SecurityMarks -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateFindingRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateNotificationConfigRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateSourceRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import DeleteNotificationConfigRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetNotificationConfigRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetOrganizationSettingsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetSourceRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupAssetsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupAssetsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupFindingsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupFindingsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupResult -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListAssetsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListAssetsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListFindingsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListFindingsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListNotificationConfigsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListNotificationConfigsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListSourcesRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListSourcesResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import RunAssetDiscoveryRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import SetFindingStateRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateFindingRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateNotificationConfigRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateOrganizationSettingsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateSecurityMarksRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateSourceRequest -from google.cloud.securitycenter_v1p1beta1.types.source import Source - -__all__ = ('SecurityCenterClient', - 'SecurityCenterAsyncClient', - 'Asset', - 'Finding', - 'Folder', - 'NotificationConfig', - 'NotificationMessage', - 'OrganizationSettings', - 'Resource', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateNotificationConfigRequest', - 'CreateSourceRequest', - 'DeleteNotificationConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/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-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py deleted file mode 100644 index 84391a72a3b7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__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 google.cloud.securitycenter_v1p1beta1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.security_center import SecurityCenterClient -from .services.security_center import SecurityCenterAsyncClient - -from .types.asset import Asset -from .types.finding import Finding -from .types.folder import Folder -from .types.notification_config import NotificationConfig -from .types.notification_message import NotificationMessage -from .types.organization_settings import OrganizationSettings -from .types.resource import Resource -from .types.run_asset_discovery_response import RunAssetDiscoveryResponse -from .types.security_marks import SecurityMarks -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateNotificationConfigRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import DeleteNotificationConfigRequest -from .types.securitycenter_service import GetNotificationConfigRequest -from .types.securitycenter_service import GetOrganizationSettingsRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GroupAssetsRequest -from .types.securitycenter_service import GroupAssetsResponse -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAssetsRequest -from .types.securitycenter_service import ListAssetsResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListNotificationConfigsRequest -from .types.securitycenter_service import ListNotificationConfigsResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import RunAssetDiscoveryRequest -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateNotificationConfigRequest -from .types.securitycenter_service import UpdateOrganizationSettingsRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.source import Source - -__all__ = ( - 'SecurityCenterAsyncClient', -'Asset', -'CreateFindingRequest', -'CreateNotificationConfigRequest', -'CreateSourceRequest', -'DeleteNotificationConfigRequest', -'Finding', -'Folder', -'GetNotificationConfigRequest', -'GetOrganizationSettingsRequest', -'GetSourceRequest', -'GroupAssetsRequest', -'GroupAssetsResponse', -'GroupFindingsRequest', -'GroupFindingsResponse', -'GroupResult', -'ListAssetsRequest', -'ListAssetsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListNotificationConfigsRequest', -'ListNotificationConfigsResponse', -'ListSourcesRequest', -'ListSourcesResponse', -'NotificationConfig', -'NotificationMessage', -'OrganizationSettings', -'Resource', -'RunAssetDiscoveryRequest', -'RunAssetDiscoveryResponse', -'SecurityCenterClient', -'SecurityMarks', -'SetFindingStateRequest', -'Source', -'UpdateFindingRequest', -'UpdateNotificationConfigRequest', -'UpdateOrganizationSettingsRequest', -'UpdateSecurityMarksRequest', -'UpdateSourceRequest', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json deleted file mode 100644 index 892a85e5f9fd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json +++ /dev/null @@ -1,373 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.securitycenter_v1p1beta1", - "protoPackage": "google.cloud.securitycenter.v1p1beta1", - "schema": "1.0", - "services": { - "SecurityCenter": { - "clients": { - "grpc": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SecurityCenterAsyncClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "rest": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py deleted file mode 100644 index bffcff5da306..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - 'SecurityCenterClient', - 'SecurityCenterAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py deleted file mode 100644 index a996989322a3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py +++ /dev/null @@ -1,3039 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.securitycenter_v1p1beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.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.securitycenter_v1p1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1p1beta1.types import security_marks -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_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 SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V1p1Beta1 APIs for Security Center service.""" - - _client: SecurityCenterClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE - - asset_path = staticmethod(SecurityCenterClient.asset_path) - parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) - parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) - notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) - parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) - organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) - parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) - source_path = staticmethod(SecurityCenterClient.source_path) - parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) - topic_path = staticmethod(SecurityCenterClient.topic_path) - parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) - common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) - parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) - common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) - parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) - parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) - parse_common_location_path = staticmethod(SecurityCenterClient.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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v1p1beta1 - - async def sample_create_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest, dict]]): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = 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_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding_id: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_create_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest, dict]]): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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 create_notification_config(self, - request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - config_id: Optional[str] = None, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_create_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.create_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest, dict]]): - The request object. Request message for creating a - notification config. - parent (:class:`str`): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be between 1 and 128 characters, - and contains alphanumeric characters, - underscores or hyphens only. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_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.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_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_notification_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_notification_config(self, - request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest, dict]]): - The request object. Request message for deleting a - notification config. - name (:class:`str`): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1p1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 get_notification_config(self, - request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_get_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest, dict]]): - The request object. Request message for getting a - notification config. - name (:class:`str`): - Required. Name of the notification config to get. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 get_organization_settings(self, - request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest, dict]]): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_organization_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 get_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v1p1beta1 - - async def sample_get_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest, dict]]): - The request object. Request message for getting a source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 group_assets(self, - request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsAsyncPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_group_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest, dict]]): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsAsyncPager: - Response message for grouping by - assets. - 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, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.GroupAssetsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_group_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest, dict]]): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]", - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]. To groupBy - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/-, or - projects/{project_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - severity - - The following fields are supported when compare_duration - is set: - - - state_change - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_assets(self, - request: Optional[Union[securitycenter_service.ListAssetsRequest, 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.ListAssetsAsyncPager: - r"""Lists an organization's assets. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_list_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest, dict]]): - The request object. Request message for listing assets. - parent (:class:`str`): - Required. Name of the organization assets should belong - to. Its format is "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsAsyncPager: - Response message for listing assets. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListAssetsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings(self, - request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsAsyncPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_list_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListFindingsRequest( - parent="parent_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.securitycenter_v1p1beta1.types.ListFindingsRequest, dict]]): - The request object. Request message for listing findings. - parent (:class:`str`): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id], - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]". To list - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/- or - projects/{projects_id}/sources/- - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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_notification_configs(self, - request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsAsyncPager: - r"""Lists notification configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest, dict]]): - The request object. Request message for listing - notification configs. - parent (:class:`str`): - Required. Name of the organization to list notification - configs. Its format is - "organizations/[organization_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsAsyncPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListNotificationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_list_sources(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest, dict]]): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id], folders/[folder_id], - or projects/[project_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesAsyncPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_asset_discovery(self, - request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), - ) -> operation_async.AsyncOperation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS 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 securitycenter_v1p1beta1 - - async def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest, dict]]): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` - Response of asset discovery run - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - async def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - start_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of 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 securitycenter_v1p1beta1 - - async def sample_set_finding_state(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest, dict]]): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding.State`): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1p1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v1p1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 update_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - update_mask: 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]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_update_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest, dict]]): - The request object. Request message for updating or - creating a finding. - finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a - finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing - source_properties. Individual source_properties can be - added/updated by using "source_properties." in the field - mask. - - 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.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - 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_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe domain. - self._client._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_config(self, - request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, - *, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - update_mask: 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]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_update_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = await client.update_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest, dict]]): - The request object. Request message for updating a - notification config. - notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the notification config. - If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_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 update_organization_settings(self, - request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, - *, - organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = await client.update_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest, dict]]): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings`): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_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 update_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - update_mask: 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]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v1p1beta1 - - async def sample_update_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest, dict]]): - The request object. Request message for updating a - source. - source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): - Required. The source resource to - update. - - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the source resource. - If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = 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_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - update_mask: 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]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_update_security_marks(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest, dict]]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`google.cloud.securitycenter_v1p1beta1.types.SecurityMarks`): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If - empty or set to "marks", all marks will be replaced. - Individual marks can be updated using - "marks.". - - 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.securitycenter_v1p1beta1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - 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_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe domain. - self._client._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) -> "SecurityCenterAsyncClient": - 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__ = ( - "SecurityCenterAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py deleted file mode 100644 index caeded73d36f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py +++ /dev/null @@ -1,3441 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_v1p1beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from 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.securitycenter_v1p1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1p1beta1.types import security_marks -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_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 SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .transports.rest import SecurityCenterRestTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - _transport_registry["rest"] = SecurityCenterRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SecurityCenterTransport]: - """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V1p1Beta1 APIs for Security Center 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 = "securitycenter.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: - SecurityCenterClient: 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: - SecurityCenterClient: 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) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def asset_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified asset string.""" - return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_asset_path(path: str) -> Dict[str,str]: - """Parses a asset path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def finding_path(organization: str,source: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def notification_config_path(organization: str,notification_config: str,) -> str: - """Returns a fully-qualified notification_config string.""" - return "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) - - @staticmethod - def parse_notification_config_path(path: str) -> Dict[str,str]: - """Parses a notification_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def organization_settings_path(organization: str,) -> str: - """Returns a fully-qualified organization_settings string.""" - return "organizations/{organization}/organizationSettings".format(organization=organization, ) - - @staticmethod - def parse_organization_settings_path(path: str) -> Dict[str,str]: - """Parses a organization_settings path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str,str]: - """Parses a security_marks path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str,source: str,) -> str: - """Returns a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str,str]: - """Parses a source path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def topic_path(project: str,topic: str,) -> str: - """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - - @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: - """Parses a topic path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/topics/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 - SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient._read_environment_variables() - self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) - if transport_provided: - # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( - type(self).get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., SecurityCenterTransport], 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_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v1p1beta1 - - def sample_create_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest, dict]): - The request object. Request message for creating a - source. - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (google.cloud.securitycenter_v1p1beta1.types.Source): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding_id: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_create_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest, dict]): - The request object. Request message for creating a - finding. - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (str): - Required. Unique identifier provided - by the client within the parent scope. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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 create_notification_config(self, - request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - config_id: Optional[str] = None, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_create_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = client.create_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest, dict]): - The request object. Request message for creating a - notification config. - parent (str): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must be between 1 and 128 characters, - and contains alphanumeric characters, - underscores or hyphens only. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_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.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_notification_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_notification_config(self, - request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest, dict]): - The request object. Request message for deleting a - notification config. - name (str): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1p1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 get_notification_config(self, - request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_get_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest, dict]): - The request object. Request message for getting a - notification config. - name (str): - Required. Name of the notification config to get. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 get_organization_settings(self, - request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest, dict]): - The request object. Request message for getting - organization settings. - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_organization_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 get_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v1p1beta1 - - def sample_get_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest, dict]): - The request object. Request message for getting a source. - name (str): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 group_assets(self, - request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_group_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest, dict]): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsPager: - Response message for grouping by - assets. - 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, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.GroupAssetsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_group_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest, dict]): - The request object. Request message for grouping by - findings. - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]", - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]. To groupBy - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/-, or - projects/{project_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (str): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - severity - - The following fields are supported when compare_duration - is set: - - - state_change - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_assets(self, - request: Optional[Union[securitycenter_service.ListAssetsRequest, 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.ListAssetsPager: - r"""Lists an organization's assets. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_list_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest, dict]): - The request object. Request message for listing assets. - parent (str): - Required. Name of the organization assets should belong - to. Its format is "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsPager: - Response message for listing assets. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListAssetsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings(self, - request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_list_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListFindingsRequest( - parent="parent_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.securitycenter_v1p1beta1.types.ListFindingsRequest, dict]): - The request object. Request message for listing findings. - parent (str): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id], - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]". To list - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/- or - projects/{projects_id}/sources/- - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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_notification_configs(self, - request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsPager: - r"""Lists notification configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest, dict]): - The request object. Request message for listing - notification configs. - parent (str): - Required. Name of the organization to list notification - configs. Its format is - "organizations/[organization_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListNotificationConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_list_sources(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest, dict]): - The request object. Request message for listing sources. - parent (str): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id], folders/[folder_id], - or projects/[project_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_asset_discovery(self, - request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), - ) -> operation.Operation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS 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 securitycenter_v1p1beta1 - - def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest, dict]): - The request object. Request message for running asset - discovery for an organization. - parent (str): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` - Response of asset discovery run - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - start_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of 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 securitycenter_v1p1beta1 - - def sample_set_finding_state(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest, dict]): - The request object. Request message for updating a - finding's state. - name (str): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1p1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v1p1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # 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 - - def update_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - update_mask: 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]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_update_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest, dict]): - The request object. Request message for updating or - creating a finding. - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a - finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing - source_properties. Individual source_properties can be - added/updated by using "source_properties." in the field - mask. - - 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.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - 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_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe 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_config(self, - request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, - *, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - update_mask: 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]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_update_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = client.update_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest, dict]): - The request object. Request message for updating a - notification config. - notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the notification config. - If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_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 update_organization_settings(self, - request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, - *, - organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = client.update_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest, dict]): - The request object. Request message for updating an - organization's settings. - organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_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 update_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - update_mask: 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]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v1p1beta1 - - def sample_update_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest, dict]): - The request object. Request message for updating a - source. - source (google.cloud.securitycenter_v1p1beta1.types.Source): - Required. The source resource to - update. - - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the source resource. - If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = 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_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - update_mask: 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]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_update_security_marks(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest, dict]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If - empty or set to "marks", all marks will be replaced. - Individual marks can be updated using - "marks.". - - 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.securitycenter_v1p1beta1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - 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_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe 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) -> "SecurityCenterClient": - 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__ = ( - "SecurityCenterClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py deleted file mode 100644 index ddad1b803817..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py +++ /dev/null @@ -1,839 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from 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.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source - - -class GroupAssetsPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupAssetsResponse], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1p1beta1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - 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[securitycenter_service.GroupAssetsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupAssetsAsyncPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` - attributes are available on the 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[securitycenter_service.GroupAssetsResponse]], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1p1beta1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - 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[securitycenter_service.GroupAssetsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1p1beta1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` - attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1p1beta1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListAssetsResponse], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - 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[securitycenter_service.ListAssetsResponse]: - 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - for page in self.pages: - yield from page.list_assets_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` - attributes are available on the 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[securitycenter_service.ListAssetsResponse]], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - 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[securitycenter_service.ListAssetsResponse]: - 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_assets_results: - 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.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.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[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v1p1beta1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - for page in self.pages: - yield from page.list_findings_results - - 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.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.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[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v1p1beta1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_findings_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - 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[securitycenter_service.ListNotificationConfigsResponse]: - 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[notification_config.NotificationConfig]: - for page in self.pages: - yield from page.notification_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsAsyncPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` - attributes are available on the 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[securitycenter_service.ListNotificationConfigsResponse]], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - 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[securitycenter_service.ListNotificationConfigsResponse]: - 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[notification_config.NotificationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.notification_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1p1beta1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` - attributes are available on the 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[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1p1beta1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.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-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py deleted file mode 100644 index 9d36139c1a9b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/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 SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .rest import SecurityCenterRestTransport -from .rest import SecurityCenterRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry['grpc'] = SecurityCenterGrpcTransport -_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport -_transport_registry['rest'] = SecurityCenterRestTransport - -__all__ = ( - 'SecurityCenterTransport', - 'SecurityCenterGrpcTransport', - 'SecurityCenterGrpcAsyncIOTransport', - 'SecurityCenterRestTransport', - 'SecurityCenterRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py deleted file mode 100644 index 00cffef9c86f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py +++ /dev/null @@ -1,591 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.securitycenter_v1p1beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -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 empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'securitycenter.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.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: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_source: gapic_v1.method.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method.wrap_method( - self.create_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method.wrap_method( - self.delete_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_notification_config: gapic_v1.method.wrap_method( - self.get_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_organization_settings: gapic_v1.method.wrap_method( - self.get_organization_settings, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_source: gapic_v1.method.wrap_method( - self.get_source, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.group_assets: gapic_v1.method.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method.wrap_method( - self.list_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_sources: gapic_v1.method.wrap_method( - self.list_sources, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.run_asset_discovery: gapic_v1.method.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_finding: gapic_v1.method.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method.wrap_method( - self.update_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=480.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 operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - 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 get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Union[ - notification_config.NotificationConfig, - Awaitable[notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Union[ - organization_settings.OrganizationSettings, - Awaitable[organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Union[ - source.Source, - Awaitable[source.Source] - ]]: - raise NotImplementedError() - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Union[ - securitycenter_service.GroupAssetsResponse, - Awaitable[securitycenter_service.GroupAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Union[ - securitycenter_service.GroupFindingsResponse, - Awaitable[securitycenter_service.GroupFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Union[ - securitycenter_service.ListAssetsResponse, - Awaitable[securitycenter_service.ListAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Union[ - securitycenter_service.ListFindingsResponse, - Awaitable[securitycenter_service.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Union[ - securitycenter_service.ListNotificationConfigsResponse, - Awaitable[securitycenter_service.ListNotificationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Union[ - securitycenter_service.ListSourcesResponse, - Awaitable[securitycenter_service.ListSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - 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 test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Union[ - gcs_organization_settings.OrganizationSettings, - Awaitable[gcs_organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Union[ - gcs_security_marks.SecurityMarks, - Awaitable[gcs_security_marks.SecurityMarks] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SecurityCenterTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py deleted file mode 100644 index a2a5e40ef1f0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py +++ /dev/null @@ -1,895 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import 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.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -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 empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V1p1Beta1 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: 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 create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - ~.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_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - ~.GroupAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - 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.securitycenter.v1p1beta1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - ~.ListNotificationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - operations_pb2.Operation]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - ~.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 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - ~.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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SecurityCenterGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index 0743b78ddbd6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,1125 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -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 empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V1p1Beta1 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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._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 create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - 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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - 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_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Awaitable[notification_config.NotificationConfig]]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Awaitable[organization_settings.OrganizationSettings]]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Awaitable[securitycenter_service.GroupAssetsResponse]]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - Awaitable[~.GroupAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse]]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Awaitable[securitycenter_service.ListAssetsResponse]]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - 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.securitycenter.v1p1beta1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - Awaitable[~.ListNotificationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse]]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - 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 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - 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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.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.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - 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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Awaitable[gcs_organization_settings.OrganizationSettings]]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks]]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - 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_source: gapic_v1.method_async.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method_async.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method_async.wrap_method( - self.create_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method_async.wrap_method( - self.delete_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( - self.get_iam_policy, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_notification_config: gapic_v1.method_async.wrap_method( - self.get_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_organization_settings: gapic_v1.method_async.wrap_method( - self.get_organization_settings, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_source: gapic_v1.method_async.wrap_method( - self.get_source, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.group_assets: gapic_v1.method_async.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method_async.wrap_method( - self.group_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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method_async.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method_async.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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method_async.wrap_method( - self.list_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_sources: gapic_v1.method_async.wrap_method( - self.list_sources, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.run_asset_discovery: gapic_v1.method_async.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method_async.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( - self.test_iam_permissions, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_finding: gapic_v1.method_async.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method_async.wrap_method( - self.update_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method_async.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method_async.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method_async.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py deleted file mode 100644 index ea67cf703231..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py +++ /dev/null @@ -1,3197 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # 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 path_template -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 -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -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.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SecurityCenterRestInterceptor: - """Interceptor for SecurityCenter. - - 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 SecurityCenterRestTransport. - - .. code-block:: python - class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): - def pre_create_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_organization_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_organization_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_assets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_assets(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_notification_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_notification_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_sources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_sources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_run_asset_discovery(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_run_asset_discovery(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_finding_state(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_finding_state(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_organization_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_organization_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_security_marks(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_security_marks(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_source(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) - client = SecurityCenterClient(transport=transport) - - - """ - def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for create_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_notification_config(self, request: securitycenter_service.CreateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: - """Post-rpc interceptor for create_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for create_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_delete_notification_config(self, request: securitycenter_service.DeleteNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_notification_config(self, request: securitycenter_service.GetNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_notification_config(self, response: notification_config.NotificationConfig) -> notification_config.NotificationConfig: - """Post-rpc interceptor for get_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_organization_settings(self, request: securitycenter_service.GetOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_organization_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_organization_settings(self, response: organization_settings.OrganizationSettings) -> organization_settings.OrganizationSettings: - """Post-rpc interceptor for get_organization_settings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_source(self, response: source.Source) -> source.Source: - """Post-rpc interceptor for get_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_assets(self, request: securitycenter_service.GroupAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_assets(self, response: securitycenter_service.GroupAssetsResponse) -> securitycenter_service.GroupAssetsResponse: - """Post-rpc interceptor for group_assets - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: - """Post-rpc interceptor for group_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_assets(self, request: securitycenter_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_assets(self, response: securitycenter_service.ListAssetsResponse) -> securitycenter_service.ListAssetsResponse: - """Post-rpc interceptor for list_assets - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. - """ - return request, metadata - - def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: - """Post-rpc interceptor for list_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_notification_configs(self, request: securitycenter_service.ListNotificationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListNotificationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_notification_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_notification_configs(self, response: securitycenter_service.ListNotificationConfigsResponse) -> securitycenter_service.ListNotificationConfigsResponse: - """Post-rpc interceptor for list_notification_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_sources - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: - """Post-rpc interceptor for list_sources - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_run_asset_discovery(self, request: securitycenter_service.RunAssetDiscoveryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.RunAssetDiscoveryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for run_asset_discovery - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_run_asset_discovery(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for run_asset_discovery - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for update_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_notification_config(self, request: securitycenter_service.UpdateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: - """Post-rpc interceptor for update_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_organization_settings(self, request: securitycenter_service.UpdateOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_organization_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_organization_settings(self, response: gcs_organization_settings.OrganizationSettings) -> gcs_organization_settings.OrganizationSettings: - """Post-rpc interceptor for update_organization_settings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: - """Post-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for update_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SecurityCenterRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SecurityCenterRestInterceptor - - -class SecurityCenterRestTransport(SecurityCenterTransport): - """REST backend transport for SecurityCenter. - - V1p1Beta1 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SecurityCenterRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 - 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 - ) - 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 SecurityCenterRestInterceptor() - 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': '/v1p1beta1/{name=organizations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1p1beta1/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1p1beta1/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1p1beta1/{name=organizations/*/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="v1p1beta1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "findingId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the create finding method over HTTP. - - Args: - request (~.securitycenter_service.CreateFindingRequest): - The request object. Request message for creating a - finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=organizations/*/sources/*}/findings', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_create_finding(request, metadata) - pb_request = securitycenter_service.CreateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_finding(resp) - return resp - - class _CreateNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "configId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_notification_config.NotificationConfig: - r"""Call the create notification - config method over HTTP. - - Args: - request (~.securitycenter_service.CreateNotificationConfigRequest): - The request object. Request message for creating a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=organizations/*}/notificationConfigs', - 'body': 'notification_config', - }, - ] - request, metadata = self._interceptor.pre_create_notification_config(request, metadata) - pb_request = securitycenter_service.CreateNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_notification_config.NotificationConfig() - pb_resp = gcs_notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_notification_config(resp) - return resp - - class _CreateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the create source method over HTTP. - - Args: - request (~.securitycenter_service.CreateSourceRequest): - The request object. Request message for creating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=organizations/*}/sources', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_create_source(request, metadata) - pb_request = securitycenter_service.CreateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_source(resp) - return resp - - class _DeleteNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete notification - config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteNotificationConfigRequest): - The request object. Request message for deleting a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1p1beta1/{name=organizations/*/notificationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_notification_config(request, metadata) - pb_request = securitycenter_service.DeleteNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _GetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{resource=organizations/*/sources/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _GetNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> notification_config.NotificationConfig: - r"""Call the get notification config method over HTTP. - - Args: - request (~.securitycenter_service.GetNotificationConfigRequest): - The request object. Request message for getting a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.notification_config.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{name=organizations/*/notificationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_notification_config(request, metadata) - pb_request = securitycenter_service.GetNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = notification_config.NotificationConfig() - pb_resp = notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_notification_config(resp) - return resp - - class _GetOrganizationSettings(SecurityCenterRestStub): - def __hash__(self): - return hash("GetOrganizationSettings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetOrganizationSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> organization_settings.OrganizationSettings: - r"""Call the get organization settings method over HTTP. - - Args: - request (~.securitycenter_service.GetOrganizationSettingsRequest): - The request object. Request message for getting - organization 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: - ~.organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{name=organizations/*/organizationSettings}', - }, - ] - request, metadata = self._interceptor.pre_get_organization_settings(request, metadata) - pb_request = securitycenter_service.GetOrganizationSettingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = organization_settings.OrganizationSettings() - pb_resp = organization_settings.OrganizationSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_organization_settings(resp) - return resp - - class _GetSource(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> source.Source: - r"""Call the get source method over HTTP. - - Args: - request (~.securitycenter_service.GetSourceRequest): - The request object. Request message for getting a source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{name=organizations/*/sources/*}', - }, - ] - request, metadata = self._interceptor.pre_get_source(request, metadata) - pb_request = securitycenter_service.GetSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = source.Source() - pb_resp = source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_source(resp) - return resp - - class _GroupAssets(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupAssets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupAssetsResponse: - r"""Call the group assets method over HTTP. - - Args: - request (~.securitycenter_service.GroupAssetsRequest): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupAssetsResponse: - Response message for grouping by - assets. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=organizations/*}/assets:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=folders/*}/assets:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=projects/*}/assets:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_assets(request, metadata) - pb_request = securitycenter_service.GroupAssetsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupAssetsResponse() - pb_resp = securitycenter_service.GroupAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_assets(resp) - return resp - - class _GroupFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupFindingsResponse: - r"""Call the group findings method over HTTP. - - Args: - request (~.securitycenter_service.GroupFindingsRequest): - The request object. Request message for grouping by - findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupFindingsResponse: - Response message for group by - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=organizations/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=folders/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=projects/*/sources/*}/findings:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_findings(request, metadata) - pb_request = securitycenter_service.GroupFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupFindingsResponse() - pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_findings(resp) - return resp - - class _ListAssets(SecurityCenterRestStub): - def __hash__(self): - return hash("ListAssets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListAssetsResponse: - r"""Call the list assets method over HTTP. - - Args: - request (~.securitycenter_service.ListAssetsRequest): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListAssetsResponse: - Response message for listing assets. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=organizations/*}/assets', - }, -{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=folders/*}/assets', - }, -{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=projects/*}/assets', - }, - ] - request, metadata = self._interceptor.pre_list_assets(request, metadata) - pb_request = securitycenter_service.ListAssetsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListAssetsResponse() - pb_resp = securitycenter_service.ListAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_assets(resp) - return resp - - class _ListFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("ListFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListFindingsResponse: - r"""Call the list findings method over HTTP. - - Args: - request (~.securitycenter_service.ListFindingsRequest): - The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListFindingsResponse: - Response message for listing - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=organizations/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=folders/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=projects/*/sources/*}/findings', - }, - ] - request, metadata = self._interceptor.pre_list_findings(request, metadata) - pb_request = securitycenter_service.ListFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListFindingsResponse() - pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_findings(resp) - return resp - - class _ListNotificationConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListNotificationConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListNotificationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListNotificationConfigsResponse: - r"""Call the list notification configs method over HTTP. - - Args: - request (~.securitycenter_service.ListNotificationConfigsRequest): - The request object. Request message for listing - notification configs. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListNotificationConfigsResponse: - Response message for listing - notification configs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=organizations/*}/notificationConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_notification_configs(request, metadata) - pb_request = securitycenter_service.ListNotificationConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListNotificationConfigsResponse() - pb_resp = securitycenter_service.ListNotificationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_notification_configs(resp) - return resp - - class _ListSources(SecurityCenterRestStub): - def __hash__(self): - return hash("ListSources") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListSourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListSourcesResponse: - r"""Call the list sources method over HTTP. - - Args: - request (~.securitycenter_service.ListSourcesRequest): - The request object. Request message for listing sources. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListSourcesResponse: - Response message for listing sources. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=organizations/*}/sources', - }, -{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=folders/*}/sources', - }, -{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=projects/*}/sources', - }, - ] - request, metadata = self._interceptor.pre_list_sources(request, metadata) - pb_request = securitycenter_service.ListSourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListSourcesResponse() - pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_sources(resp) - return resp - - class _RunAssetDiscovery(SecurityCenterRestStub): - def __hash__(self): - return hash("RunAssetDiscovery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.RunAssetDiscoveryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the run asset discovery method over HTTP. - - Args: - request (~.securitycenter_service.RunAssetDiscoveryRequest): - The request object. Request message for running asset - discovery for an organization. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=organizations/*}/assets:runDiscovery', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_run_asset_discovery(request, metadata) - pb_request = securitycenter_service.RunAssetDiscoveryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_run_asset_discovery(resp) - return resp - - class _SetFindingState(SecurityCenterRestStub): - def __hash__(self): - return hash("SetFindingState") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SetFindingStateRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the set finding state method over HTTP. - - Args: - request (~.securitycenter_service.SetFindingStateRequest): - The request object. Request message for updating a - finding's state. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{name=organizations/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1p1beta1/{name=folders/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1p1beta1/{name=projects/*/sources/*/findings/*}:setState', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_finding_state(request, metadata) - pb_request = securitycenter_service.SetFindingStateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_set_finding_state(resp) - return resp - - class _SetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{resource=organizations/*/sources/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _TestIamPermissions(SecurityCenterRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{resource=organizations/*/sources/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UpdateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the update finding method over HTTP. - - Args: - request (~.securitycenter_service.UpdateFindingRequest): - The request object. Request message for updating or - creating a finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1p1beta1/{finding.name=organizations/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{finding.name=folders/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{finding.name=projects/*/sources/*/findings/*}', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_update_finding(request, metadata) - pb_request = securitycenter_service.UpdateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_finding(resp) - return resp - - class _UpdateNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_notification_config.NotificationConfig: - r"""Call the update notification - config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateNotificationConfigRequest): - The request object. Request message for updating a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1p1beta1/{notification_config.name=organizations/*/notificationConfigs/*}', - 'body': 'notification_config', - }, - ] - request, metadata = self._interceptor.pre_update_notification_config(request, metadata) - pb_request = securitycenter_service.UpdateNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_notification_config.NotificationConfig() - pb_resp = gcs_notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_notification_config(resp) - return resp - - class _UpdateOrganizationSettings(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateOrganizationSettings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateOrganizationSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Call the update organization - settings method over HTTP. - - Args: - request (~.securitycenter_service.UpdateOrganizationSettingsRequest): - The request object. Request message for updating an - organization's 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: - ~.gcs_organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1p1beta1/{organization_settings.name=organizations/*/organizationSettings}', - 'body': 'organization_settings', - }, - ] - request, metadata = self._interceptor.pre_update_organization_settings(request, metadata) - pb_request = securitycenter_service.UpdateOrganizationSettingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_organization_settings.OrganizationSettings() - pb_resp = gcs_organization_settings.OrganizationSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_organization_settings(resp) - return resp - - class _UpdateSecurityMarks(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSecurityMarks") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSecurityMarksRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_security_marks.SecurityMarks: - r"""Call the update security marks method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSecurityMarksRequest): - The request object. Request message for updating a - SecurityMarks resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1p1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{security_marks.name=folders/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{security_marks.name=projects/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, - ] - request, metadata = self._interceptor.pre_update_security_marks(request, metadata) - pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_security_marks.SecurityMarks() - pb_resp = gcs_security_marks.SecurityMarks.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_security_marks(resp) - return resp - - class _UpdateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the update source method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSourceRequest): - The request object. Request message for updating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1p1beta1/{source.name=organizations/*/sources/*}', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_update_source(request, metadata) - pb_request = securitycenter_service.UpdateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_source(resp) - return resp - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - 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._DeleteNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.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_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListNotificationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSources(self._session, self._host, self._interceptor) # type: ignore - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - 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._RunAssetDiscovery(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SecurityCenterRestTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py deleted file mode 100644 index 9f0c2b8e8129..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__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 .asset import ( - Asset, -) -from .finding import ( - Finding, -) -from .folder import ( - Folder, -) -from .notification_config import ( - NotificationConfig, -) -from .notification_message import ( - NotificationMessage, -) -from .organization_settings import ( - OrganizationSettings, -) -from .resource import ( - Resource, -) -from .run_asset_discovery_response import ( - RunAssetDiscoveryResponse, -) -from .security_marks import ( - SecurityMarks, -) -from .securitycenter_service import ( - CreateFindingRequest, - CreateNotificationConfigRequest, - CreateSourceRequest, - DeleteNotificationConfigRequest, - GetNotificationConfigRequest, - GetOrganizationSettingsRequest, - GetSourceRequest, - GroupAssetsRequest, - GroupAssetsResponse, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListAssetsRequest, - ListAssetsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListNotificationConfigsRequest, - ListNotificationConfigsResponse, - ListSourcesRequest, - ListSourcesResponse, - RunAssetDiscoveryRequest, - SetFindingStateRequest, - UpdateFindingRequest, - UpdateNotificationConfigRequest, - UpdateOrganizationSettingsRequest, - UpdateSecurityMarksRequest, - UpdateSourceRequest, -) -from .source import ( - Source, -) - -__all__ = ( - 'Asset', - 'Finding', - 'Folder', - 'NotificationConfig', - 'NotificationMessage', - 'OrganizationSettings', - 'Resource', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateNotificationConfigRequest', - 'CreateSourceRequest', - 'DeleteNotificationConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py deleted file mode 100644 index 2250330a504d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py +++ /dev/null @@ -1,227 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1p1beta1.types import folder -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'Asset', - }, -) - - -class Asset(proto.Message): - r"""Security Command Center representation of a Google Cloud - resource. - - The Asset is a Security Command Center resource that captures - information about a single Google Cloud resource. All - modifications to an Asset are only within the context of - Security Command Center and don't affect the referenced Google - Cloud resource. - - Attributes: - name (str): - The relative resource name of this asset. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (google.cloud.securitycenter_v1p1beta1.types.Asset.SecurityCenterProperties): - Security Command Center managed properties. - These properties are managed by Security Command - Center and cannot be modified by the user. - resource_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Resource managed properties. These properties - are managed and defined by the Google Cloud - resource and cannot be modified by the user. - security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): - User specified security marks. These marks - are entirely managed by the user and come from - the SecurityMarks resource that belongs to the - asset. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was created in - Security Command Center. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was last updated - or added in Cloud SCC. - iam_policy (google.cloud.securitycenter_v1p1beta1.types.Asset.IamPolicy): - Cloud IAM Policy information associated with - the Google Cloud resource described by the - Security Command Center asset. This information - is managed and defined by the Google Cloud - resource and cannot be modified by the user. - canonical_name (str): - The canonical name of the resource. It's either - "organizations/{organization_id}/assets/{asset_id}", - "folders/{folder_id}/assets/{asset_id}" or - "projects/{project_number}/assets/{asset_id}", depending on - the closest CRM ancestor of the resource. - """ - - class SecurityCenterProperties(proto.Message): - r"""Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified by - the user. - - Attributes: - resource_name (str): - The full resource name of the Google Cloud resource this - asset represents. This field is immutable after create time. - See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_type (str): - The type of the Google Cloud resource. - Examples include: APPLICATION, PROJECT, and - ORGANIZATION. This is a case insensitive field - defined by Security Command Center and/or the - producer of the resource and is immutable after - create time. - resource_parent (str): - The full resource name of the immediate parent of the - resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_project (str): - The full resource name of the project the resource belongs - to. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_owners (MutableSequence[str]): - Owners of the Google Cloud resource. - resource_display_name (str): - The user defined display name for this - resource. - resource_parent_display_name (str): - The user defined display name for the parent - of this resource. - resource_project_display_name (str): - The user defined display name for the project - of this resource. - folders (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): - Contains a Folder message for each folder in - the assets ancestry. The first folder is the - deepest nested folder, and the last folder is - the folder directly under the Organization. - """ - - resource_name: str = proto.Field( - proto.STRING, - number=1, - ) - resource_type: str = proto.Field( - proto.STRING, - number=2, - ) - resource_parent: str = proto.Field( - proto.STRING, - number=3, - ) - resource_project: str = proto.Field( - proto.STRING, - number=4, - ) - resource_owners: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - resource_display_name: str = proto.Field( - proto.STRING, - number=6, - ) - resource_parent_display_name: str = proto.Field( - proto.STRING, - number=7, - ) - resource_project_display_name: str = proto.Field( - proto.STRING, - number=8, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=folder.Folder, - ) - - class IamPolicy(proto.Message): - r"""Cloud IAM Policy information associated with the Google Cloud - resource described by the Security Command Center asset. This - information is managed and defined by the Google Cloud resource - and cannot be modified by the user. - - Attributes: - policy_blob (str): - The JSON representation of the Policy - associated with the asset. See - https://cloud.google.com/iam/docs/reference/rest/v1/Policy - for format details. - """ - - policy_blob: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - security_center_properties: SecurityCenterProperties = proto.Field( - proto.MESSAGE, - number=2, - message=SecurityCenterProperties, - ) - resource_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - iam_policy: IamPolicy = proto.Field( - proto.MESSAGE, - number=11, - message=IamPolicy, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=13, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py deleted file mode 100644 index 8fe9a48e3cfb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - - A finding is a record of assessment data (security, risk, health - or privacy) ingested into Security Command Center for - presentation, notification, analysis, policy testing, and - enforcement. For example, an XSS vulnerability in an App Engine - application is a finding. - - Attributes: - name (str): - The relative resource name of this finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". - parent (str): - The relative resource name of the source the finding belongs - to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. For example: - "organizations/{organization_id}/sources/{source_id}". - resource_name (str): - For findings on Google Cloud resources, the full resource - name of the Google Cloud resource this finding is for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - This field is immutable after creation time. - state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): - The state of the finding. - category (str): - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. - Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the event took place, or - when an update to the finding occurred. For - example, if the finding represents an open - firewall it would capture the time the detector - believes the firewall became open. The accuracy - is determined by the detector. If the finding - were to be resolved afterward, this time would - reflect when the finding was resolved. Must not - be set to a value greater than the current - timestamp. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the finding was created in - Security Command Center. - severity (google.cloud.securitycenter_v1p1beta1.types.Finding.Severity): - The severity of the finding. This field is - managed by the source that writes the finding. - canonical_name (str): - The canonical name of the finding. It's either - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" - or - "projects/{project_number}/sources/{source_id}/findings/{finding_id}", - depending on the closest CRM ancestor of the resource - associated with the finding. - """ - class State(proto.Enum): - r"""The state of the finding. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - ACTIVE (1): - The finding requires attention and has not - been addressed yet. - INACTIVE (2): - The finding has been fixed, triaged as a - non-issue or otherwise addressed and is no - longer active. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - class Severity(proto.Enum): - r"""The severity of the finding. This field is managed by the - source that writes the finding. - - 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, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - resource_name: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - category: str = proto.Field( - proto.STRING, - number=5, - ) - external_uri: str = proto.Field( - proto.STRING, - number=6, - ) - source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - severity: Severity = proto.Field( - proto.ENUM, - number=13, - enum=Severity, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=14, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py deleted file mode 100644 index 17d1a3c450ed..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.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.securitycenter.v1p1beta1', - manifest={ - 'Folder', - }, -) - - -class Folder(proto.Message): - r"""Message that contains the resource name and display name of a - folder resource. - - Attributes: - resource_folder (str): - Full resource name of this folder. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_folder_display_name (str): - The user defined display name for this - folder. - """ - - resource_folder: str = proto.Field( - proto.STRING, - number=1, - ) - resource_folder_display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py deleted file mode 100644 index 8b92401c657b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'NotificationConfig', - }, -) - - -class NotificationConfig(proto.Message): - r"""Security Command Center notification configs. - - A notification config is a Security Command Center resource that - contains the configuration to send notifications for - create/update events of findings, assets and etc. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The relative resource name of this notification config. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/notificationConfigs/notify_public_bucket". - description (str): - The description of the notification config - (max of 1024 characters). - event_type (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.EventType): - The type of events the config is for, e.g. - FINDING. - pubsub_topic (str): - The Pub/Sub topic to send notifications to. Its format is - "projects/[project_id]/topics/[topic]". - service_account (str): - Output only. The service account that needs - "pubsub.topics.publish" permission to publish to - the Pub/Sub topic. - streaming_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.StreamingConfig): - The config for triggering streaming-based - notifications. - - This field is a member of `oneof`_ ``notify_config``. - """ - class EventType(proto.Enum): - r"""The type of events. - - Values: - EVENT_TYPE_UNSPECIFIED (0): - Unspecified event type. - FINDING (1): - Events for findings. - """ - EVENT_TYPE_UNSPECIFIED = 0 - FINDING = 1 - - class StreamingConfig(proto.Message): - r"""The config for streaming-based notifications, which send each - event as soon as it is detected. - - Attributes: - filter (str): - Expression that defines the filter to apply across - create/update events of assets or findings as specified by - the event type. The expression is a list of zero or more - restrictions combined via logical operators ``AND`` and - ``OR``. Parentheses are supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - """ - - filter: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - event_type: EventType = proto.Field( - proto.ENUM, - number=3, - enum=EventType, - ) - pubsub_topic: str = proto.Field( - proto.STRING, - number=4, - ) - service_account: str = proto.Field( - proto.STRING, - number=5, - ) - streaming_config: StreamingConfig = proto.Field( - proto.MESSAGE, - number=6, - oneof='notify_config', - message=StreamingConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py deleted file mode 100644 index 5572db1a6d80..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.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.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import resource as gcs_resource - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'NotificationMessage', - }, -) - - -class NotificationMessage(proto.Message): - r"""Security Command Center's Notification - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - notification_config_name (str): - Name of the notification config that - generated current notification. - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - If it's a Finding based notification config, - this field will be populated. - - This field is a member of `oneof`_ ``event``. - resource (google.cloud.securitycenter_v1p1beta1.types.Resource): - The Cloud resource tied to the notification. - """ - - notification_config_name: str = proto.Field( - proto.STRING, - number=1, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=2, - oneof='event', - message=gcs_finding.Finding, - ) - resource: gcs_resource.Resource = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_resource.Resource, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py deleted file mode 100644 index e8a49050b4aa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'OrganizationSettings', - }, -) - - -class OrganizationSettings(proto.Message): - r"""User specified settings that are attached to the Security - Command Center organization. - - Attributes: - name (str): - The relative resource name of the settings. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/organizationSettings". - enable_asset_discovery (bool): - A flag that indicates if Asset Discovery should be enabled. - If the flag is set to ``true``, then discovery of assets - will occur. If it is set to \`false, all historical assets - will remain, but discovery of future assets will not occur. - asset_discovery_config (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig): - The configuration used for Asset Discovery - runs. - """ - - class AssetDiscoveryConfig(proto.Message): - r"""The configuration used for Asset Discovery runs. - - Attributes: - project_ids (MutableSequence[str]): - The project ids to use for filtering asset - discovery. - inclusion_mode (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): - The mode to use for filtering asset - discovery. - folder_ids (MutableSequence[str]): - The folder ids to use for filtering asset - discovery. It consists of only digits, e.g., - 756619654966. - """ - class InclusionMode(proto.Enum): - r"""The mode of inclusion when running Asset Discovery. Asset discovery - can be limited by explicitly identifying projects to be included or - excluded. If INCLUDE_ONLY is set, then only those projects within - the organization and their children are discovered during asset - discovery. If EXCLUDE is set, then projects that don't match those - projects are discovered during asset discovery. If neither are set, - then all projects within the organization are discovered during - asset discovery. - - Values: - INCLUSION_MODE_UNSPECIFIED (0): - Unspecified. Setting the mode with this value - will disable inclusion/exclusion filtering for - Asset Discovery. - INCLUDE_ONLY (1): - Asset Discovery will capture only the - resources within the projects specified. All - other resources will be ignored. - EXCLUDE (2): - Asset Discovery will ignore all resources - under the projects specified. All other - resources will be retrieved. - """ - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - project_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - inclusion_mode: 'OrganizationSettings.AssetDiscoveryConfig.InclusionMode' = proto.Field( - proto.ENUM, - number=2, - enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', - ) - folder_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - enable_asset_discovery: bool = proto.Field( - proto.BOOL, - number=2, - ) - asset_discovery_config: AssetDiscoveryConfig = proto.Field( - proto.MESSAGE, - number=3, - message=AssetDiscoveryConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py deleted file mode 100644 index 2fd5e7836be1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py +++ /dev/null @@ -1,85 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1p1beta1.types import folder - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'Resource', - }, -) - - -class Resource(proto.Message): - r"""Information related to the Google Cloud resource. - - Attributes: - name (str): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - project (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The human readable name of project that the - resource belongs to. - parent (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): - Output only. Contains a Folder message for - each folder in the assets ancestry. The first - folder is the deepest nested folder, and the - last folder is the folder directly under the - Organization. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - project: str = proto.Field( - proto.STRING, - number=2, - ) - project_display_name: str = proto.Field( - proto.STRING, - number=3, - ) - parent: str = proto.Field( - proto.STRING, - number=4, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=5, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=folder.Folder, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py deleted file mode 100644 index 10769c100399..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.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 - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'RunAssetDiscoveryResponse', - }, -) - - -class RunAssetDiscoveryResponse(proto.Message): - r"""Response of asset discovery run - - Attributes: - state (google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse.State): - The state of an asset discovery run. - duration (google.protobuf.duration_pb2.Duration): - The duration between asset discovery run - start and end - """ - class State(proto.Enum): - r"""The state of an asset discovery run. - - Values: - STATE_UNSPECIFIED (0): - Asset discovery run state was unspecified. - COMPLETED (1): - Asset discovery run completed successfully. - SUPERSEDED (2): - Asset discovery run was cancelled with tasks - still pending, as another run for the same - organization was started with a higher priority. - TERMINATED (3): - Asset discovery run was killed and - terminated. - """ - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py deleted file mode 100644 index 8473d65602f2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'SecurityMarks', - }, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (MutableMapping[str, str]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - canonical_name (str): - The canonical name of the marks. Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "folders/{folder_id}/assets/{asset_id}/securityMarks" - "projects/{project_number}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" - "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - marks: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py deleted file mode 100644 index 42ec8bf37842..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py +++ /dev/null @@ -1,1641 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1p1beta1.types import asset as gcs_asset -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import folder -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'CreateFindingRequest', - 'CreateNotificationConfigRequest', - 'CreateSourceRequest', - 'DeleteNotificationConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'SetFindingStateRequest', - 'RunAssetDiscoveryRequest', - 'UpdateFindingRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSourceRequest', - 'UpdateSecurityMarksRequest', - }, -) - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - - Attributes: - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - finding_id: str = proto.Field( - proto.STRING, - number=2, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_finding.Finding, - ) - - -class CreateNotificationConfigRequest(proto.Message): - r"""Request message for creating a notification config. - - Attributes: - parent (str): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - config_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - between 1 and 128 characters, and contains - alphanumeric characters, underscores or hyphens - only. - notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): - Required. The notification config being - created. The name and the service account will - be ignored as they are both output only fields - on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - config_id: str = proto.Field( - proto.STRING, - number=2, - ) - notification_config: gcs_notification_config.NotificationConfig = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_notification_config.NotificationConfig, - ) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - source (google.cloud.securitycenter_v1p1beta1.types.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_source.Source, - ) - - -class DeleteNotificationConfigRequest(proto.Message): - r"""Request message for deleting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetNotificationConfigRequest(proto.Message): - r"""Request message for getting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to get. Its format - is - "organizations/[organization_id]/notificationConfigs/[config_id]". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetOrganizationSettingsRequest(proto.Message): - r"""Request message for getting organization settings. - - Attributes: - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is "organizations/[organization_id]/source/[source_id]". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GroupAssetsRequest(proto.Message): - r"""Request message for grouping by assets. - - Attributes: - parent (str): - Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id], folders/[folder_id], or - projects/[project_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_name_display_name: - ``=``, ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is - not set: - - - security_center_properties.resource_project - - security_center_properties.resource_project_display_name - - security_center_properties.resource_type - - security_center_properties.resource_parent - - security_center_properties.resource_parent_display_name - - The following fields are supported when compare_duration is - set: - - - security_center_properties.resource_type - - security_center_properties.resource_project_display_name - - security_center_properties.resource_parent_display_name - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the GroupResult's - "state_change" property is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at - reference_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and reference_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupAssetsResponse``; - indicates that this is a continuation of a prior - ``GroupAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - page_size: int = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupAssetsResponse(proto.Message): - r"""Response message for grouping by assets. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - - Attributes: - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]", - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]. To groupBy across - all sources provide a source_id of ``-``. For example: - organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/-, or - projects/{project_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - - severity: ``=``, ``:`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - security_marks.marks: ``=``, ``:`` - - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping (including ``state_change``). The string value - should follow SQL syntax: comma separated list of fields. - For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - severity - - The following fields are supported when compare_duration is - set: - - - state_change - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the GroupResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - page_size: int = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message=struct_pb2.Value, - ) - count: int = proto.Field( - proto.INT64, - number=2, - ) - - -class ListNotificationConfigsRequest(proto.Message): - r"""Request message for listing notification configs. - - Attributes: - parent (str): - Required. Name of the organization to list notification - configs. Its format is "organizations/[organization_id]". - page_token (str): - The value returned by the last - ``ListNotificationConfigsResponse``; indicates that this is - a continuation of a prior ``ListNotificationConfigs`` call, - and that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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 ListNotificationConfigsResponse(proto.Message): - r"""Response message for listing notification configs. - - Attributes: - notification_configs (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.NotificationConfig]): - Notification configs belonging to the - requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - notification_configs: MutableSequence[gcs_notification_config.NotificationConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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=7, - ) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - - Attributes: - sources (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListAssetsRequest(proto.Message): - r"""Request message for listing assets. - - Attributes: - parent (str): - Required. Name of the organization assets should belong to. - Its format is "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following are the allowed field and operator - combinations: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, - ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,resource_properties.a_property". - Redundant space characters in the syntax are insignificant. - "name desc,resource_properties.a_property" and " name desc , - resource_properties.a_property " are equivalent. - - The following fields are supported: name update_time - resource_properties security_marks.marks - security_center_properties.resource_name - security_center_properties.resource_display_name - security_center_properties.resource_parent - security_center_properties.resource_parent_display_name - security_center_properties.resource_project - security_center_properties.resource_project_display_name - security_center_properties.resource_type - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListAssetsResult's - "state_change" attribute is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at read_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at read_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the ListAssetsResult - fields to be listed in the response. - An empty field mask will list all fields. - page_token (str): - The value returned by the last ``ListAssetsResponse``; - indicates that this is a continuation of a prior - ``ListAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=8, - ) - page_size: int = proto.Field( - proto.INT32, - number=9, - ) - - -class ListAssetsResponse(proto.Message): - r"""Response message for listing assets. - - Attributes: - list_assets_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult]): - Assets matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of assets matching the - query. - """ - - class ListAssetsResult(proto.Message): - r"""Result containing the Asset and its State. - - Attributes: - asset (google.cloud.securitycenter_v1p1beta1.types.Asset): - Asset matching the search request. - state_change (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult.StateChange): - State change of the asset between the points - in time. - """ - class StateChange(proto.Enum): - r"""The change in state of the asset. - - When querying across two points in time this describes the change - between the two points: ADDED, REMOVED, or ACTIVE. If there was no - compare_duration supplied in the request the state change will be: - UNUSED - - Values: - UNUSED (0): - State change is unused, this is the canonical - default for this enum. - ADDED (1): - Asset was added between the points in time. - REMOVED (2): - Asset was removed between the points in time. - ACTIVE (3): - Asset was present at both point(s) in time. - """ - UNUSED = 0 - ADDED = 1 - REMOVED = 2 - ACTIVE = 3 - - asset: gcs_asset.Asset = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_asset.Asset, - ) - state_change: 'ListAssetsResponse.ListAssetsResult.StateChange' = proto.Field( - proto.ENUM, - number=2, - enum='ListAssetsResponse.ListAssetsResult.StateChange', - ) - - @property - def raw_page(self): - return self - - list_assets_results: MutableSequence[ListAssetsResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListAssetsResult, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - - Attributes: - parent (str): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id], - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]". To list across - all sources provide a source_id of ``-``. For example: - organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/- or - projects/{projects_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - - severity: ``=``, ``:`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - security_marks.marks: ``=``, ``:`` source_properties: ``=``, - ``:``, ``>``, ``<``, ``>=``, ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,source_properties.a_property". Redundant - space characters in the syntax are insignificant. "name - desc,source_properties.a_property" and " name desc , - source_properties.a_property " are equivalent. - - The following fields are supported: name parent state - category resource_name event_time source_properties - security_marks.marks - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListFindingsResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added in any state during - the compare_duration period of time that precedes the - read_time. This is the time between (read_time - - compare_duration) and read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the Finding fields to - be listed in the response. An empty field mask - will list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=8, - ) - page_size: int = proto.Field( - proto.INT32, - number=9, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - - Attributes: - list_findings_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult]): - Findings matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - class ListFindingsResult(proto.Message): - r"""Result containing the Finding and its StateChange. - - Attributes: - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Finding matching the search request. - state_change (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.StateChange): - State change of the finding between the - points in time. - resource (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.Resource): - Output only. Resource that is associated with - this finding. - """ - class StateChange(proto.Enum): - r"""The change in state of the finding. - - When querying across two points in time this describes the change in - the finding between the two points: CHANGED, UNCHANGED, ADDED, or - REMOVED. Findings can not be deleted, so REMOVED implies that the - finding at timestamp does not match the filter specified, but it did - at timestamp - compare_duration. If there was no compare_duration - supplied in the request the state change will be: UNUSED - - Values: - UNUSED (0): - State change is unused, this is the canonical - default for this enum. - CHANGED (1): - The finding has changed state in some way - between the points in time and existed at both - points. - UNCHANGED (2): - The finding has not changed state between the - points in time and existed at both points. - ADDED (3): - The finding was created between the points in - time. - REMOVED (4): - The finding at timestamp does not match the filter - specified, but it did at timestamp - compare_duration. - """ - UNUSED = 0 - CHANGED = 1 - UNCHANGED = 2 - ADDED = 3 - REMOVED = 4 - - class Resource(proto.Message): - r"""Information related to the Google Cloud resource that is - associated with this finding. - - Attributes: - name (str): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - project_name (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The human readable name of project that the - resource belongs to. - parent_name (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): - Contains a Folder message for each folder in - the assets ancestry. The first folder is the - deepest nested folder, and the last folder is - the folder directly under the Organization. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - project_name: str = proto.Field( - proto.STRING, - number=2, - ) - project_display_name: str = proto.Field( - proto.STRING, - number=3, - ) - parent_name: str = proto.Field( - proto.STRING, - number=4, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=5, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=folder.Folder, - ) - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - state_change: 'ListFindingsResponse.ListFindingsResult.StateChange' = proto.Field( - proto.ENUM, - number=2, - enum='ListFindingsResponse.ListFindingsResult.StateChange', - ) - resource: 'ListFindingsResponse.ListFindingsResult.Resource' = proto.Field( - proto.MESSAGE, - number=3, - message='ListFindingsResponse.ListFindingsResult.Resource', - ) - - @property - def raw_page(self): - return self - - list_findings_results: MutableSequence[ListFindingsResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListFindingsResult, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - - Attributes: - name (str): - Required. The relative resource name of the finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): - Required. The desired State of the finding. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the updated state - takes effect. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: gcs_finding.Finding.State = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.State, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class RunAssetDiscoveryRequest(proto.Message): - r"""Request message for running asset discovery for an - organization. - - Attributes: - parent (str): - Required. Name of the organization to run asset discovery - for. Its format is "organizations/[organization_id]". - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - - Attributes: - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must be alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing source_properties. - Individual source_properties can be added/updated by using - "source_properties." in the field mask. - """ - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateNotificationConfigRequest(proto.Message): - r"""Request message for updating a notification config. - - Attributes: - notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): - Required. The notification config to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - notification config. - If empty all mutable fields will be updated. - """ - - notification_config: gcs_notification_config.NotificationConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateOrganizationSettingsRequest(proto.Message): - r"""Request message for updating an organization's settings. - - Attributes: - organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): - Required. The organization settings resource - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - settings resource. - If empty all mutable fields will be updated. - """ - - organization_settings: gcs_organization_settings.OrganizationSettings = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_organization_settings.OrganizationSettings, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - - Attributes: - source (google.cloud.securitycenter_v1p1beta1.types.Source): - Required. The source resource to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the source - resource. - If empty all mutable fields will be updated. - """ - - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - - Attributes: - security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): - Required. The security marks resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If empty - or set to "marks", all marks will be replaced. Individual - marks can be updated using "marks.". - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the updated SecurityMarks - take effect. If not set uses current server - time. Updates will be applied to the - SecurityMarks that are active immediately - preceding this time. - """ - - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_security_marks.SecurityMarks, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - start_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-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py deleted file mode 100644 index 53b3d04fda40..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'Source', - }, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, etc. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and - outdated/insecure libraries.". - canonical_name (str): - The canonical name of the finding. It's either - "organizations/{organization_id}/sources/{source_id}", - "folders/{folder_id}/sources/{source_id}" or - "projects/{project_number}/sources/{source_id}", depending - on the closest CRM ancestor of the resource associated with - the finding. - """ - - 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, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=14, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/noxfile.py deleted file mode 100644 index 32b130e85f33..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-securitycenter' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -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"): - 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/securitycenter_v1p1beta1/', - '--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"): - 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", - "grpcio", - "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/securitycenter_v1p1beta1/', - '--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( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): - # Ignore release of mypy 1.11.0 which may have a regression - 'mypy!=1.11.0', - '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-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_async.py deleted file mode 100644 index 9609719bb2ab..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_create_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py deleted file mode 100644 index a908f103062d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_create_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py deleted file mode 100644 index ce18ebfeab2a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_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 CreateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_create_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.create_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py deleted file mode 100644 index ec4621a56f92..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_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 CreateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_create_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = client.create_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_async.py deleted file mode 100644 index a05525b26ae5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_create_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_sync.py deleted file mode 100644 index 53a2606db659..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_create_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py deleted file mode 100644 index 77696925a3b2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_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 DeleteNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_config(request=request) - - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py deleted file mode 100644 index 697bd5dc58b7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_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 DeleteNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_config(request=request) - - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py deleted file mode 100644 index 0143835b3615..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py deleted file mode 100644 index fc6a2f9ecd38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py deleted file mode 100644 index beffb7197acc..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_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 GetNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_get_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py deleted file mode 100644 index e0bf761c0629..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_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 GetNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_get_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py deleted file mode 100644 index 25b7d03ebdb4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_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 GetOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py deleted file mode 100644 index 94cd60452455..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_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 GetOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_async.py deleted file mode 100644 index 1210ba0c3e4e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_get_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_sync.py deleted file mode 100644 index 942cc4b79272..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_get_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_async.py deleted file mode 100644 index a487bea8e359..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_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 GroupAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_group_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py deleted file mode 100644 index c99f19c6389b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_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 GroupAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_group_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_async.py deleted file mode 100644 index 3f65d770b14b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_group_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py deleted file mode 100644 index f70d29e29a1d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_group_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_async.py deleted file mode 100644 index 55dec3edae30..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_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 ListAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_list_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py deleted file mode 100644 index 150f9240dedb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_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 ListAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_list_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_async.py deleted file mode 100644 index 6b7785c3b4f1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_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 securitycenter_v1p1beta1 - - -async def sample_list_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py deleted file mode 100644 index 5a8b07c8466d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_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 securitycenter_v1p1beta1 - - -def sample_list_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py deleted file mode 100644 index 41cdb54d0669..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_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 ListNotificationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py deleted file mode 100644 index 8d8286a62581..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_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 ListNotificationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_async.py deleted file mode 100644 index 261f3b9fcb73..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_list_sources(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py deleted file mode 100644 index 847e73dd0797..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_list_sources(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py deleted file mode 100644 index 47e5c5bb61d7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py deleted file mode 100644 index fa965b321439..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py deleted file mode 100644 index 4d10d033f247..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_set_finding_state(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py deleted file mode 100644 index a77fb9ce8347..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_set_finding_state(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py deleted file mode 100644 index 3cd28543769f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py deleted file mode 100644 index 29ba6d93636e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py deleted file mode 100644 index 8b663d640a2f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py deleted file mode 100644 index b484fc5c8e69..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_async.py deleted file mode 100644 index 6fbcfd65b541..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_update_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py deleted file mode 100644 index 11a3b6e7fac8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_update_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py deleted file mode 100644 index cc60d07059d3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_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 UpdateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_update_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = await client.update_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py deleted file mode 100644 index 1ad9f8ee9c1c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_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 UpdateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_update_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = client.update_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py deleted file mode 100644 index 962efe30b0e6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = await client.update_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py deleted file mode 100644 index 007047607a2f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = client.update_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py deleted file mode 100644 index 6f9484b9d009..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_update_security_marks(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py deleted file mode 100644 index 091847a4ef33..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_update_security_marks(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_async.py deleted file mode 100644 index 559623a451be..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_update_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_sync.py deleted file mode 100644 index 5f72d8dd2b64..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_update_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json deleted file mode 100644 index 774592ce11f7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json +++ /dev/null @@ -1,3808 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.securitycenter.v1p1beta1", - "version": "v1p1beta1" - } - ], - "language": "PYTHON", - "name": "google-cloud-securitycenter", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v1p1beta1_generated_security_center_create_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1p1beta1_generated_security_center_create_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.create_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "config_id", - "type": "str" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig", - "shortName": "create_notification_config" - }, - "description": "Sample for CreateNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.create_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "config_id", - "type": "str" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig", - "shortName": "create_notification_config" - }, - "description": "Sample for CreateNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1p1beta1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v1p1beta1_generated_security_center_create_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_create_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1p1beta1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v1p1beta1_generated_security_center_create_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_create_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.delete_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.DeleteNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest" - }, - { - "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_config" - }, - "description": "Sample for DeleteNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.delete_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.DeleteNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest" - }, - { - "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_config" - }, - "description": "Sample for DeleteNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest" - }, - { - "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.securitycenter_v1p1beta1.types.NotificationConfig", - "shortName": "get_notification_config" - }, - "description": "Sample for GetNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest" - }, - { - "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.securitycenter_v1p1beta1.types.NotificationConfig", - "shortName": "get_notification_config" - }, - "description": "Sample for GetNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest" - }, - { - "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.securitycenter_v1p1beta1.types.OrganizationSettings", - "shortName": "get_organization_settings" - }, - "description": "Sample for GetOrganizationSettings", - "file": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest" - }, - { - "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.securitycenter_v1p1beta1.types.OrganizationSettings", - "shortName": "get_organization_settings" - }, - "description": "Sample for GetOrganizationSettings", - "file": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest" - }, - { - "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.securitycenter_v1p1beta1.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v1p1beta1_generated_security_center_get_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest" - }, - { - "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.securitycenter_v1p1beta1.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v1p1beta1_generated_security_center_get_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.group_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsAsyncPager", - "shortName": "group_assets" - }, - "description": "Sample for GroupAssets", - "file": "securitycenter_v1p1beta1_generated_security_center_group_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1p1beta1_generated_security_center_group_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.group_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsPager", - "shortName": "group_assets" - }, - "description": "Sample for GroupAssets", - "file": "securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsAsyncPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v1p1beta1_generated_security_center_group_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1p1beta1_generated_security_center_group_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsAsyncPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "securitycenter_v1p1beta1_generated_security_center_list_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1p1beta1_generated_security_center_list_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsAsyncPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v1p1beta1_generated_security_center_list_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1p1beta1_generated_security_center_list_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_notification_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListNotificationConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListNotificationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsAsyncPager", - "shortName": "list_notification_configs" - }, - "description": "Sample for ListNotificationConfigs", - "file": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_notification_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListNotificationConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListNotificationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsPager", - "shortName": "list_notification_configs" - }, - "description": "Sample for ListNotificationConfigs", - "file": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesAsyncPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v1p1beta1_generated_security_center_list_sources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1p1beta1_generated_security_center_list_sources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.run_asset_discovery", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.RunAssetDiscovery", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "RunAssetDiscovery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "run_asset_discovery" - }, - "description": "Sample for RunAssetDiscovery", - "file": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.run_asset_discovery", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.RunAssetDiscovery", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "RunAssetDiscovery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "run_asset_discovery" - }, - "description": "Sample for RunAssetDiscovery", - "file": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v1p1beta1.types.Finding.State" - }, - { - "name": "start_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v1p1beta1.types.Finding.State" - }, - { - "name": "start_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" - }, - { - "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.securitycenter_v1p1beta1.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v1p1beta1_generated_security_center_update_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1p1beta1_generated_security_center_update_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" - }, - { - "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.securitycenter_v1p1beta1.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" - }, - { - "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.securitycenter_v1p1beta1.types.NotificationConfig", - "shortName": "update_notification_config" - }, - "description": "Sample for UpdateNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" - }, - { - "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.securitycenter_v1p1beta1.types.NotificationConfig", - "shortName": "update_notification_config" - }, - "description": "Sample for UpdateNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest" - }, - { - "name": "organization_settings", - "type": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings", - "shortName": "update_organization_settings" - }, - "description": "Sample for UpdateOrganizationSettings", - "file": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest" - }, - { - "name": "organization_settings", - "type": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings", - "shortName": "update_organization_settings" - }, - "description": "Sample for UpdateOrganizationSettings", - "file": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v1p1beta1.types.SecurityMarks" - }, - { - "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.securitycenter_v1p1beta1.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v1p1beta1.types.SecurityMarks" - }, - { - "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.securitycenter_v1p1beta1.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1p1beta1.types.Source" - }, - { - "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.securitycenter_v1p1beta1.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v1p1beta1_generated_security_center_update_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1p1beta1_generated_security_center_update_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1p1beta1.types.Source" - }, - { - "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.securitycenter_v1p1beta1.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v1p1beta1_generated_security_center_update_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1p1beta1_generated_security_center_update_source_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py deleted file mode 100644 index 51a5e411dcfb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py +++ /dev/null @@ -1,198 +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 securitycenterCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_notification_config': ('parent', 'config_id', 'notification_config', ), - 'create_source': ('parent', 'source', ), - 'delete_notification_config': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_notification_config': ('name', ), - 'get_organization_settings': ('name', ), - 'get_source': ('name', ), - 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), - 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), - 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_notification_configs': ('parent', 'page_token', 'page_size', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'run_asset_discovery': ('parent', ), - 'set_finding_state': ('name', 'state', 'start_time', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_notification_config': ('notification_config', 'update_mask', ), - 'update_organization_settings': ('organization_settings', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), - 'update_source': ('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=securitycenterCallTransformer(), -): - """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 securitycenter 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-securitycenter/v1p1beta1/setup.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/setup.py deleted file mode 100644 index c4538ec101f3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/setup.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. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-securitycenter' - - -description = "Google Cloud Securitycenter API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/securitycenter/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", - "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", -] -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" - -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__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-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py deleted file mode 100644 index 8de42633a7ea..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py +++ /dev/null @@ -1,18405 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -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 - -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.securitycenter_v1p1beta1.services.security_center import SecurityCenterAsyncClient -from google.cloud.securitycenter_v1p1beta1.services.security_center import SecurityCenterClient -from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1p1beta1.services.security_center import transports -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1p1beta1.types import security_marks -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -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 duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None - assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert SecurityCenterClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SecurityCenterGrpcTransport, "grpc"), - (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - 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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -def test_security_center_client_get_transport_class(): - transport = SecurityCenterClient.get_transport_class() - available_transports = [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterRestTransport, - ] - assert transport in available_transports - - transport = SecurityCenterClient.get_transport_class("grpc") - assert transport == transports.SecurityCenterGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, 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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), -]) -def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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_security_center_client_client_options_from_dict(): - with mock.patch('google.cloud.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_create_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object - - request = {} - await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_create_source_async_from_dict(): - await test_create_source_async(request_type=dict) - - -def test_create_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.create_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - - -def test_create_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - response = client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -def test_create_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.create_finding] = mock_rpc - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object - - request = {} - await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_create_finding_async_from_dict(): - await test_create_finding_async(request_type=dict) - - -def test_create_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - arg = args[0].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - - -def test_create_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - arg = args[0].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateNotificationConfigRequest, - dict, -]) -def test_create_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_create_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateNotificationConfigRequest( - parent='parent_value', - config_id='config_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest( - parent='parent_value', - config_id='config_id_value', - ) - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_create_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_notification_config] = mock_object - - request = {} - await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_create_notification_config_async_from_dict(): - await test_create_notification_config_async(request_type=dict) - - -def test_create_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.create_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.create_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_notification_config( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - # Establish that the 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].config_id - mock_val = 'config_id_value' - assert arg == mock_val - arg = args[0].notification_config - mock_val = gcs_notification_config.NotificationConfig(name='name_value') - assert arg == mock_val - - -def test_create_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_notification_config( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - # Establish that 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].config_id - mock_val = 'config_id_value' - assert arg == mock_val - arg = args[0].notification_config - mock_val = gcs_notification_config.NotificationConfig(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_notification_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteNotificationConfigRequest, - dict, -]) -def test_delete_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteNotificationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest( - name='name_value', - ) - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_delete_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_notification_config] = mock_object - - request = {} - await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteNotificationConfigRequest() - 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_config_async_from_dict(): - await test_delete_notification_config_async(request_type=dict) - - -def test_delete_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = None - client.delete_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_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_notification_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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_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_notification_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_notification_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.GetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest( - resource='resource_value', - ) - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object - - request = {} - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_get_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetNotificationConfigRequest, - dict, -]) -def test_get_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_get_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetNotificationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest( - name='name_value', - ) - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_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_notification_config] = mock_rpc - request = {} - client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_get_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_notification_config] = mock_object - - request = {} - await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_get_notification_config_async_from_dict(): - await test_get_notification_config_async(request_type=dict) - - -def test_get_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = notification_config.NotificationConfig() - client.get_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - await client.get_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_notification_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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_notification_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_notification_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetOrganizationSettingsRequest, - dict, -]) -def test_get_organization_settings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_get_organization_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetOrganizationSettingsRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_organization_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest( - name='name_value', - ) - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_organization_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_organization_settings] = mock_rpc - request = {} - client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_organization_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_organization_settings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - -@pytest.mark.asyncio -async def test_get_organization_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_organization_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_organization_settings] = mock_object - - request = {} - await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_organization_settings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_get_organization_settings_async_from_dict(): - await test_get_organization_settings_async(request_type=dict) - - -def test_get_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = organization_settings.OrganizationSettings() - client.get_organization_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_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - await client.get_organization_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_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_organization_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_organization_settings_flattened_error(): - client = SecurityCenterClient( - credentials=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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_organization_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_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_get_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest( - name='name_value', - ) - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - -@pytest.mark.asyncio -async def test_get_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object - - request = {} - await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_get_source_async_from_dict(): - await test_get_source_async(request_type=dict) - - -def test_get_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = source.Source() - client.get_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_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_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_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_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupAssetsRequest, - dict, -]) -def test_group_assets(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_assets_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - -def test_group_assets_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupAssetsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_assets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_assets_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc - request = {} - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_group_assets_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - -@pytest.mark.asyncio -async def test_group_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_assets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_assets] = mock_object - - request = {} - await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_assets_async_from_dict(): - await test_group_assets_async(request_type=dict) - - -def test_group_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = securitycenter_service.GroupAssetsResponse() - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_group_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) - await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_group_assets_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_assets(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, securitycenter_service.GroupResult) - for i in results) -def test_group_assets_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_assets(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_group_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_assets(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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_assets(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", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - -@pytest.mark.asyncio -async def test_group_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_findings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object - - request = {} - await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_findings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_findings_async_from_dict(): - await test_group_findings_async(request_type=dict) - - -def test_group_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_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_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - await client.group_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_group_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that the 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - - -def test_group_findings_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - -@pytest.mark.asyncio -async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_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, securitycenter_service.GroupResult) - for i in results) -def test_group_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_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_group_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_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", [ - securitycenter_service.ListAssetsRequest, - dict, -]) -def test_list_assets(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_assets_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - -def test_list_assets_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListAssetsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_assets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_value', - page_token='page_token_value', - ) - -def test_list_assets_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc - request = {} - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_assets_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - -@pytest.mark.asyncio -async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_assets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object - - request = {} - await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_assets_async_from_dict(): - await test_list_assets_async(request_type=dict) - - -def test_list_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = securitycenter_service.ListAssetsResponse() - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) - await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_assets_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_assets( - 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_assets_flattened_error(): - client = SecurityCenterClient( - credentials=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_assets( - securitycenter_service.ListAssetsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_assets_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_assets( - 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_assets_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_assets( - securitycenter_service.ListAssetsRequest(), - parent='parent_value', - ) - - -def test_list_assets_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) -def test_list_assets_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_assets(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_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - 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_assets(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", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -def test_list_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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] == securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - -@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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object - - request = {} - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -@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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( - 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 = securitycenter_service.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', - ) - - # Establish that the 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_findings_flattened_error(): - client = SecurityCenterClient( - credentials=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( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_findings_flattened_async(): - client = SecurityCenterAsyncClient( - 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 = securitycenter_service.ListFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.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', - ) - - # Establish that 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_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_findings( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - - -def test_list_findings_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in results) -def test_list_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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 = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_findings_async_pages(): - client = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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", [ - securitycenter_service.ListNotificationConfigsRequest, - dict, -]) -def test_list_notification_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListNotificationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_notification_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListNotificationConfigsRequest( - 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_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notification_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_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_notification_configs] = mock_rpc - request = {} - client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_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_notification_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - -@pytest.mark.asyncio -async def test_list_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_notification_configs] = mock_object - - request = {} - await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_notification_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListNotificationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_from_dict(): - await test_list_notification_configs_async(request_type=dict) - - -def test_list_notification_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - 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_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - client.list_notification_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_notification_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - 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_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - await client.list_notification_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_notification_configs_flattened(): - client = SecurityCenterClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_notification_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_notification_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_notification_configs_flattened_async(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_notification_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_notification_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_notification_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - 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_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, notification_config.NotificationConfig) - for i in results) -def test_list_notification_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_notification_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_notification_configs_async_pager(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_notification_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, notification_config.NotificationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_pages(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - 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_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", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_sources_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListSourcesRequest( - 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_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - -@pytest.mark.asyncio -async def test_list_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_sources in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object - - request = {} - await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_sources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_sources_async_from_dict(): - await test_list_sources_async(request_type=dict) - - -def test_list_sources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = securitycenter_service.ListSourcesResponse() - client.list_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_sources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - await client.list_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_sources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_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_sources_flattened_error(): - client = SecurityCenterClient( - credentials=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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_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_sources_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_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, source.Source) - for i in results) -def test_list_sources_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = list(client.list_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_sources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_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, source.Source) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - 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_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", [ - securitycenter_service.RunAssetDiscoveryRequest, - dict, -]) -def test_run_asset_discovery(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.RunAssetDiscoveryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_run_asset_discovery_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - -def test_run_asset_discovery_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.RunAssetDiscoveryRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.run_asset_discovery(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest( - parent='parent_value', - ) - -def test_run_asset_discovery_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.run_asset_discovery in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc - request = {} - client.run_asset_discovery(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.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_run_asset_discovery_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - -@pytest.mark.asyncio -async def test_run_asset_discovery_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.run_asset_discovery in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.run_asset_discovery] = mock_object - - request = {} - await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.RunAssetDiscoveryRequest() - 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_run_asset_discovery_async_from_dict(): - await test_run_asset_discovery_async(request_type=dict) - - -def test_run_asset_discovery_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_run_asset_discovery_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_run_asset_discovery_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery( - 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_run_asset_discovery_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_run_asset_discovery_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery( - 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_run_asset_discovery_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - response = client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -def test_set_finding_state_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - -@pytest.mark.asyncio -async def test_set_finding_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object - - request = {} - await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_finding_state(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_set_finding_state_async_from_dict(): - await test_set_finding_state_async(request_type=dict) - - -def test_set_finding_state_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = finding.Finding() - client.set_finding_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_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_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_set_finding_state_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - - -def test_set_finding_state_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.SetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest( - resource='resource_value', - ) - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object - - request = {} - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = SecurityCenterClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.TestIamPermissionsRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( - resource='resource_value', - ) - -def test_test_iam_permissions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object - - request = {} - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - response = client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -def test_update_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateFindingRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.update_finding] = mock_rpc - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object - - request = {} - await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_finding_async_from_dict(): - await test_update_finding_async(request_type=dict) - - -def test_update_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -def test_update_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_finding( - finding=gcs_finding.Finding(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].finding - mock_val = gcs_finding.Finding(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_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_finding( - finding=gcs_finding.Finding(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].finding - mock_val = gcs_finding.Finding(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_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateNotificationConfigRequest, - dict, -]) -def test_update_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_update_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateNotificationConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest( - ) - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_update_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_notification_config] = mock_object - - request = {} - await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_update_notification_config_async_from_dict(): - await test_update_notification_config_async(request_type=dict) - - -def test_update_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.update_notification_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', - 'notification_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.update_notification_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', - 'notification_config.name=name_value', - ) in kw['metadata'] - - -def test_update_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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].notification_config - mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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].notification_config - mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_notification_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateOrganizationSettingsRequest, - dict, -]) -def test_update_organization_settings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_update_organization_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateOrganizationSettingsRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_organization_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest( - ) - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_organization_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_organization_settings] = mock_rpc - request = {} - client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_organization_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_organization_settings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - -@pytest.mark.asyncio -async def test_update_organization_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_organization_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_organization_settings] = mock_object - - request = {} - await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_organization_settings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_update_organization_settings_async_from_dict(): - await test_update_organization_settings_async(request_type=dict) - - -def test_update_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = gcs_organization_settings.OrganizationSettings() - client.update_organization_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', - 'organization_settings.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - await client.update_organization_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', - 'organization_settings.name=name_value', - ) in kw['metadata'] - - -def test_update_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].organization_settings - mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') - assert arg == mock_val - - -def test_update_organization_settings_flattened_error(): - client = SecurityCenterClient( - credentials=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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].organization_settings - mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSourceRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object - - request = {} - await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_source_async_from_dict(): - await test_update_source_async(request_type=dict) - - -def test_update_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -def test_update_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_source( - source=gcs_source.Source(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].source - mock_val = gcs_source.Source(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_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_source( - source=gcs_source.Source(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].source - mock_val = gcs_source.Source(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_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - response = client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_security_marks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - -def test_update_security_marks_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSecurityMarksRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( - ) - -def test_update_security_marks_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish that a new wrapper 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_security_marks_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - -@pytest.mark.asyncio -async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_marks in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object - - request = {} - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_security_marks(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_security_marks_async_from_dict(): - await test_update_security_marks_async(request_type=dict) - - -def test_update_security_marks_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -def test_update_security_marks_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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].security_marks - mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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].security_marks - mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.CreateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_source(request) - - -def test_create_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1p1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_create_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -def test_create_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request_init["finding"] = {'name': 'name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.create_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.create_finding] = mock_rpc - - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["finding_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 "findingId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "findingId" in jsonified_request - assert jsonified_request["findingId"] == request_init["finding_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["findingId"] = 'finding_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request - assert jsonified_request["findingId"] == 'finding_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.create_finding(request) - - expected_params = [ - ( - "findingId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.CreateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_finding(request) - - -def test_create_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(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 = gcs_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.create_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/v1p1beta1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) - - -def test_create_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_create_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateNotificationConfigRequest, - dict, -]) -def test_create_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["notification_config"] = {'name': 'name_value', 'description': 'description_value', 'event_type': 1, 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.CreateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): - del request_init["notification_config"][field][i][subfield] - else: - del request_init["notification_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 = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.CreateNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["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 "configId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "configId" in jsonified_request - assert jsonified_request["configId"] == request_init["config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["configId"] = 'config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("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 "configId" in jsonified_request - assert jsonified_request["configId"] == 'config_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ( - "configId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("configId", )) & set(("parent", "configId", "notificationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateNotificationConfigRequest.pb(securitycenter_service.CreateNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) - - request = securitycenter_service.CreateNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_notification_config.NotificationConfig() - - client.create_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_notification_config(request) - - -def test_create_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/v1p1beta1/{parent=organizations/*}/notificationConfigs" % client.transport._host, args[1]) - - -def test_create_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - -def test_create_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteNotificationConfigRequest, - dict, -]) -def test_delete_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/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 = 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_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.DeleteNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_notification_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteNotificationConfigRequest.pb(securitycenter_service.DeleteNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_notification_config(request) - - -def test_delete_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/notificationConfigs/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_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/v1p1beta1/{name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -def test_delete_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.get_iam_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/v1p1beta1/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetNotificationConfigRequest, - dict, -]) -def test_get_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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_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_notification_config] = mock_rpc - - request = {} - client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.GetNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetNotificationConfigRequest.pb(securitycenter_service.GetNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = notification_config.NotificationConfig.to_json(notification_config.NotificationConfig()) - - request = securitycenter_service.GetNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = notification_config.NotificationConfig() - - client.get_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_notification_config(request) - - -def test_get_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig.pb(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_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/v1p1beta1/{name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_get_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -def test_get_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetOrganizationSettingsRequest, - dict, -]) -def test_get_organization_settings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/organizationSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_organization_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_organization_settings] = mock_rpc - - request = {} - client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.GetOrganizationSettingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_organization_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_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_organization_settings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_organization_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_organization_settings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_organization_settings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_organization_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetOrganizationSettingsRequest.pb(securitycenter_service.GetOrganizationSettingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = organization_settings.OrganizationSettings.to_json(organization_settings.OrganizationSettings()) - - request = securitycenter_service.GetOrganizationSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = organization_settings.OrganizationSettings() - - client.get_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/organizationSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_organization_settings(request) - - -def test_get_organization_settings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/organizationSettings'} - - # get truthy value for each flattened field - mock_args = dict( - 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 = organization_settings.OrganizationSettings.pb(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_organization_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/v1p1beta1/{name=organizations/*/organizationSettings}" % client.transport._host, args[1]) - - -def test_get_organization_settings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -def test_get_organization_settings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/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 = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = source.Source.to_json(source.Source()) - - request = securitycenter_service.GetSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = source.Source() - - client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_source(request) - - -def test_get_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v1p1beta1/{name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_get_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -def test_get_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupAssetsRequest, - dict, -]) -def test_group_assets_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_group_assets_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc - - request = {} - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_group_assets_rest_required_fields(request_type=securitycenter_service.GroupAssetsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupAssetsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_assets_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_assets_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_assets") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupAssetsRequest.pb(securitycenter_service.GroupAssetsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupAssetsResponse.to_json(securitycenter_service.GroupAssetsResponse()) - - request = securitycenter_service.GroupAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupAssetsResponse() - - client.group_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_assets(request) - - -def test_group_assets_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupAssetsResponse.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': 'organizations/sample1'} - - pager = client.group_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_findings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_findings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_findings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) - - request = securitycenter_service.GroupFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupFindingsResponse() - - client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_findings(request) - - -def test_group_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - group_by='group_by_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v1p1beta1/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) - - -def test_group_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} - - pager = client.group_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_findings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListAssetsRequest, - dict, -]) -def test_list_assets_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListAssetsResponse.pb(return_value) - 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_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_list_assets_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc - - request = {} - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_assets(request) - - # Establish 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_assets_rest_required_fields(request_type=securitycenter_service.ListAssetsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_assets._get_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_assets._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) - jsonified_request.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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAssetsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListAssetsResponse.pb(return_value) - 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_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_assets_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_assets_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_assets") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListAssetsRequest.pb(securitycenter_service.ListAssetsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListAssetsResponse.to_json(securitycenter_service.ListAssetsResponse()) - - request = securitycenter_service.ListAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListAssetsResponse() - - client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_assets(request) - - -def test_list_assets_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAssetsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse.pb(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_assets(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1p1beta1/{parent=organizations/*}/assets" % client.transport._host, args[1]) - - -def test_list_assets_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_assets( - securitycenter_service.ListAssetsRequest(), - parent='parent_value', - ) - - -def test_list_assets_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListAssetsResponse.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': 'organizations/sample1'} - - pager = client.list_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) - - pages = list(client.list_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.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' - assert response.total_size == 1086 - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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=securitycenter_service.ListFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) - jsonified_request.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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.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 = securitycenter_service.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 = [ - ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) - - request = securitycenter_service.ListFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListFindingsResponse() - - client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_findings(request) - - -def test_list_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.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/v1p1beta1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) - - -def test_list_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - - -def test_list_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} - - pager = client.list_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) - 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 - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListNotificationConfigsRequest, - dict, -]) -def test_list_notification_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) - 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_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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_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_notification_configs] = mock_rpc - - request = {} - client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_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_notification_configs_rest_required_fields(request_type=securitycenter_service.ListNotificationConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListNotificationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) - 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_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_notification_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_notification_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_notification_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_notification_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_notification_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListNotificationConfigsRequest.pb(securitycenter_service.ListNotificationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListNotificationConfigsResponse.to_json(securitycenter_service.ListNotificationConfigsResponse()) - - request = securitycenter_service.ListNotificationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListNotificationConfigsResponse() - - client.list_notification_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_notification_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_notification_configs(request) - - -def test_list_notification_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListNotificationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse.pb(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_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/v1p1beta1/{parent=organizations/*}/notificationConfigs" % client.transport._host, args[1]) - - -def test_list_notification_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListNotificationConfigsResponse.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': 'organizations/sample1'} - - pager = client.list_notification_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, notification_config.NotificationConfig) - for i in results) - - pages = list(client.list_notification_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_sources_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_sources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_sources_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) - - request = securitycenter_service.ListSourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListSourcesResponse() - - client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_sources(request) - - -def test_list_sources_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v1p1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_list_sources_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} - - pager = client.list_sources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, source.Source) - for i in results) - - pages = list(client.list_sources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.RunAssetDiscoveryRequest, - dict, -]) -def test_run_asset_discovery_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') - - # 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 - response = client.run_asset_discovery(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_run_asset_discovery_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.run_asset_discovery in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc - - request = {} - client.run_asset_discovery(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.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_run_asset_discovery_rest_required_fields(request_type=securitycenter_service.RunAssetDiscoveryRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_asset_discovery._get_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()).run_asset_discovery._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 = SecurityCenterClient( - 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.run_asset_discovery(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_run_asset_discovery_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.run_asset_discovery._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_run_asset_discovery_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_run_asset_discovery") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_run_asset_discovery") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.RunAssetDiscoveryRequest.pb(securitycenter_service.RunAssetDiscoveryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = securitycenter_service.RunAssetDiscoveryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.run_asset_discovery(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_run_asset_discovery_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.run_asset_discovery(request) - - -def test_run_asset_discovery_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.run_asset_discovery(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1p1beta1/{parent=organizations/*}/assets:runDiscovery" % client.transport._host, args[1]) - - -def test_run_asset_discovery_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -def test_run_asset_discovery_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - - # 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 - response = client.set_finding_state(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( - 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': "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 = 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.set_finding_state(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_finding_state_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_finding_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "state", "startTime", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_finding_state_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = finding.Finding.to_json(finding.Finding()) - - request = securitycenter_service.SetFindingStateRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_finding_state(request) - - -def test_set_finding_state_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - mock_args.update(sample_request) - - # 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.set_finding_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/v1p1beta1/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) - - -def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -def test_set_finding_state_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.set_iam_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/v1p1beta1/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # 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 - response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_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.test_iam_permissions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1p1beta1/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.update_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.update_finding] = mock_rpc - - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_finding._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_finding._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.update_finding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.UpdateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_finding(request) - - -def test_update_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - finding=gcs_finding.Finding(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 = gcs_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.update_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/v1p1beta1/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) - - -def test_update_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateNotificationConfigRequest, - dict, -]) -def test_update_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} - request_init["notification_config"] = {'name': 'organizations/sample1/notificationConfigs/sample2', 'description': 'description_value', 'event_type': 1, 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.UpdateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): - del request_init["notification_config"][field][i][subfield] - else: - del request_init["notification_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 = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.UpdateNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("notificationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateNotificationConfigRequest.pb(securitycenter_service.UpdateNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) - - request = securitycenter_service.UpdateNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_notification_config.NotificationConfig() - - client.update_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_notification_config(request) - - -def test_update_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/v1p1beta1/{notification_config.name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_update_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateOrganizationSettingsRequest, - dict, -]) -def test_update_organization_settings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - request_init["organization_settings"] = {'name': 'organizations/sample1/organizationSettings', 'enable_asset_discovery': True, 'asset_discovery_config': {'project_ids': ['project_ids_value1', 'project_ids_value2'], 'inclusion_mode': 1, 'folder_ids': ['folder_ids_value1', 'folder_ids_value2']}} - # The version of a generated dependency at test runtime may differ from the version used 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 = securitycenter_service.UpdateOrganizationSettingsRequest.meta.fields["organization_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["organization_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["organization_settings"][field])): - del request_init["organization_settings"][field][i][subfield] - else: - del request_init["organization_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 = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_organization_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_organization_settings] = mock_rpc - - request = {} - client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_organization_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_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_organization_settings.OrganizationSettings() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_organization_settings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_organization_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("organizationSettings", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_organization_settings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_organization_settings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_organization_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateOrganizationSettingsRequest.pb(securitycenter_service.UpdateOrganizationSettingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_organization_settings.OrganizationSettings.to_json(gcs_organization_settings.OrganizationSettings()) - - request = securitycenter_service.UpdateOrganizationSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_organization_settings.OrganizationSettings() - - client.update_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_organization_settings(request) - - -def test_update_organization_settings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_organization_settings.OrganizationSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - - # get truthy value for each flattened field - mock_args = dict( - organization_settings=gcs_organization_settings.OrganizationSettings(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 = gcs_organization_settings.OrganizationSettings.pb(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_organization_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/v1p1beta1/{organization_settings.name=organizations/*/organizationSettings}" % client.transport._host, args[1]) - - -def test_update_organization_settings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -def test_update_organization_settings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.UpdateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_source(request) - - -def test_update_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1p1beta1/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_update_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - request_init["security_marks"] = {'name': 'organizations/sample1/assets/sample2/securityMarks', 'marks': {}, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] - - 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["security_marks"].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["security_marks"][field])): - del request_init["security_marks"][field][i][subfield] - else: - del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - -def test_update_security_marks_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_security_marks._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_security_marks._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("start_time", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_security_marks_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_security_marks._get_unset_required_fields({}) - assert set(unset_fields) == (set(("startTime", "updateMask", )) & set(("securityMarks", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_security_marks_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) - - request = securitycenter_service.UpdateSecurityMarksRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_security_marks.SecurityMarks() - - client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_security_marks(request) - - -def test_update_security_marks_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - - # get arguments that satisfy an http rule for this method - sample_request = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - - # get truthy value for each flattened field - mock_args = dict( - security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1p1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}" % client.transport._host, args[1]) - - -def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_security_marks_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SecurityCenterClient( - 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 = SecurityCenterClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SecurityCenterClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SecurityCenterClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SecurityCenterGrpcTransport, - ) - -def test_security_center_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_security_center_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_source', - 'create_finding', - 'create_notification_config', - 'delete_notification_config', - 'get_iam_policy', - 'get_notification_config', - 'get_organization_settings', - 'get_source', - 'group_assets', - 'group_findings', - 'list_assets', - 'list_findings', - 'list_notification_configs', - 'list_sources', - 'run_asset_discovery', - 'set_finding_state', - 'set_iam_policy', - 'test_iam_permissions', - 'update_finding', - 'update_notification_config', - 'update_organization_settings', - 'update_source', - 'update_security_marks', - ) - 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_security_center_base_transport_with_credentials_file(): - # Instantiate the 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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - 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_security_center_base_transport_with_adc(): - # Test the default 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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport() - adc.assert_called_once() - - -def test_security_center_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) - SecurityCenterClient() - 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -def test_security_center_transport_auth_adc(transport_class): - # If 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, - ], -) -def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), - (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_security_center_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host 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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_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.SecurityCenterRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_security_center_rest_lro_client(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a 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 - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_no_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_with_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_security_center_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SecurityCenterClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SecurityCenterClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_source._session - session2 = client2.transport.create_source._session - assert session1 != session2 - session1 = client1.transport.create_finding._session - session2 = client2.transport.create_finding._session - assert session1 != session2 - session1 = client1.transport.create_notification_config._session - session2 = client2.transport.create_notification_config._session - assert session1 != session2 - session1 = client1.transport.delete_notification_config._session - session2 = client2.transport.delete_notification_config._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.get_notification_config._session - session2 = client2.transport.get_notification_config._session - assert session1 != session2 - session1 = client1.transport.get_organization_settings._session - session2 = client2.transport.get_organization_settings._session - assert session1 != session2 - session1 = client1.transport.get_source._session - session2 = client2.transport.get_source._session - assert session1 != session2 - session1 = client1.transport.group_assets._session - session2 = client2.transport.group_assets._session - assert session1 != session2 - session1 = client1.transport.group_findings._session - session2 = client2.transport.group_findings._session - assert session1 != session2 - session1 = client1.transport.list_assets._session - session2 = client2.transport.list_assets._session - assert session1 != session2 - session1 = client1.transport.list_findings._session - session2 = client2.transport.list_findings._session - assert session1 != session2 - session1 = client1.transport.list_notification_configs._session - session2 = client2.transport.list_notification_configs._session - assert session1 != session2 - session1 = client1.transport.list_sources._session - session2 = client2.transport.list_sources._session - assert session1 != session2 - session1 = client1.transport.run_asset_discovery._session - session2 = client2.transport.run_asset_discovery._session - assert session1 != session2 - session1 = client1.transport.set_finding_state._session - session2 = client2.transport.set_finding_state._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 - session1 = client1.transport.update_finding._session - session2 = client2.transport.update_finding._session - assert session1 != session2 - session1 = client1.transport.update_notification_config._session - session2 = client2.transport.update_notification_config._session - assert session1 != session2 - session1 = client1.transport.update_organization_settings._session - session2 = client2.transport.update_organization_settings._session - assert session1 != session2 - session1 = client1.transport.update_source._session - session2 = client2.transport.update_source._session - assert session1 != session2 - session1 = client1.transport.update_security_marks._session - session2 = client2.transport.update_security_marks._session - assert session1 != session2 -def test_security_center_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcTransport( - 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_security_center_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcAsyncIOTransport( - 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(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_security_center_grpc_lro_client(): - client = SecurityCenterClient( - 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_security_center_grpc_lro_async_client(): - client = SecurityCenterAsyncClient( - 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_asset_path(): - organization = "squid" - asset = "clam" - expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.asset_path(organization, asset) - assert expected == actual - - -def test_parse_asset_path(): - expected = { - "organization": "whelk", - "asset": "octopus", - } - path = SecurityCenterClient.asset_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_asset_path(path) - assert expected == actual - -def test_finding_path(): - organization = "oyster" - source = "nudibranch" - finding = "cuttlefish" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - actual = SecurityCenterClient.finding_path(organization, source, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "organization": "mussel", - "source": "winkle", - "finding": "nautilus", - } - path = SecurityCenterClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_finding_path(path) - assert expected == actual - -def test_notification_config_path(): - organization = "scallop" - notification_config = "abalone" - expected = "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) - actual = SecurityCenterClient.notification_config_path(organization, notification_config) - assert expected == actual - - -def test_parse_notification_config_path(): - expected = { - "organization": "squid", - "notification_config": "clam", - } - path = SecurityCenterClient.notification_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_notification_config_path(path) - assert expected == actual - -def test_organization_settings_path(): - organization = "whelk" - expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) - actual = SecurityCenterClient.organization_settings_path(organization) - assert expected == actual - - -def test_parse_organization_settings_path(): - expected = { - "organization": "octopus", - } - path = SecurityCenterClient.organization_settings_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_organization_settings_path(path) - assert expected == actual - -def test_security_marks_path(): - organization = "oyster" - asset = "nudibranch" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.security_marks_path(organization, asset) - assert expected == actual - - -def test_parse_security_marks_path(): - expected = { - "organization": "cuttlefish", - "asset": "mussel", - } - path = SecurityCenterClient.security_marks_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_security_marks_path(path) - assert expected == actual - -def test_source_path(): - organization = "winkle" - source = "nautilus" - expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - actual = SecurityCenterClient.source_path(organization, source) - assert expected == actual - - -def test_parse_source_path(): - expected = { - "organization": "scallop", - "source": "abalone", - } - path = SecurityCenterClient.source_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_source_path(path) - assert expected == actual - -def test_topic_path(): - project = "squid" - topic = "clam" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = SecurityCenterClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "whelk", - "topic": "octopus", - } - path = SecurityCenterClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_topic_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SecurityCenterClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = SecurityCenterClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = SecurityCenterClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = SecurityCenterClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SecurityCenterClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = SecurityCenterClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = SecurityCenterClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = SecurityCenterClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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 = SecurityCenterClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = SecurityCenterClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - transport_class = SecurityCenterClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), -]) -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-securitycenter/v2/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v2/.coveragerc deleted file mode 100644 index 45cb273f8f7c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/securitycenter/__init__.py - google/cloud/securitycenter/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-securitycenter/v2/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v2/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v2/MANIFEST.in deleted file mode 100644 index 7d0a7010fae0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/securitycenter *.py -recursive-include google/cloud/securitycenter_v2 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/README.rst b/owl-bot-staging/google-cloud-securitycenter/v2/README.rst deleted file mode 100644 index f8c63f4cb48a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v2/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v2/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v2/docs/conf.py deleted file mode 100644 index 8e92d2319721..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter 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-securitycenter" -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-securitycenter-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-securitycenter.tex", - u"google-cloud-securitycenter 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-securitycenter", - u"Google Cloud Securitycenter 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-securitycenter", - u"google-cloud-securitycenter Documentation", - author, - "google-cloud-securitycenter", - "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v2/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/index.rst deleted file mode 100644 index af3ca0f134f0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - securitycenter_v2/services - securitycenter_v2/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst deleted file mode 100644 index 6b9d3b9b1795..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst +++ /dev/null @@ -1,10 +0,0 @@ -SecurityCenter --------------------------------- - -.. automodule:: google.cloud.securitycenter_v2.services.security_center - :members: - :inherited-members: - -.. automodule:: google.cloud.securitycenter_v2.services.security_center.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst deleted file mode 100644 index adb8a6096090..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Securitycenter v2 API -=============================================== -.. toctree:: - :maxdepth: 2 - - security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst deleted file mode 100644 index 3210d372fb24..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Securitycenter v2 API -============================================ - -.. automodule:: google.cloud.securitycenter_v2.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py deleted file mode 100644 index 121fb285646b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py +++ /dev/null @@ -1,257 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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.securitycenter import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.securitycenter_v2.services.security_center.client import SecurityCenterClient -from google.cloud.securitycenter_v2.services.security_center.async_client import SecurityCenterAsyncClient - -from google.cloud.securitycenter_v2.types.access import Access -from google.cloud.securitycenter_v2.types.access import Geolocation -from google.cloud.securitycenter_v2.types.access import ServiceAccountDelegationInfo -from google.cloud.securitycenter_v2.types.application import Application -from google.cloud.securitycenter_v2.types.attack_exposure import AttackExposure -from google.cloud.securitycenter_v2.types.attack_path import AttackPath -from google.cloud.securitycenter_v2.types.backup_disaster_recovery import BackupDisasterRecovery -from google.cloud.securitycenter_v2.types.bigquery_export import BigQueryExport -from google.cloud.securitycenter_v2.types.cloud_armor import AdaptiveProtection -from google.cloud.securitycenter_v2.types.cloud_armor import Attack -from google.cloud.securitycenter_v2.types.cloud_armor import CloudArmor -from google.cloud.securitycenter_v2.types.cloud_armor import Requests -from google.cloud.securitycenter_v2.types.cloud_armor import SecurityPolicy -from google.cloud.securitycenter_v2.types.cloud_dlp_data_profile import CloudDlpDataProfile -from google.cloud.securitycenter_v2.types.cloud_dlp_inspection import CloudDlpInspection -from google.cloud.securitycenter_v2.types.compliance import Compliance -from google.cloud.securitycenter_v2.types.connection import Connection -from google.cloud.securitycenter_v2.types.contact_details import Contact -from google.cloud.securitycenter_v2.types.contact_details import ContactDetails -from google.cloud.securitycenter_v2.types.container import Container -from google.cloud.securitycenter_v2.types.database import Database -from google.cloud.securitycenter_v2.types.exfiltration import ExfilResource -from google.cloud.securitycenter_v2.types.exfiltration import Exfiltration -from google.cloud.securitycenter_v2.types.external_system import ExternalSystem -from google.cloud.securitycenter_v2.types.file import File -from google.cloud.securitycenter_v2.types.finding import Finding -from google.cloud.securitycenter_v2.types.folder import Folder -from google.cloud.securitycenter_v2.types.group_membership import GroupMembership -from google.cloud.securitycenter_v2.types.iam_binding import IamBinding -from google.cloud.securitycenter_v2.types.indicator import Indicator -from google.cloud.securitycenter_v2.types.kernel_rootkit import KernelRootkit -from google.cloud.securitycenter_v2.types.kubernetes import Kubernetes -from google.cloud.securitycenter_v2.types.label import Label -from google.cloud.securitycenter_v2.types.load_balancer import LoadBalancer -from google.cloud.securitycenter_v2.types.log_entry import CloudLoggingEntry -from google.cloud.securitycenter_v2.types.log_entry import LogEntry -from google.cloud.securitycenter_v2.types.mitre_attack import MitreAttack -from google.cloud.securitycenter_v2.types.mute_config import MuteConfig -from google.cloud.securitycenter_v2.types.notebook import Notebook -from google.cloud.securitycenter_v2.types.notification_config import NotificationConfig -from google.cloud.securitycenter_v2.types.notification_message import NotificationMessage -from google.cloud.securitycenter_v2.types.org_policy import OrgPolicy -from google.cloud.securitycenter_v2.types.process import EnvironmentVariable -from google.cloud.securitycenter_v2.types.process import Process -from google.cloud.securitycenter_v2.types.resource import AwsMetadata -from google.cloud.securitycenter_v2.types.resource import AzureMetadata -from google.cloud.securitycenter_v2.types.resource import GcpMetadata -from google.cloud.securitycenter_v2.types.resource import Resource -from google.cloud.securitycenter_v2.types.resource import ResourcePath -from google.cloud.securitycenter_v2.types.resource import CloudProvider -from google.cloud.securitycenter_v2.types.resource_value_config import ResourceValueConfig -from google.cloud.securitycenter_v2.types.resource_value_config import ResourceValue -from google.cloud.securitycenter_v2.types.security_marks import SecurityMarks -from google.cloud.securitycenter_v2.types.security_posture import SecurityPosture -from google.cloud.securitycenter_v2.types.securitycenter_service import BatchCreateResourceValueConfigsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import BatchCreateResourceValueConfigsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import BulkMuteFindingsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import BulkMuteFindingsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import CreateBigQueryExportRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import CreateFindingRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import CreateMuteConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import CreateNotificationConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import CreateResourceValueConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import CreateSourceRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteBigQueryExportRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteMuteConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteNotificationConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteResourceValueConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetBigQueryExportRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetMuteConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetNotificationConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetResourceValueConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetSimulationRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetSourceRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetValuedResourceRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GroupFindingsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GroupFindingsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import GroupResult -from google.cloud.securitycenter_v2.types.securitycenter_service import ListAttackPathsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListAttackPathsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListBigQueryExportsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListBigQueryExportsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListFindingsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListFindingsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListMuteConfigsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListMuteConfigsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListNotificationConfigsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListNotificationConfigsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListResourceValueConfigsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListResourceValueConfigsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListSourcesRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListSourcesResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListValuedResourcesRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListValuedResourcesResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import SetFindingStateRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import SetMuteRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateBigQueryExportRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateExternalSystemRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateFindingRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateMuteConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateNotificationConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateResourceValueConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateSecurityMarksRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateSourceRequest -from google.cloud.securitycenter_v2.types.simulation import Simulation -from google.cloud.securitycenter_v2.types.source import Source -from google.cloud.securitycenter_v2.types.toxic_combination import ToxicCombination -from google.cloud.securitycenter_v2.types.valued_resource import ResourceValueConfigMetadata -from google.cloud.securitycenter_v2.types.valued_resource import ValuedResource -from google.cloud.securitycenter_v2.types.vulnerability import Cve -from google.cloud.securitycenter_v2.types.vulnerability import Cvssv3 -from google.cloud.securitycenter_v2.types.vulnerability import Package -from google.cloud.securitycenter_v2.types.vulnerability import Reference -from google.cloud.securitycenter_v2.types.vulnerability import SecurityBulletin -from google.cloud.securitycenter_v2.types.vulnerability import Vulnerability - -__all__ = ('SecurityCenterClient', - 'SecurityCenterAsyncClient', - 'Access', - 'Geolocation', - 'ServiceAccountDelegationInfo', - 'Application', - 'AttackExposure', - 'AttackPath', - 'BackupDisasterRecovery', - 'BigQueryExport', - 'AdaptiveProtection', - 'Attack', - 'CloudArmor', - 'Requests', - 'SecurityPolicy', - 'CloudDlpDataProfile', - 'CloudDlpInspection', - 'Compliance', - 'Connection', - 'Contact', - 'ContactDetails', - 'Container', - 'Database', - 'ExfilResource', - 'Exfiltration', - 'ExternalSystem', - 'File', - 'Finding', - 'Folder', - 'GroupMembership', - 'IamBinding', - 'Indicator', - 'KernelRootkit', - 'Kubernetes', - 'Label', - 'LoadBalancer', - 'CloudLoggingEntry', - 'LogEntry', - 'MitreAttack', - 'MuteConfig', - 'Notebook', - 'NotificationConfig', - 'NotificationMessage', - 'OrgPolicy', - 'EnvironmentVariable', - 'Process', - 'AwsMetadata', - 'AzureMetadata', - 'GcpMetadata', - 'Resource', - 'ResourcePath', - 'CloudProvider', - 'ResourceValueConfig', - 'ResourceValue', - 'SecurityMarks', - 'SecurityPosture', - 'BatchCreateResourceValueConfigsRequest', - 'BatchCreateResourceValueConfigsResponse', - 'BulkMuteFindingsRequest', - 'BulkMuteFindingsResponse', - 'CreateBigQueryExportRequest', - 'CreateFindingRequest', - 'CreateMuteConfigRequest', - 'CreateNotificationConfigRequest', - 'CreateResourceValueConfigRequest', - 'CreateSourceRequest', - 'DeleteBigQueryExportRequest', - 'DeleteMuteConfigRequest', - 'DeleteNotificationConfigRequest', - 'DeleteResourceValueConfigRequest', - 'GetBigQueryExportRequest', - 'GetMuteConfigRequest', - 'GetNotificationConfigRequest', - 'GetResourceValueConfigRequest', - 'GetSimulationRequest', - 'GetSourceRequest', - 'GetValuedResourceRequest', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAttackPathsRequest', - 'ListAttackPathsResponse', - 'ListBigQueryExportsRequest', - 'ListBigQueryExportsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListMuteConfigsRequest', - 'ListMuteConfigsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListResourceValueConfigsRequest', - 'ListResourceValueConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListValuedResourcesRequest', - 'ListValuedResourcesResponse', - 'SetFindingStateRequest', - 'SetMuteRequest', - 'UpdateBigQueryExportRequest', - 'UpdateExternalSystemRequest', - 'UpdateFindingRequest', - 'UpdateMuteConfigRequest', - 'UpdateNotificationConfigRequest', - 'UpdateResourceValueConfigRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Simulation', - 'Source', - 'ToxicCombination', - 'ResourceValueConfigMetadata', - 'ValuedResource', - 'Cve', - 'Cvssv3', - 'Package', - 'Reference', - 'SecurityBulletin', - 'Vulnerability', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/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-securitycenter/v2/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py deleted file mode 100644 index f27bfdd5500f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py +++ /dev/null @@ -1,258 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.securitycenter_v2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.security_center import SecurityCenterClient -from .services.security_center import SecurityCenterAsyncClient - -from .types.access import Access -from .types.access import Geolocation -from .types.access import ServiceAccountDelegationInfo -from .types.application import Application -from .types.attack_exposure import AttackExposure -from .types.attack_path import AttackPath -from .types.backup_disaster_recovery import BackupDisasterRecovery -from .types.bigquery_export import BigQueryExport -from .types.cloud_armor import AdaptiveProtection -from .types.cloud_armor import Attack -from .types.cloud_armor import CloudArmor -from .types.cloud_armor import Requests -from .types.cloud_armor import SecurityPolicy -from .types.cloud_dlp_data_profile import CloudDlpDataProfile -from .types.cloud_dlp_inspection import CloudDlpInspection -from .types.compliance import Compliance -from .types.connection import Connection -from .types.contact_details import Contact -from .types.contact_details import ContactDetails -from .types.container import Container -from .types.database import Database -from .types.exfiltration import ExfilResource -from .types.exfiltration import Exfiltration -from .types.external_system import ExternalSystem -from .types.file import File -from .types.finding import Finding -from .types.folder import Folder -from .types.group_membership import GroupMembership -from .types.iam_binding import IamBinding -from .types.indicator import Indicator -from .types.kernel_rootkit import KernelRootkit -from .types.kubernetes import Kubernetes -from .types.label import Label -from .types.load_balancer import LoadBalancer -from .types.log_entry import CloudLoggingEntry -from .types.log_entry import LogEntry -from .types.mitre_attack import MitreAttack -from .types.mute_config import MuteConfig -from .types.notebook import Notebook -from .types.notification_config import NotificationConfig -from .types.notification_message import NotificationMessage -from .types.org_policy import OrgPolicy -from .types.process import EnvironmentVariable -from .types.process import Process -from .types.resource import AwsMetadata -from .types.resource import AzureMetadata -from .types.resource import GcpMetadata -from .types.resource import Resource -from .types.resource import ResourcePath -from .types.resource import CloudProvider -from .types.resource_value_config import ResourceValueConfig -from .types.resource_value_config import ResourceValue -from .types.security_marks import SecurityMarks -from .types.security_posture import SecurityPosture -from .types.securitycenter_service import BatchCreateResourceValueConfigsRequest -from .types.securitycenter_service import BatchCreateResourceValueConfigsResponse -from .types.securitycenter_service import BulkMuteFindingsRequest -from .types.securitycenter_service import BulkMuteFindingsResponse -from .types.securitycenter_service import CreateBigQueryExportRequest -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateMuteConfigRequest -from .types.securitycenter_service import CreateNotificationConfigRequest -from .types.securitycenter_service import CreateResourceValueConfigRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import DeleteBigQueryExportRequest -from .types.securitycenter_service import DeleteMuteConfigRequest -from .types.securitycenter_service import DeleteNotificationConfigRequest -from .types.securitycenter_service import DeleteResourceValueConfigRequest -from .types.securitycenter_service import GetBigQueryExportRequest -from .types.securitycenter_service import GetMuteConfigRequest -from .types.securitycenter_service import GetNotificationConfigRequest -from .types.securitycenter_service import GetResourceValueConfigRequest -from .types.securitycenter_service import GetSimulationRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GetValuedResourceRequest -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAttackPathsRequest -from .types.securitycenter_service import ListAttackPathsResponse -from .types.securitycenter_service import ListBigQueryExportsRequest -from .types.securitycenter_service import ListBigQueryExportsResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListMuteConfigsRequest -from .types.securitycenter_service import ListMuteConfigsResponse -from .types.securitycenter_service import ListNotificationConfigsRequest -from .types.securitycenter_service import ListNotificationConfigsResponse -from .types.securitycenter_service import ListResourceValueConfigsRequest -from .types.securitycenter_service import ListResourceValueConfigsResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import ListValuedResourcesRequest -from .types.securitycenter_service import ListValuedResourcesResponse -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import SetMuteRequest -from .types.securitycenter_service import UpdateBigQueryExportRequest -from .types.securitycenter_service import UpdateExternalSystemRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateMuteConfigRequest -from .types.securitycenter_service import UpdateNotificationConfigRequest -from .types.securitycenter_service import UpdateResourceValueConfigRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.simulation import Simulation -from .types.source import Source -from .types.toxic_combination import ToxicCombination -from .types.valued_resource import ResourceValueConfigMetadata -from .types.valued_resource import ValuedResource -from .types.vulnerability import Cve -from .types.vulnerability import Cvssv3 -from .types.vulnerability import Package -from .types.vulnerability import Reference -from .types.vulnerability import SecurityBulletin -from .types.vulnerability import Vulnerability - -__all__ = ( - 'SecurityCenterAsyncClient', -'Access', -'AdaptiveProtection', -'Application', -'Attack', -'AttackExposure', -'AttackPath', -'AwsMetadata', -'AzureMetadata', -'BackupDisasterRecovery', -'BatchCreateResourceValueConfigsRequest', -'BatchCreateResourceValueConfigsResponse', -'BigQueryExport', -'BulkMuteFindingsRequest', -'BulkMuteFindingsResponse', -'CloudArmor', -'CloudDlpDataProfile', -'CloudDlpInspection', -'CloudLoggingEntry', -'CloudProvider', -'Compliance', -'Connection', -'Contact', -'ContactDetails', -'Container', -'CreateBigQueryExportRequest', -'CreateFindingRequest', -'CreateMuteConfigRequest', -'CreateNotificationConfigRequest', -'CreateResourceValueConfigRequest', -'CreateSourceRequest', -'Cve', -'Cvssv3', -'Database', -'DeleteBigQueryExportRequest', -'DeleteMuteConfigRequest', -'DeleteNotificationConfigRequest', -'DeleteResourceValueConfigRequest', -'EnvironmentVariable', -'ExfilResource', -'Exfiltration', -'ExternalSystem', -'File', -'Finding', -'Folder', -'GcpMetadata', -'Geolocation', -'GetBigQueryExportRequest', -'GetMuteConfigRequest', -'GetNotificationConfigRequest', -'GetResourceValueConfigRequest', -'GetSimulationRequest', -'GetSourceRequest', -'GetValuedResourceRequest', -'GroupFindingsRequest', -'GroupFindingsResponse', -'GroupMembership', -'GroupResult', -'IamBinding', -'Indicator', -'KernelRootkit', -'Kubernetes', -'Label', -'ListAttackPathsRequest', -'ListAttackPathsResponse', -'ListBigQueryExportsRequest', -'ListBigQueryExportsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListMuteConfigsRequest', -'ListMuteConfigsResponse', -'ListNotificationConfigsRequest', -'ListNotificationConfigsResponse', -'ListResourceValueConfigsRequest', -'ListResourceValueConfigsResponse', -'ListSourcesRequest', -'ListSourcesResponse', -'ListValuedResourcesRequest', -'ListValuedResourcesResponse', -'LoadBalancer', -'LogEntry', -'MitreAttack', -'MuteConfig', -'Notebook', -'NotificationConfig', -'NotificationMessage', -'OrgPolicy', -'Package', -'Process', -'Reference', -'Requests', -'Resource', -'ResourcePath', -'ResourceValue', -'ResourceValueConfig', -'ResourceValueConfigMetadata', -'SecurityBulletin', -'SecurityCenterClient', -'SecurityMarks', -'SecurityPolicy', -'SecurityPosture', -'ServiceAccountDelegationInfo', -'SetFindingStateRequest', -'SetMuteRequest', -'Simulation', -'Source', -'ToxicCombination', -'UpdateBigQueryExportRequest', -'UpdateExternalSystemRequest', -'UpdateFindingRequest', -'UpdateMuteConfigRequest', -'UpdateNotificationConfigRequest', -'UpdateResourceValueConfigRequest', -'UpdateSecurityMarksRequest', -'UpdateSourceRequest', -'ValuedResource', -'Vulnerability', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json deleted file mode 100644 index 517d51c03f32..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json +++ /dev/null @@ -1,628 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.securitycenter_v2", - "protoPackage": "google.cloud.securitycenter.v2", - "schema": "1.0", - "services": { - "SecurityCenter": { - "clients": { - "grpc": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "BatchCreateResourceValueConfigs": { - "methods": [ - "batch_create_resource_value_configs" - ] - }, - "BulkMuteFindings": { - "methods": [ - "bulk_mute_findings" - ] - }, - "CreateBigQueryExport": { - "methods": [ - "create_big_query_export" - ] - }, - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateMuteConfig": { - "methods": [ - "create_mute_config" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteBigQueryExport": { - "methods": [ - "delete_big_query_export" - ] - }, - "DeleteMuteConfig": { - "methods": [ - "delete_mute_config" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "DeleteResourceValueConfig": { - "methods": [ - "delete_resource_value_config" - ] - }, - "GetBigQueryExport": { - "methods": [ - "get_big_query_export" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetMuteConfig": { - "methods": [ - "get_mute_config" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetResourceValueConfig": { - "methods": [ - "get_resource_value_config" - ] - }, - "GetSimulation": { - "methods": [ - "get_simulation" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GetValuedResource": { - "methods": [ - "get_valued_resource" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAttackPaths": { - "methods": [ - "list_attack_paths" - ] - }, - "ListBigQueryExports": { - "methods": [ - "list_big_query_exports" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListMuteConfigs": { - "methods": [ - "list_mute_configs" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListResourceValueConfigs": { - "methods": [ - "list_resource_value_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "ListValuedResources": { - "methods": [ - "list_valued_resources" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "SetMute": { - "methods": [ - "set_mute" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateBigQueryExport": { - "methods": [ - "update_big_query_export" - ] - }, - "UpdateExternalSystem": { - "methods": [ - "update_external_system" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateMuteConfig": { - "methods": [ - "update_mute_config" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateResourceValueConfig": { - "methods": [ - "update_resource_value_config" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SecurityCenterAsyncClient", - "rpcs": { - "BatchCreateResourceValueConfigs": { - "methods": [ - "batch_create_resource_value_configs" - ] - }, - "BulkMuteFindings": { - "methods": [ - "bulk_mute_findings" - ] - }, - "CreateBigQueryExport": { - "methods": [ - "create_big_query_export" - ] - }, - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateMuteConfig": { - "methods": [ - "create_mute_config" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteBigQueryExport": { - "methods": [ - "delete_big_query_export" - ] - }, - "DeleteMuteConfig": { - "methods": [ - "delete_mute_config" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "DeleteResourceValueConfig": { - "methods": [ - "delete_resource_value_config" - ] - }, - "GetBigQueryExport": { - "methods": [ - "get_big_query_export" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetMuteConfig": { - "methods": [ - "get_mute_config" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetResourceValueConfig": { - "methods": [ - "get_resource_value_config" - ] - }, - "GetSimulation": { - "methods": [ - "get_simulation" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GetValuedResource": { - "methods": [ - "get_valued_resource" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAttackPaths": { - "methods": [ - "list_attack_paths" - ] - }, - "ListBigQueryExports": { - "methods": [ - "list_big_query_exports" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListMuteConfigs": { - "methods": [ - "list_mute_configs" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListResourceValueConfigs": { - "methods": [ - "list_resource_value_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "ListValuedResources": { - "methods": [ - "list_valued_resources" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "SetMute": { - "methods": [ - "set_mute" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateBigQueryExport": { - "methods": [ - "update_big_query_export" - ] - }, - "UpdateExternalSystem": { - "methods": [ - "update_external_system" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateMuteConfig": { - "methods": [ - "update_mute_config" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateResourceValueConfig": { - "methods": [ - "update_resource_value_config" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "rest": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "BatchCreateResourceValueConfigs": { - "methods": [ - "batch_create_resource_value_configs" - ] - }, - "BulkMuteFindings": { - "methods": [ - "bulk_mute_findings" - ] - }, - "CreateBigQueryExport": { - "methods": [ - "create_big_query_export" - ] - }, - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateMuteConfig": { - "methods": [ - "create_mute_config" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteBigQueryExport": { - "methods": [ - "delete_big_query_export" - ] - }, - "DeleteMuteConfig": { - "methods": [ - "delete_mute_config" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "DeleteResourceValueConfig": { - "methods": [ - "delete_resource_value_config" - ] - }, - "GetBigQueryExport": { - "methods": [ - "get_big_query_export" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetMuteConfig": { - "methods": [ - "get_mute_config" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetResourceValueConfig": { - "methods": [ - "get_resource_value_config" - ] - }, - "GetSimulation": { - "methods": [ - "get_simulation" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GetValuedResource": { - "methods": [ - "get_valued_resource" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAttackPaths": { - "methods": [ - "list_attack_paths" - ] - }, - "ListBigQueryExports": { - "methods": [ - "list_big_query_exports" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListMuteConfigs": { - "methods": [ - "list_mute_configs" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListResourceValueConfigs": { - "methods": [ - "list_resource_value_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "ListValuedResources": { - "methods": [ - "list_valued_resources" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "SetMute": { - "methods": [ - "set_mute" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateBigQueryExport": { - "methods": [ - "update_big_query_export" - ] - }, - "UpdateExternalSystem": { - "methods": [ - "update_external_system" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateMuteConfig": { - "methods": [ - "update_mute_config" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateResourceValueConfig": { - "methods": [ - "update_resource_value_config" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_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-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_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-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__init__.py deleted file mode 100644 index bffcff5da306..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - 'SecurityCenterClient', - 'SecurityCenterAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py deleted file mode 100644 index 2d6ff6d7cf55..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py +++ /dev/null @@ -1,5422 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.securitycenter_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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.securitycenter_v2.services.security_center import pagers -from google.cloud.securitycenter_v2.types import access -from google.cloud.securitycenter_v2.types import application -from google.cloud.securitycenter_v2.types import attack_exposure -from google.cloud.securitycenter_v2.types import attack_path -from google.cloud.securitycenter_v2.types import backup_disaster_recovery -from google.cloud.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import cloud_armor -from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile -from google.cloud.securitycenter_v2.types import cloud_dlp_inspection -from google.cloud.securitycenter_v2.types import compliance -from google.cloud.securitycenter_v2.types import connection -from google.cloud.securitycenter_v2.types import container -from google.cloud.securitycenter_v2.types import database -from google.cloud.securitycenter_v2.types import exfiltration -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import file -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import group_membership -from google.cloud.securitycenter_v2.types import iam_binding -from google.cloud.securitycenter_v2.types import indicator -from google.cloud.securitycenter_v2.types import kernel_rootkit -from google.cloud.securitycenter_v2.types import kubernetes -from google.cloud.securitycenter_v2.types import load_balancer -from google.cloud.securitycenter_v2.types import log_entry -from google.cloud.securitycenter_v2.types import mitre_attack -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notebook -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import org_policy -from google.cloud.securitycenter_v2.types import process -from google.cloud.securitycenter_v2.types import resource -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import security_posture -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import toxic_combination -from google.cloud.securitycenter_v2.types import valued_resource -from google.cloud.securitycenter_v2.types import vulnerability -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 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 SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V2 APIs for Security Center service.""" - - _client: SecurityCenterClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE - - attack_path_path = staticmethod(SecurityCenterClient.attack_path_path) - parse_attack_path_path = staticmethod(SecurityCenterClient.parse_attack_path_path) - big_query_export_path = staticmethod(SecurityCenterClient.big_query_export_path) - parse_big_query_export_path = staticmethod(SecurityCenterClient.parse_big_query_export_path) - dlp_job_path = staticmethod(SecurityCenterClient.dlp_job_path) - parse_dlp_job_path = staticmethod(SecurityCenterClient.parse_dlp_job_path) - external_system_path = staticmethod(SecurityCenterClient.external_system_path) - parse_external_system_path = staticmethod(SecurityCenterClient.parse_external_system_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) - parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) - mute_config_path = staticmethod(SecurityCenterClient.mute_config_path) - parse_mute_config_path = staticmethod(SecurityCenterClient.parse_mute_config_path) - notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) - parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) - policy_path = staticmethod(SecurityCenterClient.policy_path) - parse_policy_path = staticmethod(SecurityCenterClient.parse_policy_path) - resource_value_config_path = staticmethod(SecurityCenterClient.resource_value_config_path) - parse_resource_value_config_path = staticmethod(SecurityCenterClient.parse_resource_value_config_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) - simulation_path = staticmethod(SecurityCenterClient.simulation_path) - parse_simulation_path = staticmethod(SecurityCenterClient.parse_simulation_path) - source_path = staticmethod(SecurityCenterClient.source_path) - parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) - table_data_profile_path = staticmethod(SecurityCenterClient.table_data_profile_path) - parse_table_data_profile_path = staticmethod(SecurityCenterClient.parse_table_data_profile_path) - topic_path = staticmethod(SecurityCenterClient.topic_path) - parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) - valued_resource_path = staticmethod(SecurityCenterClient.valued_resource_path) - parse_valued_resource_path = staticmethod(SecurityCenterClient.parse_valued_resource_path) - common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) - parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) - common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) - parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) - parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) - parse_common_location_path = staticmethod(SecurityCenterClient.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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def batch_create_resource_value_configs(self, - request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - r"""Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - requests = securitycenter_v2.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - - request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest, dict]]): - The request object. Request message to create multiple - resource value configs - parent (:class:`str`): - Required. Resource name of the new - ResourceValueConfig's parent. The parent - field in the - CreateResourceValueConfigRequest - messages must either be empty or match - this field. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - requests (:class:`MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]`): - Required. The resource value configs - to be created. - - This corresponds to the ``requests`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse: - Response message for - BatchCreateResourceValueConfigs - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, requests]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): - request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if requests: - request.requests.extend(requests) - - # 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_resource_value_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, - ) - - # Done; return the response. - return response - - async def bulk_mute_findings(self, - request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), - ) -> operation_async.AsyncOperation: - r"""Kicks off an LRO to bulk mute findings for a parent - based on a filter. If no location is specified, findings - are muted in global. The parent can be either an - organization, folder, or project. The findings matched - by the filter will be muted after the LRO is done. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest, dict]]): - The request object. Request message for bulk findings - update. - Note: - - 1. If multiple bulk update requests - match the same resource, the order - in which they get executed is not - defined. - 2. Once a bulk operation is started, - there is no way to stop it. - parent (:class:`str`): - Required. The parent, at which bulk action needs to be - applied. If no location is specified, findings are - updated in global. The following list shows some - examples: - - - ``organizations/[organization_id]`` - - ``organizations/[organization_id]/locations/[location_id]`` - - ``folders/[folder_id]`` - - ``folders/[folder_id]/locations/[location_id]`` - - ``projects/[project_id]`` - - ``projects/[project_id]/locations/[location_id]`` - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v2.types.BulkMuteFindingsResponse` - The response to a BulkMute request. Contains the LRO - 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]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): - request = securitycenter_service.BulkMuteFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.bulk_mute_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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - securitycenter_service.BulkMuteFindingsResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - async def create_big_query_export(self, - request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, - *, - parent: Optional[str] = None, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - big_query_export_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Creates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_create_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = await client.create_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest, dict]]): - The request object. Request message for creating a - BigQuery export. - parent (:class:`str`): - Required. The name of the parent resource of the new - BigQuery export. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export (:class:`google.cloud.securitycenter_v2.types.BigQueryExport`): - Required. The BigQuery export being - created. - - This corresponds to the ``big_query_export`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``big_query_export_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.cloud.securitycenter_v2.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): - request = securitycenter_service.CreateBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if big_query_export is not None: - request.big_query_export = big_query_export - if big_query_export_id is not None: - request.big_query_export_id = big_query_export_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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - finding_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding in a location. The corresponding - source must exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_create_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.CreateFindingRequest, dict]]): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. The - following list shows some examples of the format: + - ``organizations/[organization_id]/sources/[source_id]`` - + - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`google.cloud.securitycenter_v2.types.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_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.cloud.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding, finding_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, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding is not None: - request.finding = finding - if finding_id is not None: - request.finding_id = finding_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_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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 create_mute_config(self, - request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - mute_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Creates a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_create_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = await client.create_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.CreateMuteConfigRequest, dict]]): - The request object. Request message for creating a mute - config. - parent (:class:`str`): - Required. Resource name of the new mute configs's - parent. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config (:class:`google.cloud.securitycenter_v2.types.MuteConfig`): - Required. The mute config being - created. - - This corresponds to the ``mute_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``mute_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.cloud.securitycenter_v2.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): - request = securitycenter_service.CreateMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if mute_config is not None: - request.mute_config = mute_config - if mute_config_id is not None: - request.mute_config_id = mute_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_mute_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 create_notification_config(self, - request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_create_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.create_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest, dict]]): - The request object. Request message for creating a - notification config. - parent (:class:`str`): - Required. Resource name of the new notification config's - parent. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (:class:`google.cloud.securitycenter_v2.types.NotificationConfig`): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (:class:`str`): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters and contain - alphanumeric characters, underscores, or - hyphens only. - - This corresponds to the ``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.cloud.securitycenter_v2.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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_config, 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, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if notification_config is not None: - request.notification_config = notification_config - if config_id is not None: - request.config_id = 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_notification_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 create_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v2 - - async def sample_create_source(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.CreateSourceRequest, dict]]): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be ``organizations/[organization_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`google.cloud.securitycenter_v2.types.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v2.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = 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_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 delete_big_query_export(self, - request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - await client.delete_big_query_export(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest, dict]]): - The request object. Request message for deleting a - BigQuery export. - name (:class:`str`): - Required. The name of the BigQuery export to delete. The - following list shows some examples of the format: - - - - - ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` - - - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` - - ``projects/{project}/locations/{location}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): - request = securitycenter_service.DeleteBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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 delete_mute_config(self, - request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. If no location is - specified, default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_delete_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_mute_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest, dict]]): - The request object. Request message for deleting a mute - config. If no location is specified, - default is global. - name (:class:`str`): - Required. Name of the mute config to delete. The - following list shows some examples of the format: - - - ``organizations/{organization}/muteConfigs/{config_id}`` - - - - ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` - - - ``folders/{folder}/muteConfigs/{config_id}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` - - ``projects/{project}/muteConfigs/{config_id}`` - - ``projects/{project}/locations/{location}/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): - request = securitycenter_service.DeleteMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_mute_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 delete_notification_config(self, - request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_delete_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest, dict]]): - The request object. Request message for deleting a - notification config. - name (:class:`str`): - Required. Name of the notification config to delete. The - following list shows some examples of the format: - - - - - ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` - + - ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 delete_resource_value_config(self, - request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_resource_value_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest, dict]]): - The request object. Request message to delete resource - value config - name (:class:`str`): - Required. Name of the - ResourceValueConfig 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. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): - request = securitycenter_service.DeleteResourceValueConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_resource_value_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_big_query_export(self, - request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Gets a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_get_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = await client.get_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetBigQueryExportRequest, dict]]): - The request object. Request message for retrieving a - BigQuery export. - name (:class:`str`): - Required. Name of the BigQuery export to retrieve. The - following list shows some examples of the format: - - - - - ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` - - - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` - - ``projects/{project}locations/{location}//bigQueryExports/{export_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.cloud.securitycenter_v2.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): - request = securitycenter_service.GetBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_simulation(self, - request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> simulation.Simulation: - r"""Get the simulation by name or the latest simulation - for the given organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_get_simulation(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_simulation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetSimulationRequest, dict]]): - The request object. Request message for getting - simulation. Simulation name can include - "latest" to retrieve the latest - simulation For example, - "organizations/123/simulations/latest". - name (:class:`str`): - Required. The organization name or simulation name of - this simulation - - Valid format: - ``organizations/{organization}/simulations/latest`` - ``organizations/{organization}/simulations/{simulation}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.Simulation: - Attack path simulation - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSimulationRequest): - request = securitycenter_service.GetSimulationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_simulation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_valued_resource(self, - request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> valued_resource.ValuedResource: - r"""Get the valued resource by 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 import securitycenter_v2 - - async def sample_get_valued_resource(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_valued_resource(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetValuedResourceRequest, dict]]): - The request object. Request message for getting a valued - resource. - name (:class:`str`): - Required. The name of this valued resource - - Valid format: - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v2.types.ValuedResource: - A resource that is determined to have - value to a user's system - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetValuedResourceRequest): - request = securitycenter_service.GetValuedResourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_valued_resource] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v2 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 get_mute_config(self, - request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> mute_config.MuteConfig: - r"""Gets a mute config. If no location is specified, - default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_get_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetMuteConfigRequest, dict]]): - The request object. Request message for retrieving a mute - config. If no location is specified, - default is global. - name (:class:`str`): - Required. Name of the mute config to retrieve. The - following list shows some examples of the format: - - - ``organizations/{organization}/muteConfigs/{config_id}`` - - - - ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` - - - ``folders/{folder}/muteConfigs/{config_id}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` - - ``projects/{project}/muteConfigs/{config_id}`` - - ``projects/{project}/locations/{location}/muteConfigs/{config_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.cloud.securitycenter_v2.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetMuteConfigRequest): - request = securitycenter_service.GetMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_mute_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 get_notification_config(self, - request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_get_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetNotificationConfigRequest, dict]]): - The request object. Request message for getting a - notification config. - name (:class:`str`): - Required. Name of the notification config to get. The - following list shows some examples of the format: - - - - - ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_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.cloud.securitycenter_v2.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 get_resource_value_config(self, - request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resource_value_config.ResourceValueConfig: - r"""Gets a ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest, dict]]): - The request object. Request message to get resource value - config - name (:class:`str`): - Required. Name of the resource value config to retrieve. - Its format is - organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v2.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): - request = securitycenter_service.GetResourceValueConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_resource_value_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 get_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v2 - - async def sample_get_source(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetSourceRequest, dict]]): - The request object. Request message for getting a source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v2.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties in a location. If no location is - specified, findings are assumed to be in global - - To group across all sources provide a ``-`` as the source id. - The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - - ``/v2/folders/{folder_id}/sources/-/findings`` - - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` - - ``/v2/projects/{project_id}/sources/-/findings`` - - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_group_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GroupFindingsRequest, dict]]): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. If no location - is specified, finding is assumed to be in global. The - following list shows some examples: - - - ``organizations/[organization_id]/sources/[source_id]`` - - - - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - - ``folders/[folder_id]/sources/[source_id]`` - - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` - - ``projects/[project_id]/sources/[source_id]`` - - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` - - To groupBy across all sources provide a source_id of - ``-``. The following list shows some examples: - - - ``organizations/{organization_id}/sources/-`` - - ``organizations/{organization_id}/sources/-/locations/[location_id]`` - - ``folders/{folder_id}/sources/-`` - - ``folders/{folder_id}/sources/-/locations/[location_id]`` - - ``projects/{project_id}/sources/-`` - - ``projects/{project_id}/sources/-/locations/[location_id]`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping. The string value should follow SQL - syntax: comma separated list of fields. For example: - "parent,resource_name". - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_attack_paths(self, - request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsAsyncPager: - r"""Lists the attack paths for a set of simulation - results or valued resources and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_attack_paths(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListAttackPathsRequest, dict]]): - The request object. Request message for listing the - attack paths for a given simulation or - valued resource. - parent (:class:`str`): - Required. Name of parent to list attack paths. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - - 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.securitycenter_v2.services.security_center.pagers.ListAttackPathsAsyncPager: - Response message for listing the - attack paths for a given simulation or - valued resource. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): - request = securitycenter_service.ListAttackPathsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_attack_paths] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListAttackPathsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_big_query_exports(self, - request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsAsyncPager: - r"""Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are 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 securitycenter_v2 - - async def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest, dict]]): - The request object. Request message for listing BigQuery - exports at a given scope e.g. - organization, folder or project. - parent (:class:`str`): - Required. The parent, which owns the collection of - BigQuery exports. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - 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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsAsyncPager: - Response message for listing BigQuery - exports. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): - request = securitycenter_service.ListBigQueryExportsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_big_query_exports] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListBigQueryExportsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings(self, - request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsAsyncPager: - r"""Lists an organization or source's findings. - - To list across all sources for a given location provide a ``-`` - as the source id. If no location is specified, finding are - assumed to be in global. The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListFindingsRequest( - parent="parent_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.securitycenter_v2.types.ListFindingsRequest, dict]]): - The request object. Request message for listing findings. - parent (:class:`str`): - Required. Name of the source the findings belong to. If - no location is specified, the default is global. The - following list shows some examples: - - - ``organizations/[organization_id]/sources/[source_id]`` - - - - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - - ``folders/[folder_id]/sources/[source_id]`` - - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` - - ``projects/[project_id]/sources/[source_id]`` - - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` - - To list across all sources provide a source_id of ``-``. - The following list shows some examples: - - - ``organizations/{organization_id}/sources/-`` - - ``organizations/{organization_id}/sources/-/locations/{location_id}`` - - ``folders/{folder_id}/sources/-`` - - ``folders/{folder_id}/sources/-locations/{location_id}`` - - ``projects/{projects_id}/sources/-`` - - ``projects/{projects_id}/sources/-/locations/{location_id}`` - - 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.securitycenter_v2.services.security_center.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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_mute_configs(self, - request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsAsyncPager: - r"""Lists mute configs. If no location is specified, - default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_mute_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListMuteConfigsRequest, dict]]): - The request object. Request message for listing mute - configs at a given scope e.g. - organization, folder or project. If no - location is specified, default is - global. - parent (:class:`str`): - Required. The parent, which owns the collection of mute - configs. Its format is - ``organizations/[organization_id]", "folders/[folder_id]``, - ``projects/[project_id]``, - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, - ``projects/[project_id]/locations/[location_id]``. - - 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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsAsyncPager: - Response message for listing mute - configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): - request = securitycenter_service.ListMuteConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_mute_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.ListMuteConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_notification_configs(self, - request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsAsyncPager: - r"""Lists notification configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_notification_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest, dict]]): - The request object. Request message for listing - notification configs. - parent (:class:`str`): - Required. The name of the parent in which to list the - notification configurations. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". - - 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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsAsyncPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListNotificationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_resource_value_configs(self, - request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsAsyncPager: - r"""Lists all ResourceValueConfigs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest, dict]]): - The request object. Request message to list resource - value configs of a parent - parent (:class:`str`): - Required. The parent, which owns the collection of - resource value configs. Its format is - ``organizations/[organization_id]`` - - 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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsAsyncPager: - Response message to list resource - value configs - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): - request = securitycenter_service.ListResourceValueConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_resource_value_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.ListResourceValueConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_sources(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListSourcesRequest, dict]]): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - 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.securitycenter_v2.services.security_center.pagers.ListSourcesAsyncPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_valued_resources(self, - request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesAsyncPager: - r"""Lists the valued resources for a set of simulation - results and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_valued_resources(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListValuedResourcesRequest, dict]]): - The request object. Request message for listing the - valued resources for a given simulation. - parent (:class:`str`): - Required. Name of parent to list exposed resources. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - - 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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesAsyncPager: - Response message for listing the - valued resources for a given simulation. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): - request = securitycenter_service.ListValuedResourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_valued_resources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListValuedResourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. If no location is - specified, finding is assumed to be in global - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_set_finding_state(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.SetFindingStateRequest, dict]]): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The `relative resource - name `__ - of the finding. If no location is specified, finding is - assumed to be in global. The following list shows some - examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`google.cloud.securitycenter_v2.types.Finding.State`): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v2 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 set_mute(self, - request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, - *, - name: Optional[str] = None, - mute: Optional[finding.Finding.Mute] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the mute state of a finding. If no location - is specified, finding is assumed to be in global - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_set_mute(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = await client.set_mute(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.SetMuteRequest, dict]]): - The request object. Request message for updating a - finding's mute status. - name (:class:`str`): - Required. The `relative resource - name `__ - of the finding. If no location is specified, finding is - assumed to be in global. The following list shows some - examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute (:class:`google.cloud.securitycenter_v2.types.Finding.Mute`): - Required. The desired state of the - Mute. - - This corresponds to the ``mute`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, mute]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetMuteRequest): - request = securitycenter_service.SetMuteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if mute is not None: - request.mute = mute - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.set_mute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v2 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 update_big_query_export(self, - request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, - *, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - update_mask: 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]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Updates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateBigQueryExportRequest( - ) - - # Make the request - response = await client.update_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest, dict]]): - The request object. Request message for updating a - BigQuery export. - big_query_export (:class:`google.cloud.securitycenter_v2.types.BigQueryExport`): - Required. The BigQuery export being - updated. - - This corresponds to the ``big_query_export`` 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. - If empty all mutable fields 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.cloud.securitycenter_v2.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): - request = securitycenter_service.UpdateBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if big_query_export is not None: - request.big_query_export = big_query_export - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("big_query_export.name", request.big_query_export.name), - )), - ) - - # Validate the universe domain. - self._client._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_external_system(self, - request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, - *, - external_system: Optional[gcs_external_system.ExternalSystem] = None, - update_mask: 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]] = (), - ) -> gcs_external_system.ExternalSystem: - r"""Updates external system. This is for a given finding. - If no location is specified, finding is assumed to be in - global - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_external_system(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateExternalSystemRequest( - ) - - # Make the request - response = await client.update_external_system(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest, dict]]): - The request object. Request message for updating a - ExternalSystem resource. - external_system (:class:`google.cloud.securitycenter_v2.types.ExternalSystem`): - Required. The external system - resource to update. - - This corresponds to the ``external_system`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the external system resource. - If empty all mutable fields 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.cloud.securitycenter_v2.types.ExternalSystem: - Representation of third party - SIEM/SOAR fields within SCC. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): - request = securitycenter_service.UpdateExternalSystemRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if external_system is not None: - request.external_system = external_system - 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_external_system] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("external_system.name", request.external_system.name), - )), - ) - - # Validate the universe domain. - self._client._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_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - update_mask: 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]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. If no location is - specified, finding is assumed to be in global. The - corresponding source must exist for a finding creation - to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateFindingRequest, dict]]): - The request object. Request message for updating or - creating a finding. - finding (:class:`google.cloud.securitycenter_v2.types.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a - finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing - source_properties. Individual source_properties can be - added/updated by using "source_properties." in the field - mask. - - 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.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - 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_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe domain. - self._client._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_mute_config(self, - request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, - *, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - update_mask: 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]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Updates a mute config. If no location is specified, - default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = await client.update_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest, dict]]): - The request object. Request message for updating a mute - config. - mute_config (:class:`google.cloud.securitycenter_v2.types.MuteConfig`): - Required. The mute config being - updated. - - This corresponds to the ``mute_config`` 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. - If empty all mutable fields 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.cloud.securitycenter_v2.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): - request = securitycenter_service.UpdateMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if mute_config is not None: - request.mute_config = mute_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_mute_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("mute_config.name", request.mute_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 update_notification_config(self, - request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, - *, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - update_mask: 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]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateNotificationConfigRequest( - ) - - # Make the request - response = await client.update_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest, dict]]): - The request object. Request message for updating a - notification config. - notification_config (:class:`google.cloud.securitycenter_v2.types.NotificationConfig`): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the notification config. - If empty all mutable fields 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.cloud.securitycenter_v2.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_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 update_resource_value_config(self, - request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, - *, - resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, - update_mask: 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]] = (), - ) -> gcs_resource_value_config.ResourceValueConfig: - r"""Updates an existing ResourceValueConfigs with new - rules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateResourceValueConfigRequest( - ) - - # Make the request - response = await client.update_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest, dict]]): - The request object. Request message to update resource - value config - resource_value_config (:class:`google.cloud.securitycenter_v2.types.ResourceValueConfig`): - Required. The resource value config - being updated. - - This corresponds to the ``resource_value_config`` 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. If empty all mutable - fields will be updated. - - To update nested fields, include the top level field in - the mask For example, to update - gcp_metadata.resource_type, include the "gcp_metadata" - field mask - - 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.securitycenter_v2.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): - request = securitycenter_service.UpdateResourceValueConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if resource_value_config is not None: - request.resource_value_config = resource_value_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_resource_value_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource_value_config.name", request.resource_value_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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - update_mask: 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]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. For Finding Security marks, - if no location is specified, finding is assumed to be in - global. Assets Security Marks can only be accessed - through global endpoint. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_security_marks(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest, dict]]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`google.cloud.securitycenter_v2.types.SecurityMarks`): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If - empty or set to "marks", all marks will be replaced. - Individual marks can be updated using - "marks.". - - 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.securitycenter_v2.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - 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_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe domain. - self._client._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_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - update_mask: 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]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v2 - - async def sample_update_source(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateSourceRequest, dict]]): - The request object. Request message for updating a - source. - source (:class:`google.cloud.securitycenter_v2.types.Source`): - Required. The source resource to - update. - - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the source resource. - If empty all mutable fields 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.cloud.securitycenter_v2.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = 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_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self) -> "SecurityCenterAsyncClient": - 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__ = ( - "SecurityCenterAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py deleted file mode 100644 index 550305f1c892..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py +++ /dev/null @@ -1,5948 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.securitycenter_v2.services.security_center import pagers -from google.cloud.securitycenter_v2.types import access -from google.cloud.securitycenter_v2.types import application -from google.cloud.securitycenter_v2.types import attack_exposure -from google.cloud.securitycenter_v2.types import attack_path -from google.cloud.securitycenter_v2.types import backup_disaster_recovery -from google.cloud.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import cloud_armor -from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile -from google.cloud.securitycenter_v2.types import cloud_dlp_inspection -from google.cloud.securitycenter_v2.types import compliance -from google.cloud.securitycenter_v2.types import connection -from google.cloud.securitycenter_v2.types import container -from google.cloud.securitycenter_v2.types import database -from google.cloud.securitycenter_v2.types import exfiltration -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import file -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import group_membership -from google.cloud.securitycenter_v2.types import iam_binding -from google.cloud.securitycenter_v2.types import indicator -from google.cloud.securitycenter_v2.types import kernel_rootkit -from google.cloud.securitycenter_v2.types import kubernetes -from google.cloud.securitycenter_v2.types import load_balancer -from google.cloud.securitycenter_v2.types import log_entry -from google.cloud.securitycenter_v2.types import mitre_attack -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notebook -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import org_policy -from google.cloud.securitycenter_v2.types import process -from google.cloud.securitycenter_v2.types import resource -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import security_posture -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import toxic_combination -from google.cloud.securitycenter_v2.types import valued_resource -from google.cloud.securitycenter_v2.types import vulnerability -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 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 SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .transports.rest import SecurityCenterRestTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - _transport_registry["rest"] = SecurityCenterRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SecurityCenterTransport]: - """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V2 APIs for Security Center 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 = "securitycenter.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: - SecurityCenterClient: 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: - SecurityCenterClient: 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) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def attack_path_path(organization: str,simulation: str,valued_resource: str,attack_path: str,) -> str: - """Returns a fully-qualified attack_path string.""" - return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) - - @staticmethod - def parse_attack_path_path(path: str) -> Dict[str,str]: - """Parses a attack_path path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?P.+?)/attackPaths/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def big_query_export_path(organization: str,location: str,export: str,) -> str: - """Returns a fully-qualified big_query_export string.""" - return "organizations/{organization}/locations/{location}/bigQueryExports/{export}".format(organization=organization, location=location, export=export, ) - - @staticmethod - def parse_big_query_export_path(path: str) -> Dict[str,str]: - """Parses a big_query_export path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/locations/(?P.+?)/bigQueryExports/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def dlp_job_path(project: str,dlp_job: str,) -> str: - """Returns a fully-qualified dlp_job string.""" - return "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) - - @staticmethod - def parse_dlp_job_path(path: str) -> Dict[str,str]: - """Parses a dlp_job path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/dlpJobs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def external_system_path(organization: str,source: str,finding: str,externalsystem: str,) -> str: - """Returns a fully-qualified external_system string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) - - @staticmethod - def parse_external_system_path(path: str) -> Dict[str,str]: - """Parses a external_system path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)/externalSystems/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def finding_path(organization: str,source: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def mute_config_path(organization: str,mute_config: str,) -> str: - """Returns a fully-qualified mute_config string.""" - return "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) - - @staticmethod - def parse_mute_config_path(path: str) -> Dict[str,str]: - """Parses a mute_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/muteConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def notification_config_path(organization: str,location: str,notification_config: str,) -> str: - """Returns a fully-qualified notification_config string.""" - return "organizations/{organization}/locations/{location}/notificationConfigs/{notification_config}".format(organization=organization, location=location, notification_config=notification_config, ) - - @staticmethod - def parse_notification_config_path(path: str) -> Dict[str,str]: - """Parses a notification_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/locations/(?P.+?)/notificationConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def policy_path(organization: str,constraint_name: str,) -> str: - """Returns a fully-qualified policy string.""" - return "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) - - @staticmethod - def parse_policy_path(path: str) -> Dict[str,str]: - """Parses a policy path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/policies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def resource_value_config_path(organization: str,resource_value_config: str,) -> str: - """Returns a fully-qualified resource_value_config string.""" - return "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) - - @staticmethod - def parse_resource_value_config_path(path: str) -> Dict[str,str]: - """Parses a resource_value_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/resourceValueConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str,str]: - """Parses a security_marks path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) - return m.groupdict() if m else {} - - @staticmethod - def simulation_path(organization: str,simulation: str,) -> str: - """Returns a fully-qualified simulation string.""" - return "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) - - @staticmethod - def parse_simulation_path(path: str) -> Dict[str,str]: - """Parses a simulation path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str,source: str,) -> str: - """Returns a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str,str]: - """Parses a source path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def table_data_profile_path(project: str,table_profile: str,) -> str: - """Returns a fully-qualified table_data_profile string.""" - return "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) - - @staticmethod - def parse_table_data_profile_path(path: str) -> Dict[str,str]: - """Parses a table_data_profile path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/tableProfiles/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def topic_path(project: str,topic: str,) -> str: - """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - - @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: - """Parses a topic path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def valued_resource_path(organization: str,simulation: str,valued_resource: str,) -> str: - """Returns a fully-qualified valued_resource string.""" - return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) - - @staticmethod - def parse_valued_resource_path(path: str) -> Dict[str,str]: - """Parses a valued_resource path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 - SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient._read_environment_variables() - self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) - if transport_provided: - # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( - type(self).get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., SecurityCenterTransport], 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 batch_create_resource_value_configs(self, - request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - r"""Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - requests = securitycenter_v2.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - - request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest, dict]): - The request object. Request message to create multiple - resource value configs - parent (str): - Required. Resource name of the new - ResourceValueConfig's parent. The parent - field in the - CreateResourceValueConfigRequest - messages must either be empty or match - this field. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - requests (MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]): - Required. The resource value configs - to be created. - - This corresponds to the ``requests`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse: - Response message for - BatchCreateResourceValueConfigs - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, requests]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): - request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if requests is not None: - request.requests = requests - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_resource_value_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, - ) - - # Done; return the response. - return response - - def bulk_mute_findings(self, - request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), - ) -> operation.Operation: - r"""Kicks off an LRO to bulk mute findings for a parent - based on a filter. If no location is specified, findings - are muted in global. The parent can be either an - organization, folder, or project. The findings matched - by the filter will be muted after the LRO is done. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest, dict]): - The request object. Request message for bulk findings - update. - Note: - - 1. If multiple bulk update requests - match the same resource, the order - in which they get executed is not - defined. - 2. Once a bulk operation is started, - there is no way to stop it. - parent (str): - Required. The parent, at which bulk action needs to be - applied. If no location is specified, findings are - updated in global. The following list shows some - examples: - - - ``organizations/[organization_id]`` - - ``organizations/[organization_id]/locations/[location_id]`` - - ``folders/[folder_id]`` - - ``folders/[folder_id]/locations/[location_id]`` - - ``projects/[project_id]`` - - ``projects/[project_id]/locations/[location_id]`` - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v2.types.BulkMuteFindingsResponse` - The response to a BulkMute request. Contains the LRO - 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): - request = securitycenter_service.BulkMuteFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.bulk_mute_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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - securitycenter_service.BulkMuteFindingsResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - def create_big_query_export(self, - request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, - *, - parent: Optional[str] = None, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - big_query_export_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Creates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_create_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = client.create_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest, dict]): - The request object. Request message for creating a - BigQuery export. - parent (str): - Required. The name of the parent resource of the new - BigQuery export. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): - Required. The BigQuery export being - created. - - This corresponds to the ``big_query_export`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``big_query_export_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.cloud.securitycenter_v2.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): - request = securitycenter_service.CreateBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if big_query_export is not None: - request.big_query_export = big_query_export - if big_query_export_id is not None: - request.big_query_export_id = big_query_export_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - finding_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding in a location. The corresponding - source must exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_create_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.CreateFindingRequest, dict]): - The request object. Request message for creating a - finding. - parent (str): - Required. Resource name of the new finding's parent. The - following list shows some examples of the format: + - ``organizations/[organization_id]/sources/[source_id]`` - + - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (google.cloud.securitycenter_v2.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_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.cloud.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding, finding_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, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding is not None: - request.finding = finding - if finding_id is not None: - request.finding_id = finding_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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 create_mute_config(self, - request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - mute_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Creates a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_create_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = client.create_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.CreateMuteConfigRequest, dict]): - The request object. Request message for creating a mute - config. - parent (str): - Required. Resource name of the new mute configs's - parent. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config (google.cloud.securitycenter_v2.types.MuteConfig): - Required. The mute config being - created. - - This corresponds to the ``mute_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``mute_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.cloud.securitycenter_v2.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): - request = securitycenter_service.CreateMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if mute_config is not None: - request.mute_config = mute_config - if mute_config_id is not None: - request.mute_config_id = mute_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_mute_config] - - header_params = {} - - routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - 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_notification_config(self, - request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_create_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = client.create_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest, dict]): - The request object. Request message for creating a - notification config. - parent (str): - Required. Resource name of the new notification config's - parent. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (str): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters and contain - alphanumeric characters, underscores, or - hyphens only. - - This corresponds to the ``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.cloud.securitycenter_v2.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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_config, 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, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if notification_config is not None: - request.notification_config = notification_config - if config_id is not None: - request.config_id = config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_notification_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 create_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v2 - - def sample_create_source(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.CreateSourceRequest, dict]): - The request object. Request message for creating a - source. - parent (str): - Required. Resource name of the new source's parent. Its - format should be ``organizations/[organization_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (google.cloud.securitycenter_v2.types.Source): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v2.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_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 delete_big_query_export(self, - request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - client.delete_big_query_export(request=request) - - Args: - request (Union[google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest, dict]): - The request object. Request message for deleting a - BigQuery export. - name (str): - Required. The name of the BigQuery export to delete. The - following list shows some examples of the format: - - - - - ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` - - - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` - - ``projects/{project}/locations/{location}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): - request = securitycenter_service.DeleteBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - 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 delete_mute_config(self, - request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. If no location is - specified, default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_delete_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_mute_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest, dict]): - The request object. Request message for deleting a mute - config. If no location is specified, - default is global. - name (str): - Required. Name of the mute config to delete. The - following list shows some examples of the format: - - - ``organizations/{organization}/muteConfigs/{config_id}`` - - - - ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` - - - ``folders/{folder}/muteConfigs/{config_id}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` - - ``projects/{project}/muteConfigs/{config_id}`` - - ``projects/{project}/locations/{location}/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): - request = securitycenter_service.DeleteMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_mute_config] - - header_params = {} - - routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - 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 delete_notification_config(self, - request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_delete_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest, dict]): - The request object. Request message for deleting a - notification config. - name (str): - Required. Name of the notification config to delete. The - following list shows some examples of the format: - - - - - ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` - + - ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 delete_resource_value_config(self, - request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_resource_value_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest, dict]): - The request object. Request message to delete resource - value config - name (str): - Required. Name of the - ResourceValueConfig 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. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): - request = securitycenter_service.DeleteResourceValueConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_resource_value_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_big_query_export(self, - request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Gets a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_get_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = client.get_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetBigQueryExportRequest, dict]): - The request object. Request message for retrieving a - BigQuery export. - name (str): - Required. Name of the BigQuery export to retrieve. The - following list shows some examples of the format: - - - - - ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` - - - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` - - ``projects/{project}locations/{location}//bigQueryExports/{export_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.cloud.securitycenter_v2.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): - request = securitycenter_service.GetBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_simulation(self, - request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> simulation.Simulation: - r"""Get the simulation by name or the latest simulation - for the given organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_get_simulation(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = client.get_simulation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetSimulationRequest, dict]): - The request object. Request message for getting - simulation. Simulation name can include - "latest" to retrieve the latest - simulation For example, - "organizations/123/simulations/latest". - name (str): - Required. The organization name or simulation name of - this simulation - - Valid format: - ``organizations/{organization}/simulations/latest`` - ``organizations/{organization}/simulations/{simulation}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.Simulation: - Attack path simulation - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSimulationRequest): - request = securitycenter_service.GetSimulationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_simulation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_valued_resource(self, - request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> valued_resource.ValuedResource: - r"""Get the valued resource by 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 import securitycenter_v2 - - def sample_get_valued_resource(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_valued_resource(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetValuedResourceRequest, dict]): - The request object. Request message for getting a valued - resource. - name (str): - Required. The name of this valued resource - - Valid format: - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v2.types.ValuedResource: - A resource that is determined to have - value to a user's system - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetValuedResourceRequest): - request = securitycenter_service.GetValuedResourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_valued_resource] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v2 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 get_mute_config(self, - request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> mute_config.MuteConfig: - r"""Gets a mute config. If no location is specified, - default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_get_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetMuteConfigRequest, dict]): - The request object. Request message for retrieving a mute - config. If no location is specified, - default is global. - name (str): - Required. Name of the mute config to retrieve. The - following list shows some examples of the format: - - - ``organizations/{organization}/muteConfigs/{config_id}`` - - - - ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` - - - ``folders/{folder}/muteConfigs/{config_id}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` - - ``projects/{project}/muteConfigs/{config_id}`` - - ``projects/{project}/locations/{location}/muteConfigs/{config_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.cloud.securitycenter_v2.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetMuteConfigRequest): - request = securitycenter_service.GetMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_mute_config] - - header_params = {} - - routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - 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_notification_config(self, - request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_get_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetNotificationConfigRequest, dict]): - The request object. Request message for getting a - notification config. - name (str): - Required. Name of the notification config to get. The - following list shows some examples of the format: - - - - - ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_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.cloud.securitycenter_v2.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 get_resource_value_config(self, - request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resource_value_config.ResourceValueConfig: - r"""Gets a ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest, dict]): - The request object. Request message to get resource value - config - name (str): - Required. Name of the resource value config to retrieve. - Its format is - organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v2.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): - request = securitycenter_service.GetResourceValueConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_resource_value_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 get_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v2 - - def sample_get_source(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetSourceRequest, dict]): - The request object. Request message for getting a source. - name (str): - Required. Relative resource name of the source. Its - format is - ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v2.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties in a location. If no location is - specified, findings are assumed to be in global - - To group across all sources provide a ``-`` as the source id. - The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - - ``/v2/folders/{folder_id}/sources/-/findings`` - - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` - - ``/v2/projects/{project_id}/sources/-/findings`` - - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_group_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GroupFindingsRequest, dict]): - The request object. Request message for grouping by - findings. - parent (str): - Required. Name of the source to groupBy. If no location - is specified, finding is assumed to be in global. The - following list shows some examples: - - - ``organizations/[organization_id]/sources/[source_id]`` - - - - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - - ``folders/[folder_id]/sources/[source_id]`` - - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` - - ``projects/[project_id]/sources/[source_id]`` - - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` - - To groupBy across all sources provide a source_id of - ``-``. The following list shows some examples: - - - ``organizations/{organization_id}/sources/-`` - - ``organizations/{organization_id}/sources/-/locations/[location_id]`` - - ``folders/{folder_id}/sources/-`` - - ``folders/{folder_id}/sources/-/locations/[location_id]`` - - ``projects/{project_id}/sources/-`` - - ``projects/{project_id}/sources/-/locations/[location_id]`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (str): - Required. Expression that defines what assets fields to - use for grouping. The string value should follow SQL - syntax: comma separated list of fields. For example: - "parent,resource_name". - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_attack_paths(self, - request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsPager: - r"""Lists the attack paths for a set of simulation - results or valued resources and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_attack_paths(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListAttackPathsRequest, dict]): - The request object. Request message for listing the - attack paths for a given simulation or - valued resource. - parent (str): - Required. Name of parent to list attack paths. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - - 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.securitycenter_v2.services.security_center.pagers.ListAttackPathsPager: - Response message for listing the - attack paths for a given simulation or - valued resource. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): - request = securitycenter_service.ListAttackPathsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_attack_paths] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListAttackPathsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_big_query_exports(self, - request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsPager: - r"""Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are 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 securitycenter_v2 - - def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest, dict]): - The request object. Request message for listing BigQuery - exports at a given scope e.g. - organization, folder or project. - parent (str): - Required. The parent, which owns the collection of - BigQuery exports. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - 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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsPager: - Response message for listing BigQuery - exports. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): - request = securitycenter_service.ListBigQueryExportsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_big_query_exports] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListBigQueryExportsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings(self, - request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsPager: - r"""Lists an organization or source's findings. - - To list across all sources for a given location provide a ``-`` - as the source id. If no location is specified, finding are - assumed to be in global. The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListFindingsRequest( - parent="parent_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.securitycenter_v2.types.ListFindingsRequest, dict]): - The request object. Request message for listing findings. - parent (str): - Required. Name of the source the findings belong to. If - no location is specified, the default is global. The - following list shows some examples: - - - ``organizations/[organization_id]/sources/[source_id]`` - - - - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - - ``folders/[folder_id]/sources/[source_id]`` - - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` - - ``projects/[project_id]/sources/[source_id]`` - - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` - - To list across all sources provide a source_id of ``-``. - The following list shows some examples: - - - ``organizations/{organization_id}/sources/-`` - - ``organizations/{organization_id}/sources/-/locations/{location_id}`` - - ``folders/{folder_id}/sources/-`` - - ``folders/{folder_id}/sources/-locations/{location_id}`` - - ``projects/{projects_id}/sources/-`` - - ``projects/{projects_id}/sources/-/locations/{location_id}`` - - 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.securitycenter_v2.services.security_center.pagers.ListFindingsPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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_mute_configs(self, - request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsPager: - r"""Lists mute configs. If no location is specified, - default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_mute_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListMuteConfigsRequest, dict]): - The request object. Request message for listing mute - configs at a given scope e.g. - organization, folder or project. If no - location is specified, default is - global. - parent (str): - Required. The parent, which owns the collection of mute - configs. Its format is - ``organizations/[organization_id]", "folders/[folder_id]``, - ``projects/[project_id]``, - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, - ``projects/[project_id]/locations/[location_id]``. - - 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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsPager: - Response message for listing mute - configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): - request = securitycenter_service.ListMuteConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_mute_configs] - - header_params = {} - - routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - 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.ListMuteConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_notification_configs(self, - request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsPager: - r"""Lists notification configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_notification_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest, dict]): - The request object. Request message for listing - notification configs. - parent (str): - Required. The name of the parent in which to list the - notification configurations. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". - - 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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListNotificationConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_resource_value_configs(self, - request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsPager: - r"""Lists all ResourceValueConfigs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest, dict]): - The request object. Request message to list resource - value configs of a parent - parent (str): - Required. The parent, which owns the collection of - resource value configs. Its format is - ``organizations/[organization_id]`` - - 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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsPager: - Response message to list resource - value configs - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): - request = securitycenter_service.ListResourceValueConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_resource_value_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.ListResourceValueConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_sources(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListSourcesRequest, dict]): - The request object. Request message for listing sources. - parent (str): - Required. Resource name of the parent of sources to - list. Its format should be - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - 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.securitycenter_v2.services.security_center.pagers.ListSourcesPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_valued_resources(self, - request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesPager: - r"""Lists the valued resources for a set of simulation - results and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_valued_resources(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListValuedResourcesRequest, dict]): - The request object. Request message for listing the - valued resources for a given simulation. - parent (str): - Required. Name of parent to list exposed resources. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - - 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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesPager: - Response message for listing the - valued resources for a given simulation. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): - request = securitycenter_service.ListValuedResourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_valued_resources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListValuedResourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. If no location is - specified, finding is assumed to be in global - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_set_finding_state(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.SetFindingStateRequest, dict]): - The request object. Request message for updating a - finding's state. - name (str): - Required. The `relative resource - name `__ - of the finding. If no location is specified, finding is - assumed to be in global. The following list shows some - examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (google.cloud.securitycenter_v2.types.Finding.State): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v2 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 set_mute(self, - request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, - *, - name: Optional[str] = None, - mute: Optional[finding.Finding.Mute] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the mute state of a finding. If no location - is specified, finding is assumed to be in global - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_set_mute(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = client.set_mute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.SetMuteRequest, dict]): - The request object. Request message for updating a - finding's mute status. - name (str): - Required. The `relative resource - name `__ - of the finding. If no location is specified, finding is - assumed to be in global. The following list shows some - examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute (google.cloud.securitycenter_v2.types.Finding.Mute): - Required. The desired state of the - Mute. - - This corresponds to the ``mute`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, mute]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetMuteRequest): - request = securitycenter_service.SetMuteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if mute is not None: - request.mute = mute - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_mute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v2 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # 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 - - def update_big_query_export(self, - request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, - *, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - update_mask: 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]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Updates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateBigQueryExportRequest( - ) - - # Make the request - response = client.update_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest, dict]): - The request object. Request message for updating a - BigQuery export. - big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): - Required. The BigQuery export being - updated. - - This corresponds to the ``big_query_export`` 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. - If empty all mutable fields 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.cloud.securitycenter_v2.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): - request = securitycenter_service.UpdateBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if big_query_export is not None: - request.big_query_export = big_query_export - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("big_query_export.name", request.big_query_export.name), - )), - ) - - # Validate the universe 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_external_system(self, - request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, - *, - external_system: Optional[gcs_external_system.ExternalSystem] = None, - update_mask: 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]] = (), - ) -> gcs_external_system.ExternalSystem: - r"""Updates external system. This is for a given finding. - If no location is specified, finding is assumed to be in - global - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_external_system(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateExternalSystemRequest( - ) - - # Make the request - response = client.update_external_system(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest, dict]): - The request object. Request message for updating a - ExternalSystem resource. - external_system (google.cloud.securitycenter_v2.types.ExternalSystem): - Required. The external system - resource to update. - - This corresponds to the ``external_system`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the external system resource. - If empty all mutable fields 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.cloud.securitycenter_v2.types.ExternalSystem: - Representation of third party - SIEM/SOAR fields within SCC. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): - request = securitycenter_service.UpdateExternalSystemRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if external_system is not None: - request.external_system = external_system - 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_external_system] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("external_system.name", request.external_system.name), - )), - ) - - # Validate the universe 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_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - update_mask: 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]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. If no location is - specified, finding is assumed to be in global. The - corresponding source must exist for a finding creation - to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateFindingRequest, dict]): - The request object. Request message for updating or - creating a finding. - finding (google.cloud.securitycenter_v2.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a - finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing - source_properties. Individual source_properties can be - added/updated by using "source_properties." in the field - mask. - - 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.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - 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_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe 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_mute_config(self, - request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, - *, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - update_mask: 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]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Updates a mute config. If no location is specified, - default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = client.update_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest, dict]): - The request object. Request message for updating a mute - config. - mute_config (google.cloud.securitycenter_v2.types.MuteConfig): - Required. The mute config being - updated. - - This corresponds to the ``mute_config`` 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. - If empty all mutable fields 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.cloud.securitycenter_v2.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): - request = securitycenter_service.UpdateMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if mute_config is not None: - request.mute_config = mute_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_mute_config] - - header_params = {} - - routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.mute_config.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.mute_config.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.mute_config.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - 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_notification_config(self, - request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, - *, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - update_mask: 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]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateNotificationConfigRequest( - ) - - # Make the request - response = client.update_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest, dict]): - The request object. Request message for updating a - notification config. - notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the notification config. - If empty all mutable fields 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.cloud.securitycenter_v2.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_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 update_resource_value_config(self, - request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, - *, - resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, - update_mask: 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]] = (), - ) -> gcs_resource_value_config.ResourceValueConfig: - r"""Updates an existing ResourceValueConfigs with new - rules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateResourceValueConfigRequest( - ) - - # Make the request - response = client.update_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest, dict]): - The request object. Request message to update resource - value config - resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): - Required. The resource value config - being updated. - - This corresponds to the ``resource_value_config`` 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. If empty all mutable - fields will be updated. - - To update nested fields, include the top level field in - the mask For example, to update - gcp_metadata.resource_type, include the "gcp_metadata" - field mask - - 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.securitycenter_v2.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): - request = securitycenter_service.UpdateResourceValueConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if resource_value_config is not None: - request.resource_value_config = resource_value_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_resource_value_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource_value_config.name", request.resource_value_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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - update_mask: 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]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. For Finding Security marks, - if no location is specified, finding is assumed to be in - global. Assets Security Marks can only be accessed - through global endpoint. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_security_marks(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest, dict]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If - empty or set to "marks", all marks will be replaced. - Individual marks can be updated using - "marks.". - - 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.securitycenter_v2.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - 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_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe 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_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - update_mask: 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]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v2 - - def sample_update_source(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateSourceRequest, dict]): - The request object. Request message for updating a - source. - source (google.cloud.securitycenter_v2.types.Source): - Required. The source resource to - update. - - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the source resource. - If empty all mutable fields 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.cloud.securitycenter_v2.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = 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_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 __enter__(self) -> "SecurityCenterClient": - 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 = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - 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 = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SecurityCenterClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py deleted file mode 100644 index 59d34c60c0a9..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py +++ /dev/null @@ -1,1249 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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.securitycenter_v2.types import attack_path -from google.cloud.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import valued_resource - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v2.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` - attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v2.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAttackPathsPager: - """A pager for iterating through ``list_attack_paths`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``attack_paths`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAttackPaths`` requests and continue to iterate - through the ``attack_paths`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListAttackPathsResponse], - request: securitycenter_service.ListAttackPathsRequest, - response: securitycenter_service.ListAttackPathsResponse, - *, - 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.securitycenter_v2.types.ListAttackPathsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListAttackPathsResponse): - 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 = securitycenter_service.ListAttackPathsRequest(request) - 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[securitycenter_service.ListAttackPathsResponse]: - 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[attack_path.AttackPath]: - for page in self.pages: - yield from page.attack_paths - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAttackPathsAsyncPager: - """A pager for iterating through ``list_attack_paths`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``attack_paths`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAttackPaths`` requests and continue to iterate - through the ``attack_paths`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` - attributes are available on the 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[securitycenter_service.ListAttackPathsResponse]], - request: securitycenter_service.ListAttackPathsRequest, - response: securitycenter_service.ListAttackPathsResponse, - *, - 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.securitycenter_v2.types.ListAttackPathsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListAttackPathsResponse): - 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 = securitycenter_service.ListAttackPathsRequest(request) - 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[securitycenter_service.ListAttackPathsResponse]: - 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[attack_path.AttackPath]: - async def async_generator(): - async for page in self.pages: - for response in page.attack_paths: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBigQueryExportsPager: - """A pager for iterating through ``list_big_query_exports`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``big_query_exports`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListBigQueryExports`` requests and continue to iterate - through the ``big_query_exports`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListBigQueryExportsResponse], - request: securitycenter_service.ListBigQueryExportsRequest, - response: securitycenter_service.ListBigQueryExportsResponse, - *, - 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.securitycenter_v2.types.ListBigQueryExportsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse): - 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 = securitycenter_service.ListBigQueryExportsRequest(request) - 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[securitycenter_service.ListBigQueryExportsResponse]: - 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[bigquery_export.BigQueryExport]: - for page in self.pages: - yield from page.big_query_exports - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBigQueryExportsAsyncPager: - """A pager for iterating through ``list_big_query_exports`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``big_query_exports`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListBigQueryExports`` requests and continue to iterate - through the ``big_query_exports`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` - attributes are available on the 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[securitycenter_service.ListBigQueryExportsResponse]], - request: securitycenter_service.ListBigQueryExportsRequest, - response: securitycenter_service.ListBigQueryExportsResponse, - *, - 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.securitycenter_v2.types.ListBigQueryExportsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse): - 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 = securitycenter_service.ListBigQueryExportsRequest(request) - 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[securitycenter_service.ListBigQueryExportsResponse]: - 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[bigquery_export.BigQueryExport]: - async def async_generator(): - async for page in self.pages: - for response in page.big_query_exports: - 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.securitycenter_v2.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.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[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v2.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - for page in self.pages: - yield from page.list_findings_results - - 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.securitycenter_v2.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.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[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v2.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_findings_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMuteConfigsPager: - """A pager for iterating through ``list_mute_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``mute_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListMuteConfigs`` requests and continue to iterate - through the ``mute_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListMuteConfigsResponse], - request: securitycenter_service.ListMuteConfigsRequest, - response: securitycenter_service.ListMuteConfigsResponse, - *, - 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.securitycenter_v2.types.ListMuteConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListMuteConfigsResponse): - 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 = securitycenter_service.ListMuteConfigsRequest(request) - 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[securitycenter_service.ListMuteConfigsResponse]: - 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[mute_config.MuteConfig]: - for page in self.pages: - yield from page.mute_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMuteConfigsAsyncPager: - """A pager for iterating through ``list_mute_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``mute_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListMuteConfigs`` requests and continue to iterate - through the ``mute_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` - attributes are available on the 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[securitycenter_service.ListMuteConfigsResponse]], - request: securitycenter_service.ListMuteConfigsRequest, - response: securitycenter_service.ListMuteConfigsResponse, - *, - 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.securitycenter_v2.types.ListMuteConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListMuteConfigsResponse): - 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 = securitycenter_service.ListMuteConfigsRequest(request) - 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[securitycenter_service.ListMuteConfigsResponse]: - 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[mute_config.MuteConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.mute_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v2.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - 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[securitycenter_service.ListNotificationConfigsResponse]: - 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[notification_config.NotificationConfig]: - for page in self.pages: - yield from page.notification_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsAsyncPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` - attributes are available on the 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[securitycenter_service.ListNotificationConfigsResponse]], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v2.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - 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[securitycenter_service.ListNotificationConfigsResponse]: - 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[notification_config.NotificationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.notification_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourceValueConfigsPager: - """A pager for iterating through ``list_resource_value_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``resource_value_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListResourceValueConfigs`` requests and continue to iterate - through the ``resource_value_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListResourceValueConfigsResponse], - request: securitycenter_service.ListResourceValueConfigsRequest, - response: securitycenter_service.ListResourceValueConfigsResponse, - *, - 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.securitycenter_v2.types.ListResourceValueConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse): - 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 = securitycenter_service.ListResourceValueConfigsRequest(request) - 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[securitycenter_service.ListResourceValueConfigsResponse]: - 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[resource_value_config.ResourceValueConfig]: - for page in self.pages: - yield from page.resource_value_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourceValueConfigsAsyncPager: - """A pager for iterating through ``list_resource_value_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``resource_value_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListResourceValueConfigs`` requests and continue to iterate - through the ``resource_value_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` - attributes are available on the 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[securitycenter_service.ListResourceValueConfigsResponse]], - request: securitycenter_service.ListResourceValueConfigsRequest, - response: securitycenter_service.ListResourceValueConfigsResponse, - *, - 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.securitycenter_v2.types.ListResourceValueConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse): - 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 = securitycenter_service.ListResourceValueConfigsRequest(request) - 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[securitycenter_service.ListResourceValueConfigsResponse]: - 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[resource_value_config.ResourceValueConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.resource_value_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v2.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` - attributes are available on the 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[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v2.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.sources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListValuedResourcesPager: - """A pager for iterating through ``list_valued_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``valued_resources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListValuedResources`` requests and continue to iterate - through the ``valued_resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListValuedResourcesResponse], - request: securitycenter_service.ListValuedResourcesRequest, - response: securitycenter_service.ListValuedResourcesResponse, - *, - 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.securitycenter_v2.types.ListValuedResourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListValuedResourcesResponse): - 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 = securitycenter_service.ListValuedResourcesRequest(request) - 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[securitycenter_service.ListValuedResourcesResponse]: - 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[valued_resource.ValuedResource]: - for page in self.pages: - yield from page.valued_resources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListValuedResourcesAsyncPager: - """A pager for iterating through ``list_valued_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``valued_resources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListValuedResources`` requests and continue to iterate - through the ``valued_resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` - attributes are available on the 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[securitycenter_service.ListValuedResourcesResponse]], - request: securitycenter_service.ListValuedResourcesRequest, - response: securitycenter_service.ListValuedResourcesResponse, - *, - 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.securitycenter_v2.types.ListValuedResourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListValuedResourcesResponse): - 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 = securitycenter_service.ListValuedResourcesRequest(request) - 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[securitycenter_service.ListValuedResourcesResponse]: - 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[valued_resource.ValuedResource]: - async def async_generator(): - async for page in self.pages: - for response in page.valued_resources: - 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-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py deleted file mode 100644 index 9d36139c1a9b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/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 SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .rest import SecurityCenterRestTransport -from .rest import SecurityCenterRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry['grpc'] = SecurityCenterGrpcTransport -_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport -_transport_registry['rest'] = SecurityCenterRestTransport - -__all__ = ( - 'SecurityCenterTransport', - 'SecurityCenterGrpcTransport', - 'SecurityCenterGrpcAsyncIOTransport', - 'SecurityCenterRestTransport', - 'SecurityCenterRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py deleted file mode 100644 index 817f5b747cd0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py +++ /dev/null @@ -1,761 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.securitycenter_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.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.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import valued_resource -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 empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'securitycenter.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.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: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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.batch_create_resource_value_configs: gapic_v1.method.wrap_method( - self.batch_create_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.bulk_mute_findings: gapic_v1.method.wrap_method( - self.bulk_mute_findings, - default_timeout=None, - client_info=client_info, - ), - self.create_big_query_export: gapic_v1.method.wrap_method( - self.create_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, - default_timeout=None, - client_info=client_info, - ), - self.create_mute_config: gapic_v1.method.wrap_method( - self.create_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method.wrap_method( - self.create_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.create_source: gapic_v1.method.wrap_method( - self.create_source, - default_timeout=None, - client_info=client_info, - ), - self.delete_big_query_export: gapic_v1.method.wrap_method( - self.delete_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.delete_mute_config: gapic_v1.method.wrap_method( - self.delete_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method.wrap_method( - self.delete_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_resource_value_config: gapic_v1.method.wrap_method( - self.delete_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.get_big_query_export: gapic_v1.method.wrap_method( - self.get_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.get_simulation: gapic_v1.method.wrap_method( - self.get_simulation, - default_timeout=None, - client_info=client_info, - ), - self.get_valued_resource: gapic_v1.method.wrap_method( - self.get_valued_resource, - default_timeout=None, - 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.get_mute_config: gapic_v1.method.wrap_method( - self.get_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.get_notification_config: gapic_v1.method.wrap_method( - self.get_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.get_resource_value_config: gapic_v1.method.wrap_method( - self.get_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.get_source: gapic_v1.method.wrap_method( - self.get_source, - default_timeout=None, - client_info=client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_findings, - default_timeout=None, - client_info=client_info, - ), - self.list_attack_paths: gapic_v1.method.wrap_method( - self.list_attack_paths, - default_timeout=None, - client_info=client_info, - ), - self.list_big_query_exports: gapic_v1.method.wrap_method( - self.list_big_query_exports, - default_timeout=None, - client_info=client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - default_timeout=None, - client_info=client_info, - ), - self.list_mute_configs: gapic_v1.method.wrap_method( - self.list_mute_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method.wrap_method( - self.list_notification_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_resource_value_configs: gapic_v1.method.wrap_method( - self.list_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_sources: gapic_v1.method.wrap_method( - self.list_sources, - default_timeout=None, - client_info=client_info, - ), - self.list_valued_resources: gapic_v1.method.wrap_method( - self.list_valued_resources, - default_timeout=None, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, - 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.set_mute: gapic_v1.method.wrap_method( - self.set_mute, - 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.update_big_query_export: gapic_v1.method.wrap_method( - self.update_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.update_external_system: gapic_v1.method.wrap_method( - self.update_external_system, - default_timeout=None, - client_info=client_info, - ), - self.update_finding: gapic_v1.method.wrap_method( - self.update_finding, - default_timeout=None, - client_info=client_info, - ), - self.update_mute_config: gapic_v1.method.wrap_method( - self.update_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method.wrap_method( - self.update_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.update_resource_value_config: gapic_v1.method.wrap_method( - self.update_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=None, - client_info=client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_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 operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - Union[ - securitycenter_service.BatchCreateResourceValueConfigsResponse, - Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - Union[ - bigquery_export.BigQueryExport, - Awaitable[bigquery_export.BigQueryExport] - ]]: - raise NotImplementedError() - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - Union[ - gcs_mute_config.MuteConfig, - Awaitable[gcs_mute_config.MuteConfig] - ]]: - raise NotImplementedError() - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - Union[ - bigquery_export.BigQueryExport, - Awaitable[bigquery_export.BigQueryExport] - ]]: - raise NotImplementedError() - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - Union[ - simulation.Simulation, - Awaitable[simulation.Simulation] - ]]: - raise NotImplementedError() - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - Union[ - valued_resource.ValuedResource, - Awaitable[valued_resource.ValuedResource] - ]]: - 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 get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - Union[ - mute_config.MuteConfig, - Awaitable[mute_config.MuteConfig] - ]]: - raise NotImplementedError() - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Union[ - notification_config.NotificationConfig, - Awaitable[notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - Union[ - resource_value_config.ResourceValueConfig, - Awaitable[resource_value_config.ResourceValueConfig] - ]]: - raise NotImplementedError() - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Union[ - source.Source, - Awaitable[source.Source] - ]]: - raise NotImplementedError() - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Union[ - securitycenter_service.GroupFindingsResponse, - Awaitable[securitycenter_service.GroupFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - Union[ - securitycenter_service.ListAttackPathsResponse, - Awaitable[securitycenter_service.ListAttackPathsResponse] - ]]: - raise NotImplementedError() - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - Union[ - securitycenter_service.ListBigQueryExportsResponse, - Awaitable[securitycenter_service.ListBigQueryExportsResponse] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Union[ - securitycenter_service.ListFindingsResponse, - Awaitable[securitycenter_service.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - Union[ - securitycenter_service.ListMuteConfigsResponse, - Awaitable[securitycenter_service.ListMuteConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Union[ - securitycenter_service.ListNotificationConfigsResponse, - Awaitable[securitycenter_service.ListNotificationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - Union[ - securitycenter_service.ListResourceValueConfigsResponse, - Awaitable[securitycenter_service.ListResourceValueConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Union[ - securitycenter_service.ListSourcesResponse, - Awaitable[securitycenter_service.ListSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - Union[ - securitycenter_service.ListValuedResourcesResponse, - Awaitable[securitycenter_service.ListValuedResourcesResponse] - ]]: - raise NotImplementedError() - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - 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 set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - 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 update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - Union[ - bigquery_export.BigQueryExport, - Awaitable[bigquery_export.BigQueryExport] - ]]: - raise NotImplementedError() - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - Union[ - gcs_external_system.ExternalSystem, - Awaitable[gcs_external_system.ExternalSystem] - ]]: - raise NotImplementedError() - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - Union[ - gcs_mute_config.MuteConfig, - Awaitable[gcs_mute_config.MuteConfig] - ]]: - raise NotImplementedError() - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - Union[ - gcs_resource_value_config.ResourceValueConfig, - Awaitable[gcs_resource_value_config.ResourceValueConfig] - ]]: - raise NotImplementedError() - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Union[ - gcs_security_marks.SecurityMarks, - Awaitable[gcs_security_marks.SecurityMarks] - ]]: - raise NotImplementedError() - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SecurityCenterTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py deleted file mode 100644 index 3ab2b66d9b6e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py +++ /dev/null @@ -1,1452 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import valued_resource -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 empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V2 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: 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 batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - securitycenter_service.BatchCreateResourceValueConfigsResponse]: - r"""Return a callable for the batch create resource value - configs method over gRPC. - - Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - Returns: - Callable[[~.BatchCreateResourceValueConfigsRequest], - ~.BatchCreateResourceValueConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: - self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/BatchCreateResourceValueConfigs', - request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, - ) - return self._stubs['batch_create_resource_value_configs'] - - @property - def bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - operations_pb2.Operation]: - r"""Return a callable for the bulk mute findings method over gRPC. - - Kicks off an LRO to bulk mute findings for a parent - based on a filter. If no location is specified, findings - are muted in global. The parent can be either an - organization, folder, or project. The findings matched - by the filter will be muted after the LRO is done. - - Returns: - Callable[[~.BulkMuteFindingsRequest], - ~.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 'bulk_mute_findings' not in self._stubs: - self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/BulkMuteFindings', - request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['bulk_mute_findings'] - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - r"""Return a callable for the create big query export method over gRPC. - - Creates a BigQuery export. - - Returns: - Callable[[~.CreateBigQueryExportRequest], - ~.BigQueryExport]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateBigQueryExport', - request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['create_big_query_export'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding in a location. The corresponding - source must exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - r"""Return a callable for the create mute config method over gRPC. - - Creates a mute config. - - Returns: - Callable[[~.CreateMuteConfigRequest], - ~.MuteConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateMuteConfig', - request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['create_mute_config'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete big query export method over gRPC. - - Deletes an existing BigQuery export. - - Returns: - Callable[[~.DeleteBigQueryExportRequest], - ~.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_big_query_export' not in self._stubs: - self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteBigQueryExport', - request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_big_query_export'] - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete mute config method over gRPC. - - Deletes an existing mute config. If no location is - specified, default is global. - - Returns: - Callable[[~.DeleteMuteConfigRequest], - ~.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_mute_config' not in self._stubs: - self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteMuteConfig', - request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_mute_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - ~.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_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete resource value config method over gRPC. - - Deletes a ResourceValueConfig. - - Returns: - Callable[[~.DeleteResourceValueConfigRequest], - ~.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_resource_value_config' not in self._stubs: - self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteResourceValueConfig', - request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_resource_value_config'] - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - bigquery_export.BigQueryExport]: - r"""Return a callable for the get big query export method over gRPC. - - Gets a BigQuery export. - - Returns: - Callable[[~.GetBigQueryExportRequest], - ~.BigQueryExport]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_big_query_export' not in self._stubs: - self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetBigQueryExport', - request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['get_big_query_export'] - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - simulation.Simulation]: - r"""Return a callable for the get simulation method over gRPC. - - Get the simulation by name or the latest simulation - for the given organization. - - Returns: - Callable[[~.GetSimulationRequest], - ~.Simulation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_simulation' not in self._stubs: - self._stubs['get_simulation'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetSimulation', - request_serializer=securitycenter_service.GetSimulationRequest.serialize, - response_deserializer=simulation.Simulation.deserialize, - ) - return self._stubs['get_simulation'] - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - valued_resource.ValuedResource]: - r"""Return a callable for the get valued resource method over gRPC. - - Get the valued resource by name - - Returns: - Callable[[~.GetValuedResourceRequest], - ~.ValuedResource]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_valued_resource' not in self._stubs: - self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetValuedResource', - request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, - response_deserializer=valued_resource.ValuedResource.deserialize, - ) - return self._stubs['get_valued_resource'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v2.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - mute_config.MuteConfig]: - r"""Return a callable for the get mute config method over gRPC. - - Gets a mute config. If no location is specified, - default is global. - - Returns: - Callable[[~.GetMuteConfigRequest], - ~.MuteConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_mute_config' not in self._stubs: - self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetMuteConfig', - request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, - response_deserializer=mute_config.MuteConfig.deserialize, - ) - return self._stubs['get_mute_config'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - resource_value_config.ResourceValueConfig]: - r"""Return a callable for the get resource value config method over gRPC. - - Gets a ResourceValueConfig. - - Returns: - Callable[[~.GetResourceValueConfigRequest], - ~.ResourceValueConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_resource_value_config' not in self._stubs: - self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetResourceValueConfig', - request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, - response_deserializer=resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['get_resource_value_config'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties in a location. If no location is - specified, findings are assumed to be in global - - To group across all sources provide a ``-`` as the source id. - The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - - ``/v2/folders/{folder_id}/sources/-/findings`` - - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` - - ``/v2/projects/{project_id}/sources/-/findings`` - - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - securitycenter_service.ListAttackPathsResponse]: - r"""Return a callable for the list attack paths method over gRPC. - - Lists the attack paths for a set of simulation - results or valued resources and filter. - - Returns: - Callable[[~.ListAttackPathsRequest], - ~.ListAttackPathsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_attack_paths' not in self._stubs: - self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListAttackPaths', - request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, - response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, - ) - return self._stubs['list_attack_paths'] - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - securitycenter_service.ListBigQueryExportsResponse]: - r"""Return a callable for the list big query exports method over gRPC. - - Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are returned. - - Returns: - Callable[[~.ListBigQueryExportsRequest], - ~.ListBigQueryExportsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_big_query_exports' not in self._stubs: - self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListBigQueryExports', - request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, - response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, - ) - return self._stubs['list_big_query_exports'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources for a given location provide a ``-`` - as the source id. If no location is specified, finding are - assumed to be in global. The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - 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.securitycenter.v2.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - securitycenter_service.ListMuteConfigsResponse]: - r"""Return a callable for the list mute configs method over gRPC. - - Lists mute configs. If no location is specified, - default is global. - - Returns: - Callable[[~.ListMuteConfigsRequest], - ~.ListMuteConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_mute_configs' not in self._stubs: - self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListMuteConfigs', - request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, - ) - return self._stubs['list_mute_configs'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - ~.ListNotificationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - securitycenter_service.ListResourceValueConfigsResponse]: - r"""Return a callable for the list resource value configs method over gRPC. - - Lists all ResourceValueConfigs. - - Returns: - Callable[[~.ListResourceValueConfigsRequest], - ~.ListResourceValueConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_resource_value_configs' not in self._stubs: - self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListResourceValueConfigs', - request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, - ) - return self._stubs['list_resource_value_configs'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - securitycenter_service.ListValuedResourcesResponse]: - r"""Return a callable for the list valued resources method over gRPC. - - Lists the valued resources for a set of simulation - results and filter. - - Returns: - Callable[[~.ListValuedResourcesRequest], - ~.ListValuedResourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_valued_resources' not in self._stubs: - self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListValuedResources', - request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, - response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, - ) - return self._stubs['list_valued_resources'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. If no location is - specified, finding is assumed to be in global - - Returns: - Callable[[~.SetFindingStateRequest], - ~.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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v2.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - finding.Finding]: - r"""Return a callable for the set mute method over gRPC. - - Updates the mute state of a finding. If no location - is specified, finding is assumed to be in global - - Returns: - Callable[[~.SetMuteRequest], - ~.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 'set_mute' not in self._stubs: - self._stubs['set_mute'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/SetMute', - request_serializer=securitycenter_service.SetMuteRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_mute'] - - @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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v2.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - r"""Return a callable for the update big query export method over gRPC. - - Updates a BigQuery export. - - Returns: - Callable[[~.UpdateBigQueryExportRequest], - ~.BigQueryExport]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateBigQueryExport', - request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['update_big_query_export'] - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - gcs_external_system.ExternalSystem]: - r"""Return a callable for the update external system method over gRPC. - - Updates external system. This is for a given finding. - If no location is specified, finding is assumed to be in - global - - Returns: - Callable[[~.UpdateExternalSystemRequest], - ~.ExternalSystem]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_external_system' not in self._stubs: - self._stubs['update_external_system'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateExternalSystem', - request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, - response_deserializer=gcs_external_system.ExternalSystem.deserialize, - ) - return self._stubs['update_external_system'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. If no location is - specified, finding is assumed to be in global. The - corresponding source must exist for a finding creation - to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - r"""Return a callable for the update mute config method over gRPC. - - Updates a mute config. If no location is specified, - default is global. - - Returns: - Callable[[~.UpdateMuteConfigRequest], - ~.MuteConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateMuteConfig', - request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['update_mute_config'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - gcs_resource_value_config.ResourceValueConfig]: - r"""Return a callable for the update resource value config method over gRPC. - - Updates an existing ResourceValueConfigs with new - rules. - - Returns: - Callable[[~.UpdateResourceValueConfigRequest], - ~.ResourceValueConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: - self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateResourceValueConfig', - request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, - response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['update_resource_value_config'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. For Finding Security marks, - if no location is specified, finding is assumed to be in - global. Assets Security Marks can only be accessed - through global endpoint. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - 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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SecurityCenterGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index b83a55a9f90c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,1657 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import valued_resource -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 empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V2 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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._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 batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse]]: - r"""Return a callable for the batch create resource value - configs method over gRPC. - - Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - Returns: - Callable[[~.BatchCreateResourceValueConfigsRequest], - Awaitable[~.BatchCreateResourceValueConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: - self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/BatchCreateResourceValueConfigs', - request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, - ) - return self._stubs['batch_create_resource_value_configs'] - - @property - def bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the bulk mute findings method over gRPC. - - Kicks off an LRO to bulk mute findings for a parent - based on a filter. If no location is specified, findings - are muted in global. The parent can be either an - organization, folder, or project. The findings matched - by the filter will be muted after the LRO is done. - - Returns: - Callable[[~.BulkMuteFindingsRequest], - 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 'bulk_mute_findings' not in self._stubs: - self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/BulkMuteFindings', - request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['bulk_mute_findings'] - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - Awaitable[bigquery_export.BigQueryExport]]: - r"""Return a callable for the create big query export method over gRPC. - - Creates a BigQuery export. - - Returns: - Callable[[~.CreateBigQueryExportRequest], - Awaitable[~.BigQueryExport]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateBigQueryExport', - request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['create_big_query_export'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding in a location. The corresponding - source must exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - 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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - Awaitable[gcs_mute_config.MuteConfig]]: - r"""Return a callable for the create mute config method over gRPC. - - Creates a mute config. - - Returns: - Callable[[~.CreateMuteConfigRequest], - Awaitable[~.MuteConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateMuteConfig', - request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['create_mute_config'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete big query export method over gRPC. - - Deletes an existing BigQuery export. - - Returns: - Callable[[~.DeleteBigQueryExportRequest], - 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_big_query_export' not in self._stubs: - self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteBigQueryExport', - request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_big_query_export'] - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete mute config method over gRPC. - - Deletes an existing mute config. If no location is - specified, default is global. - - Returns: - Callable[[~.DeleteMuteConfigRequest], - 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_mute_config' not in self._stubs: - self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteMuteConfig', - request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_mute_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - 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_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete resource value config method over gRPC. - - Deletes a ResourceValueConfig. - - Returns: - Callable[[~.DeleteResourceValueConfigRequest], - 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_resource_value_config' not in self._stubs: - self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteResourceValueConfig', - request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_resource_value_config'] - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - Awaitable[bigquery_export.BigQueryExport]]: - r"""Return a callable for the get big query export method over gRPC. - - Gets a BigQuery export. - - Returns: - Callable[[~.GetBigQueryExportRequest], - Awaitable[~.BigQueryExport]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_big_query_export' not in self._stubs: - self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetBigQueryExport', - request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['get_big_query_export'] - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - Awaitable[simulation.Simulation]]: - r"""Return a callable for the get simulation method over gRPC. - - Get the simulation by name or the latest simulation - for the given organization. - - Returns: - Callable[[~.GetSimulationRequest], - Awaitable[~.Simulation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_simulation' not in self._stubs: - self._stubs['get_simulation'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetSimulation', - request_serializer=securitycenter_service.GetSimulationRequest.serialize, - response_deserializer=simulation.Simulation.deserialize, - ) - return self._stubs['get_simulation'] - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - Awaitable[valued_resource.ValuedResource]]: - r"""Return a callable for the get valued resource method over gRPC. - - Get the valued resource by name - - Returns: - Callable[[~.GetValuedResourceRequest], - Awaitable[~.ValuedResource]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_valued_resource' not in self._stubs: - self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetValuedResource', - request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, - response_deserializer=valued_resource.ValuedResource.deserialize, - ) - return self._stubs['get_valued_resource'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v2.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - Awaitable[mute_config.MuteConfig]]: - r"""Return a callable for the get mute config method over gRPC. - - Gets a mute config. If no location is specified, - default is global. - - Returns: - Callable[[~.GetMuteConfigRequest], - Awaitable[~.MuteConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_mute_config' not in self._stubs: - self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetMuteConfig', - request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, - response_deserializer=mute_config.MuteConfig.deserialize, - ) - return self._stubs['get_mute_config'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Awaitable[notification_config.NotificationConfig]]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - Awaitable[resource_value_config.ResourceValueConfig]]: - r"""Return a callable for the get resource value config method over gRPC. - - Gets a ResourceValueConfig. - - Returns: - Callable[[~.GetResourceValueConfigRequest], - Awaitable[~.ResourceValueConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_resource_value_config' not in self._stubs: - self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetResourceValueConfig', - request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, - response_deserializer=resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['get_resource_value_config'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse]]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties in a location. If no location is - specified, findings are assumed to be in global - - To group across all sources provide a ``-`` as the source id. - The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - - ``/v2/folders/{folder_id}/sources/-/findings`` - - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` - - ``/v2/projects/{project_id}/sources/-/findings`` - - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - Awaitable[securitycenter_service.ListAttackPathsResponse]]: - r"""Return a callable for the list attack paths method over gRPC. - - Lists the attack paths for a set of simulation - results or valued resources and filter. - - Returns: - Callable[[~.ListAttackPathsRequest], - Awaitable[~.ListAttackPathsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_attack_paths' not in self._stubs: - self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListAttackPaths', - request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, - response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, - ) - return self._stubs['list_attack_paths'] - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - Awaitable[securitycenter_service.ListBigQueryExportsResponse]]: - r"""Return a callable for the list big query exports method over gRPC. - - Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are returned. - - Returns: - Callable[[~.ListBigQueryExportsRequest], - Awaitable[~.ListBigQueryExportsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_big_query_exports' not in self._stubs: - self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListBigQueryExports', - request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, - response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, - ) - return self._stubs['list_big_query_exports'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources for a given location provide a ``-`` - as the source id. If no location is specified, finding are - assumed to be in global. The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - 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.securitycenter.v2.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - Awaitable[securitycenter_service.ListMuteConfigsResponse]]: - r"""Return a callable for the list mute configs method over gRPC. - - Lists mute configs. If no location is specified, - default is global. - - Returns: - Callable[[~.ListMuteConfigsRequest], - Awaitable[~.ListMuteConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_mute_configs' not in self._stubs: - self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListMuteConfigs', - request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, - ) - return self._stubs['list_mute_configs'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - Awaitable[~.ListNotificationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - Awaitable[securitycenter_service.ListResourceValueConfigsResponse]]: - r"""Return a callable for the list resource value configs method over gRPC. - - Lists all ResourceValueConfigs. - - Returns: - Callable[[~.ListResourceValueConfigsRequest], - Awaitable[~.ListResourceValueConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_resource_value_configs' not in self._stubs: - self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListResourceValueConfigs', - request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, - ) - return self._stubs['list_resource_value_configs'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse]]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - Awaitable[securitycenter_service.ListValuedResourcesResponse]]: - r"""Return a callable for the list valued resources method over gRPC. - - Lists the valued resources for a set of simulation - results and filter. - - Returns: - Callable[[~.ListValuedResourcesRequest], - Awaitable[~.ListValuedResourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_valued_resources' not in self._stubs: - self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListValuedResources', - request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, - response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, - ) - return self._stubs['list_valued_resources'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. If no location is - specified, finding is assumed to be in global - - Returns: - Callable[[~.SetFindingStateRequest], - 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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v2.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set mute method over gRPC. - - Updates the mute state of a finding. If no location - is specified, finding is assumed to be in global - - Returns: - Callable[[~.SetMuteRequest], - 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 'set_mute' not in self._stubs: - self._stubs['set_mute'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/SetMute', - request_serializer=securitycenter_service.SetMuteRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_mute'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.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.cloud.securitycenter.v2.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - Awaitable[bigquery_export.BigQueryExport]]: - r"""Return a callable for the update big query export method over gRPC. - - Updates a BigQuery export. - - Returns: - Callable[[~.UpdateBigQueryExportRequest], - Awaitable[~.BigQueryExport]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateBigQueryExport', - request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['update_big_query_export'] - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - Awaitable[gcs_external_system.ExternalSystem]]: - r"""Return a callable for the update external system method over gRPC. - - Updates external system. This is for a given finding. - If no location is specified, finding is assumed to be in - global - - Returns: - Callable[[~.UpdateExternalSystemRequest], - Awaitable[~.ExternalSystem]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_external_system' not in self._stubs: - self._stubs['update_external_system'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateExternalSystem', - request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, - response_deserializer=gcs_external_system.ExternalSystem.deserialize, - ) - return self._stubs['update_external_system'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. If no location is - specified, finding is assumed to be in global. The - corresponding source must exist for a finding creation - to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - 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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - Awaitable[gcs_mute_config.MuteConfig]]: - r"""Return a callable for the update mute config method over gRPC. - - Updates a mute config. If no location is specified, - default is global. - - Returns: - Callable[[~.UpdateMuteConfigRequest], - Awaitable[~.MuteConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateMuteConfig', - request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['update_mute_config'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - Awaitable[gcs_resource_value_config.ResourceValueConfig]]: - r"""Return a callable for the update resource value config method over gRPC. - - Updates an existing ResourceValueConfigs with new - rules. - - Returns: - Callable[[~.UpdateResourceValueConfigRequest], - Awaitable[~.ResourceValueConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: - self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateResourceValueConfig', - request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, - response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['update_resource_value_config'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks]]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. For Finding Security marks, - if no location is specified, finding is assumed to be in - global. Assets Security Marks can only be accessed - through global endpoint. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_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.batch_create_resource_value_configs: gapic_v1.method_async.wrap_method( - self.batch_create_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.bulk_mute_findings: gapic_v1.method_async.wrap_method( - self.bulk_mute_findings, - default_timeout=None, - client_info=client_info, - ), - self.create_big_query_export: gapic_v1.method_async.wrap_method( - self.create_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.create_finding: gapic_v1.method_async.wrap_method( - self.create_finding, - default_timeout=None, - client_info=client_info, - ), - self.create_mute_config: gapic_v1.method_async.wrap_method( - self.create_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method_async.wrap_method( - self.create_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.create_source: gapic_v1.method_async.wrap_method( - self.create_source, - default_timeout=None, - client_info=client_info, - ), - self.delete_big_query_export: gapic_v1.method_async.wrap_method( - self.delete_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.delete_mute_config: gapic_v1.method_async.wrap_method( - self.delete_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method_async.wrap_method( - self.delete_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_resource_value_config: gapic_v1.method_async.wrap_method( - self.delete_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.get_big_query_export: gapic_v1.method_async.wrap_method( - self.get_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.get_simulation: gapic_v1.method_async.wrap_method( - self.get_simulation, - default_timeout=None, - client_info=client_info, - ), - self.get_valued_resource: gapic_v1.method_async.wrap_method( - self.get_valued_resource, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.get_mute_config: gapic_v1.method_async.wrap_method( - self.get_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.get_notification_config: gapic_v1.method_async.wrap_method( - self.get_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.get_resource_value_config: gapic_v1.method_async.wrap_method( - self.get_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.get_source: gapic_v1.method_async.wrap_method( - self.get_source, - default_timeout=None, - client_info=client_info, - ), - self.group_findings: gapic_v1.method_async.wrap_method( - self.group_findings, - default_timeout=None, - client_info=client_info, - ), - self.list_attack_paths: gapic_v1.method_async.wrap_method( - self.list_attack_paths, - default_timeout=None, - client_info=client_info, - ), - self.list_big_query_exports: gapic_v1.method_async.wrap_method( - self.list_big_query_exports, - default_timeout=None, - client_info=client_info, - ), - self.list_findings: gapic_v1.method_async.wrap_method( - self.list_findings, - default_timeout=None, - client_info=client_info, - ), - self.list_mute_configs: gapic_v1.method_async.wrap_method( - self.list_mute_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method_async.wrap_method( - self.list_notification_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_resource_value_configs: gapic_v1.method_async.wrap_method( - self.list_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_sources: gapic_v1.method_async.wrap_method( - self.list_sources, - default_timeout=None, - client_info=client_info, - ), - self.list_valued_resources: gapic_v1.method_async.wrap_method( - self.list_valued_resources, - default_timeout=None, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method_async.wrap_method( - self.set_finding_state, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_mute: gapic_v1.method_async.wrap_method( - self.set_mute, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.update_big_query_export: gapic_v1.method_async.wrap_method( - self.update_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.update_external_system: gapic_v1.method_async.wrap_method( - self.update_external_system, - default_timeout=None, - client_info=client_info, - ), - self.update_finding: gapic_v1.method_async.wrap_method( - self.update_finding, - default_timeout=None, - client_info=client_info, - ), - self.update_mute_config: gapic_v1.method_async.wrap_method( - self.update_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method_async.wrap_method( - self.update_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.update_resource_value_config: gapic_v1.method_async.wrap_method( - self.update_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method_async.wrap_method( - self.update_security_marks, - default_timeout=None, - client_info=client_info, - ), - self.update_source: gapic_v1.method_async.wrap_method( - self.update_source, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - return 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"] - - -__all__ = ( - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py deleted file mode 100644 index 251cc55815bd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py +++ /dev/null @@ -1,5820 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # 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 path_template -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 -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -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.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import valued_resource -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SecurityCenterRestInterceptor: - """Interceptor for SecurityCenter. - - 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 SecurityCenterRestTransport. - - .. code-block:: python - class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): - def pre_batch_create_resource_value_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_create_resource_value_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_bulk_mute_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_bulk_mute_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_big_query_export(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_mute_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_resource_value_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_big_query_export(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_mute_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_resource_value_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_resource_value_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_simulation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_simulation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_valued_resource(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_valued_resource(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_attack_paths(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_attack_paths(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_big_query_exports(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_big_query_exports(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_mute_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_mute_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_notification_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_notification_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_resource_value_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_resource_value_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_sources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_sources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_valued_resources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_valued_resources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_finding_state(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_finding_state(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_mute(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_mute(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_big_query_export(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_external_system(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_external_system(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_mute_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_resource_value_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_resource_value_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_security_marks(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_security_marks(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_source(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) - client = SecurityCenterClient(transport=transport) - - - """ - def pre_batch_create_resource_value_configs(self, request: securitycenter_service.BatchCreateResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BatchCreateResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_create_resource_value_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_batch_create_resource_value_configs(self, response: securitycenter_service.BatchCreateResourceValueConfigsResponse) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - """Post-rpc interceptor for batch_create_resource_value_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_bulk_mute_findings(self, request: securitycenter_service.BulkMuteFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BulkMuteFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for bulk_mute_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_bulk_mute_findings(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for bulk_mute_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_big_query_export(self, request: securitycenter_service.CreateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: - """Post-rpc interceptor for create_big_query_export - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for create_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_mute_config(self, request: securitycenter_service.CreateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: - """Post-rpc interceptor for create_mute_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_notification_config(self, request: securitycenter_service.CreateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: - """Post-rpc interceptor for create_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for create_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_delete_big_query_export(self, request: securitycenter_service.DeleteBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_mute_config(self, request: securitycenter_service.DeleteMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_notification_config(self, request: securitycenter_service.DeleteNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_resource_value_config(self, request: securitycenter_service.DeleteResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteResourceValueConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_resource_value_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_get_big_query_export(self, request: securitycenter_service.GetBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: - """Post-rpc interceptor for get_big_query_export - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_mute_config(self, request: securitycenter_service.GetMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_mute_config(self, response: mute_config.MuteConfig) -> mute_config.MuteConfig: - """Post-rpc interceptor for get_mute_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_notification_config(self, request: securitycenter_service.GetNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_notification_config(self, response: notification_config.NotificationConfig) -> notification_config.NotificationConfig: - """Post-rpc interceptor for get_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_resource_value_config(self, request: securitycenter_service.GetResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetResourceValueConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_resource_value_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_resource_value_config(self, response: resource_value_config.ResourceValueConfig) -> resource_value_config.ResourceValueConfig: - """Post-rpc interceptor for get_resource_value_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_simulation(self, request: securitycenter_service.GetSimulationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSimulationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_simulation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_simulation(self, response: simulation.Simulation) -> simulation.Simulation: - """Post-rpc interceptor for get_simulation - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_source(self, response: source.Source) -> source.Source: - """Post-rpc interceptor for get_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_valued_resource(self, request: securitycenter_service.GetValuedResourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetValuedResourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_valued_resource - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_valued_resource(self, response: valued_resource.ValuedResource) -> valued_resource.ValuedResource: - """Post-rpc interceptor for get_valued_resource - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: - """Post-rpc interceptor for group_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_attack_paths(self, request: securitycenter_service.ListAttackPathsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAttackPathsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_attack_paths - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_attack_paths(self, response: securitycenter_service.ListAttackPathsResponse) -> securitycenter_service.ListAttackPathsResponse: - """Post-rpc interceptor for list_attack_paths - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_big_query_exports(self, request: securitycenter_service.ListBigQueryExportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListBigQueryExportsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_big_query_exports - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_big_query_exports(self, response: securitycenter_service.ListBigQueryExportsResponse) -> securitycenter_service.ListBigQueryExportsResponse: - """Post-rpc interceptor for list_big_query_exports - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. - """ - return request, metadata - - def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: - """Post-rpc interceptor for list_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_mute_configs(self, request: securitycenter_service.ListMuteConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListMuteConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_mute_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_mute_configs(self, response: securitycenter_service.ListMuteConfigsResponse) -> securitycenter_service.ListMuteConfigsResponse: - """Post-rpc interceptor for list_mute_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_notification_configs(self, request: securitycenter_service.ListNotificationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListNotificationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_notification_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_notification_configs(self, response: securitycenter_service.ListNotificationConfigsResponse) -> securitycenter_service.ListNotificationConfigsResponse: - """Post-rpc interceptor for list_notification_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_resource_value_configs(self, request: securitycenter_service.ListResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_resource_value_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_resource_value_configs(self, response: securitycenter_service.ListResourceValueConfigsResponse) -> securitycenter_service.ListResourceValueConfigsResponse: - """Post-rpc interceptor for list_resource_value_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_sources - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: - """Post-rpc interceptor for list_sources - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_valued_resources(self, request: securitycenter_service.ListValuedResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListValuedResourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_valued_resources - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_valued_resources(self, response: securitycenter_service.ListValuedResourcesResponse) -> securitycenter_service.ListValuedResourcesResponse: - """Post-rpc interceptor for list_valued_resources - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_set_mute(self, request: securitycenter_service.SetMuteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetMuteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_mute - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_set_mute(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for set_mute - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_big_query_export(self, request: securitycenter_service.UpdateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: - """Post-rpc interceptor for update_big_query_export - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_external_system(self, request: securitycenter_service.UpdateExternalSystemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateExternalSystemRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_external_system - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_external_system(self, response: gcs_external_system.ExternalSystem) -> gcs_external_system.ExternalSystem: - """Post-rpc interceptor for update_external_system - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for update_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_mute_config(self, request: securitycenter_service.UpdateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: - """Post-rpc interceptor for update_mute_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_notification_config(self, request: securitycenter_service.UpdateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: - """Post-rpc interceptor for update_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_resource_value_config(self, request: securitycenter_service.UpdateResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateResourceValueConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_resource_value_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_resource_value_config(self, response: gcs_resource_value_config.ResourceValueConfig) -> gcs_resource_value_config.ResourceValueConfig: - """Post-rpc interceptor for update_resource_value_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: - """Post-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for update_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SecurityCenterRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SecurityCenterRestInterceptor - - -class SecurityCenterRestTransport(SecurityCenterTransport): - """REST backend transport for SecurityCenter. - - V2 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SecurityCenterRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 - 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 - ) - 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 SecurityCenterRestInterceptor() - 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': '/v2/{name=organizations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2/{name=organizations/*/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="v2") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _BatchCreateResourceValueConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("BatchCreateResourceValueConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.BatchCreateResourceValueConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - r"""Call the batch create resource - value configs method over HTTP. - - Args: - request (~.securitycenter_service.BatchCreateResourceValueConfigsRequest): - The request object. Request message to create multiple - resource value configs - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.BatchCreateResourceValueConfigsResponse: - Response message for - BatchCreateResourceValueConfigs - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*}/resourceValueConfigs:batchCreate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/locations/*}/resourceValueConfigs:batchCreate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_create_resource_value_configs(request, metadata) - pb_request = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.BatchCreateResourceValueConfigsResponse() - pb_resp = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_create_resource_value_configs(resp) - return resp - - class _BulkMuteFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("BulkMuteFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.BulkMuteFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the bulk mute findings method over HTTP. - - Args: - request (~.securitycenter_service.BulkMuteFindingsRequest): - The request object. Request message for bulk findings - update. - Note: - - 1. If multiple bulk update requests - match the same resource, the order - in which they get executed is not - defined. - 2. Once a bulk operation is started, - there is no way to stop it. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/locations/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*/locations/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/findings:bulkMute', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_bulk_mute_findings(request, metadata) - pb_request = securitycenter_service.BulkMuteFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_bulk_mute_findings(resp) - return resp - - class _CreateBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "bigQueryExportId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> bigquery_export.BigQueryExport: - r"""Call the create big query export method over HTTP. - - Args: - request (~.securitycenter_service.CreateBigQueryExportRequest): - The request object. Request message for creating a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.bigquery_export.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/locations/*}/bigQueryExports', - 'body': 'big_query_export', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*/locations/*}/bigQueryExports', - 'body': 'big_query_export', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/bigQueryExports', - 'body': 'big_query_export', - }, - ] - request, metadata = self._interceptor.pre_create_big_query_export(request, metadata) - pb_request = securitycenter_service.CreateBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = bigquery_export.BigQueryExport() - pb_resp = bigquery_export.BigQueryExport.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_big_query_export(resp) - return resp - - class _CreateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "findingId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the create finding method over HTTP. - - Args: - request (~.securitycenter_service.CreateFindingRequest): - The request object. Request message for creating a - finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/sources/*/locations/*}/findings', - 'body': 'finding', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/sources/*}/findings', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_create_finding(request, metadata) - pb_request = securitycenter_service.CreateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_finding(resp) - return resp - - class _CreateMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "muteConfigId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_mute_config.MuteConfig: - r"""Call the create mute config method over HTTP. - - Args: - request (~.securitycenter_service.CreateMuteConfigRequest): - The request object. Request message for creating a mute - config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_mute_config.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/locations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*/locations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*}/muteConfigs', - 'body': 'mute_config', - }, - ] - request, metadata = self._interceptor.pre_create_mute_config(request, metadata) - pb_request = securitycenter_service.CreateMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_mute_config.MuteConfig() - pb_resp = gcs_mute_config.MuteConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_mute_config(resp) - return resp - - class _CreateNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "configId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_notification_config.NotificationConfig: - r"""Call the create notification - config method over HTTP. - - Args: - request (~.securitycenter_service.CreateNotificationConfigRequest): - The request object. Request message for creating a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/locations/*}/notificationConfigs', - 'body': 'notification_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*/locations/*}/notificationConfigs', - 'body': 'notification_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/notificationConfigs', - 'body': 'notification_config', - }, - ] - request, metadata = self._interceptor.pre_create_notification_config(request, metadata) - pb_request = securitycenter_service.CreateNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_notification_config.NotificationConfig() - pb_resp = gcs_notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_notification_config(resp) - return resp - - class _CreateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the create source method over HTTP. - - Args: - request (~.securitycenter_service.CreateSourceRequest): - The request object. Request message for creating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*}/sources', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_create_source(request, metadata) - pb_request = securitycenter_service.CreateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_source(resp) - return resp - - class _DeleteBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete big query export method over HTTP. - - Args: - request (~.securitycenter_service.DeleteBigQueryExportRequest): - The request object. Request message for deleting a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/locations/*/bigQueryExports/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=folders/*/locations/*/bigQueryExports/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/bigQueryExports/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_big_query_export(request, metadata) - pb_request = securitycenter_service.DeleteBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete mute config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteMuteConfigRequest): - The request object. Request message for deleting a mute - config. If no location is specified, - default is global. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=folders/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=folders/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/muteConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_mute_config(request, metadata) - pb_request = securitycenter_service.DeleteMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete notification - config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteNotificationConfigRequest): - The request object. Request message for deleting a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/locations/*/notificationConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=folders/*/locations/*/notificationConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/notificationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_notification_config(request, metadata) - pb_request = securitycenter_service.DeleteNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteResourceValueConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteResourceValueConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteResourceValueConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete resource value - config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteResourceValueConfigRequest): - The request object. Request message to delete resource - value config - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/resourceValueConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/locations/*/resourceValueConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_resource_value_config(request, metadata) - pb_request = securitycenter_service.DeleteResourceValueConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _GetBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("GetBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> bigquery_export.BigQueryExport: - r"""Call the get big query export method over HTTP. - - Args: - request (~.securitycenter_service.GetBigQueryExportRequest): - The request object. Request message for retrieving a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.bigquery_export.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/locations/*/bigQueryExports/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=folders/*/locations/*/bigQueryExports/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/bigQueryExports/*}', - }, - ] - request, metadata = self._interceptor.pre_get_big_query_export(request, metadata) - pb_request = securitycenter_service.GetBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = bigquery_export.BigQueryExport() - pb_resp = bigquery_export.BigQueryExport.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_big_query_export(resp) - return resp - - class _GetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{resource=organizations/*/sources/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _GetMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> mute_config.MuteConfig: - r"""Call the get mute config method over HTTP. - - Args: - request (~.securitycenter_service.GetMuteConfigRequest): - The request object. Request message for retrieving a mute - config. If no location is specified, - default is global. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.mute_config.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=folders/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=folders/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/muteConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_mute_config(request, metadata) - pb_request = securitycenter_service.GetMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = mute_config.MuteConfig() - pb_resp = mute_config.MuteConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_mute_config(resp) - return resp - - class _GetNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> notification_config.NotificationConfig: - r"""Call the get notification config method over HTTP. - - Args: - request (~.securitycenter_service.GetNotificationConfigRequest): - The request object. Request message for getting a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/locations/*/notificationConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=folders/*/locations/*/notificationConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/notificationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_notification_config(request, metadata) - pb_request = securitycenter_service.GetNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = notification_config.NotificationConfig() - pb_resp = notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_notification_config(resp) - return resp - - class _GetResourceValueConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetResourceValueConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetResourceValueConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resource_value_config.ResourceValueConfig: - r"""Call the get resource value config method over HTTP. - - Args: - request (~.securitycenter_service.GetResourceValueConfigRequest): - The request object. Request message to get resource value - config - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resource_value_config.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/resourceValueConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/locations/*/resourceValueConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_resource_value_config(request, metadata) - pb_request = securitycenter_service.GetResourceValueConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resource_value_config.ResourceValueConfig() - pb_resp = resource_value_config.ResourceValueConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_resource_value_config(resp) - return resp - - class _GetSimulation(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSimulation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSimulationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> simulation.Simulation: - r"""Call the get simulation method over HTTP. - - Args: - request (~.securitycenter_service.GetSimulationRequest): - The request object. Request message for getting - simulation. Simulation name can include - "latest" to retrieve the latest - simulation For example, - "organizations/123/simulations/latest". - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.simulation.Simulation: - Attack path simulation - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/simulations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/locations/*/simulations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_simulation(request, metadata) - pb_request = securitycenter_service.GetSimulationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = simulation.Simulation() - pb_resp = simulation.Simulation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_simulation(resp) - return resp - - class _GetSource(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> source.Source: - r"""Call the get source method over HTTP. - - Args: - request (~.securitycenter_service.GetSourceRequest): - The request object. Request message for getting a source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/sources/*}', - }, - ] - request, metadata = self._interceptor.pre_get_source(request, metadata) - pb_request = securitycenter_service.GetSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = source.Source() - pb_resp = source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_source(resp) - return resp - - class _GetValuedResource(SecurityCenterRestStub): - def __hash__(self): - return hash("GetValuedResource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetValuedResourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> valued_resource.ValuedResource: - r"""Call the get valued resource method over HTTP. - - Args: - request (~.securitycenter_service.GetValuedResourceRequest): - The request object. Request message for getting a valued - resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.valued_resource.ValuedResource: - A resource that is determined to have - value to a user's system - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/simulations/*/valuedResources/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/locations/*/simulations/*/valuedResources/*}', - }, - ] - request, metadata = self._interceptor.pre_get_valued_resource(request, metadata) - pb_request = securitycenter_service.GetValuedResourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = valued_resource.ValuedResource() - pb_resp = valued_resource.ValuedResource.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_valued_resource(resp) - return resp - - class _GroupFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupFindingsResponse: - r"""Call the group findings method over HTTP. - - Args: - request (~.securitycenter_service.GroupFindingsRequest): - The request object. Request message for grouping by - findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupFindingsResponse: - Response message for group by - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/sources/*/locations/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*/sources/*/locations/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/sources/*/locations/*}/findings:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_findings(request, metadata) - pb_request = securitycenter_service.GroupFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupFindingsResponse() - pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_findings(resp) - return resp - - class _ListAttackPaths(SecurityCenterRestStub): - def __hash__(self): - return hash("ListAttackPaths") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListAttackPathsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListAttackPathsResponse: - r"""Call the list attack paths method over HTTP. - - Args: - request (~.securitycenter_service.ListAttackPathsRequest): - The request object. Request message for listing the - attack paths for a given simulation or - valued resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListAttackPathsResponse: - Response message for listing the - attack paths for a given simulation or - valued resource. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/simulations/*}/attackPaths', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/simulations/*/valuedResources/*}/attackPaths', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/locations/*/simulations/*/valuedResources/*}/attackPaths', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/simulations/*/attackExposureResults/*}/attackPaths', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/locations/*/simulations/*/attackExposureResults/*}/attackPaths', - }, - ] - request, metadata = self._interceptor.pre_list_attack_paths(request, metadata) - pb_request = securitycenter_service.ListAttackPathsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListAttackPathsResponse() - pb_resp = securitycenter_service.ListAttackPathsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_attack_paths(resp) - return resp - - class _ListBigQueryExports(SecurityCenterRestStub): - def __hash__(self): - return hash("ListBigQueryExports") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListBigQueryExportsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListBigQueryExportsResponse: - r"""Call the list big query exports method over HTTP. - - Args: - request (~.securitycenter_service.ListBigQueryExportsRequest): - The request object. Request message for listing BigQuery - exports at a given scope e.g. - organization, folder or 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: - ~.securitycenter_service.ListBigQueryExportsResponse: - Response message for listing BigQuery - exports. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/locations/*}/bigQueryExports', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*/locations/*}/bigQueryExports', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/bigQueryExports', - }, - ] - request, metadata = self._interceptor.pre_list_big_query_exports(request, metadata) - pb_request = securitycenter_service.ListBigQueryExportsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListBigQueryExportsResponse() - pb_resp = securitycenter_service.ListBigQueryExportsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_big_query_exports(resp) - return resp - - class _ListFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("ListFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListFindingsResponse: - r"""Call the list findings method over HTTP. - - Args: - request (~.securitycenter_service.ListFindingsRequest): - The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListFindingsResponse: - Response message for listing - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/sources/*/locations/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*/sources/*/locations/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/sources/*/locations/*}/findings', - }, - ] - request, metadata = self._interceptor.pre_list_findings(request, metadata) - pb_request = securitycenter_service.ListFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListFindingsResponse() - pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_findings(resp) - return resp - - class _ListMuteConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListMuteConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListMuteConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListMuteConfigsResponse: - r"""Call the list mute configs method over HTTP. - - Args: - request (~.securitycenter_service.ListMuteConfigsRequest): - The request object. Request message for listing mute - configs at a given scope e.g. - organization, folder or project. If no - location is specified, default is - global. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListMuteConfigsResponse: - Response message for listing mute - configs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/locations/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*/locations/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/muteConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_mute_configs(request, metadata) - pb_request = securitycenter_service.ListMuteConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListMuteConfigsResponse() - pb_resp = securitycenter_service.ListMuteConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_mute_configs(resp) - return resp - - class _ListNotificationConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListNotificationConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListNotificationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListNotificationConfigsResponse: - r"""Call the list notification configs method over HTTP. - - Args: - request (~.securitycenter_service.ListNotificationConfigsRequest): - The request object. Request message for listing - notification configs. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListNotificationConfigsResponse: - Response message for listing - notification configs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/locations/*}/notificationConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*/locations/*}/notificationConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/notificationConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_notification_configs(request, metadata) - pb_request = securitycenter_service.ListNotificationConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListNotificationConfigsResponse() - pb_resp = securitycenter_service.ListNotificationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_notification_configs(resp) - return resp - - class _ListResourceValueConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListResourceValueConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListResourceValueConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListResourceValueConfigsResponse: - r"""Call the list resource value - configs method over HTTP. - - Args: - request (~.securitycenter_service.ListResourceValueConfigsRequest): - The request object. Request message to list resource - value configs of a parent - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListResourceValueConfigsResponse: - Response message to list resource - value configs - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*}/resourceValueConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/locations/*}/resourceValueConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_resource_value_configs(request, metadata) - pb_request = securitycenter_service.ListResourceValueConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListResourceValueConfigsResponse() - pb_resp = securitycenter_service.ListResourceValueConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_resource_value_configs(resp) - return resp - - class _ListSources(SecurityCenterRestStub): - def __hash__(self): - return hash("ListSources") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListSourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListSourcesResponse: - r"""Call the list sources method over HTTP. - - Args: - request (~.securitycenter_service.ListSourcesRequest): - The request object. Request message for listing sources. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListSourcesResponse: - Response message for listing sources. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*}/sources', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*}/sources', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*}/sources', - }, - ] - request, metadata = self._interceptor.pre_list_sources(request, metadata) - pb_request = securitycenter_service.ListSourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListSourcesResponse() - pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_sources(resp) - return resp - - class _ListValuedResources(SecurityCenterRestStub): - def __hash__(self): - return hash("ListValuedResources") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListValuedResourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListValuedResourcesResponse: - r"""Call the list valued resources method over HTTP. - - Args: - request (~.securitycenter_service.ListValuedResourcesRequest): - The request object. Request message for listing the - valued resources for a given simulation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListValuedResourcesResponse: - Response message for listing the - valued resources for a given simulation. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/simulations/*}/valuedResources', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/simulations/*/attackExposureResults/*}/valuedResources', - }, - ] - request, metadata = self._interceptor.pre_list_valued_resources(request, metadata) - pb_request = securitycenter_service.ListValuedResourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListValuedResourcesResponse() - pb_resp = securitycenter_service.ListValuedResourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_valued_resources(resp) - return resp - - class _SetFindingState(SecurityCenterRestStub): - def __hash__(self): - return hash("SetFindingState") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SetFindingStateRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the set finding state method over HTTP. - - Args: - request (~.securitycenter_service.SetFindingStateRequest): - The request object. Request message for updating a - finding's state. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=organizations/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=organizations/*/sources/*/locations/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=folders/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=folders/*/sources/*/locations/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/sources/*/locations/*/findings/*}:setState', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_finding_state(request, metadata) - pb_request = securitycenter_service.SetFindingStateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_set_finding_state(resp) - return resp - - class _SetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{resource=organizations/*/sources/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _SetMute(SecurityCenterRestStub): - def __hash__(self): - return hash("SetMute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SetMuteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the set mute method over HTTP. - - Args: - request (~.securitycenter_service.SetMuteRequest): - The request object. Request message for updating a - finding's mute status. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=organizations/*/sources/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=organizations/*/sources/*/locations/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=folders/*/sources/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=folders/*/sources/*/locations/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/sources/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/sources/*/locations/*/findings/*}:setMute', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_mute(request, metadata) - pb_request = securitycenter_service.SetMuteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_set_mute(resp) - return resp - - class _TestIamPermissions(SecurityCenterRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{resource=organizations/*/sources/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UpdateBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> bigquery_export.BigQueryExport: - r"""Call the update big query export method over HTTP. - - Args: - request (~.securitycenter_service.UpdateBigQueryExportRequest): - The request object. Request message for updating a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.bigquery_export.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{big_query_export.name=organizations/*/locations/*/bigQueryExports/*}', - 'body': 'big_query_export', - }, -{ - 'method': 'patch', - 'uri': '/v2/{big_query_export.name=folders/*/locations/*/bigQueryExports/*}', - 'body': 'big_query_export', - }, -{ - 'method': 'patch', - 'uri': '/v2/{big_query_export.name=projects/*/locations/*/bigQueryExports/*}', - 'body': 'big_query_export', - }, - ] - request, metadata = self._interceptor.pre_update_big_query_export(request, metadata) - pb_request = securitycenter_service.UpdateBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = bigquery_export.BigQueryExport() - pb_resp = bigquery_export.BigQueryExport.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_big_query_export(resp) - return resp - - class _UpdateExternalSystem(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateExternalSystem") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateExternalSystemRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_external_system.ExternalSystem: - r"""Call the update external system method over HTTP. - - Args: - request (~.securitycenter_service.UpdateExternalSystemRequest): - The request object. Request message for updating a - ExternalSystem resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_external_system.ExternalSystem: - Representation of third party - SIEM/SOAR fields within SCC. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v2/{external_system.name=organizations/*/sources/*/locations/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v2/{external_system.name=folders/*/sources/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v2/{external_system.name=folders/*/sources/*/locations/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v2/{external_system.name=projects/*/sources/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v2/{external_system.name=projects/*/sources/*/locations/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, - ] - request, metadata = self._interceptor.pre_update_external_system(request, metadata) - pb_request = securitycenter_service.UpdateExternalSystemRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_external_system.ExternalSystem() - pb_resp = gcs_external_system.ExternalSystem.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_external_system(resp) - return resp - - class _UpdateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the update finding method over HTTP. - - Args: - request (~.securitycenter_service.UpdateFindingRequest): - The request object. Request message for updating or - creating a finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{finding.name=organizations/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v2/{finding.name=organizations/*/sources/*/locations/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v2/{finding.name=folders/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v2/{finding.name=folders/*/sources/*/locations/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v2/{finding.name=projects/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v2/{finding.name=projects/*/sources/*/locations/*/findings/*}', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_update_finding(request, metadata) - pb_request = securitycenter_service.UpdateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_finding(resp) - return resp - - class _UpdateMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_mute_config.MuteConfig: - r"""Call the update mute config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateMuteConfigRequest): - The request object. Request message for updating a mute - config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_mute_config.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{mute_config.name=organizations/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{mute_config.name=organizations/*/locations/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{mute_config.name=folders/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{mute_config.name=folders/*/locations/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{mute_config.name=projects/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{mute_config.name=projects/*/locations/*/muteConfigs/*}', - 'body': 'mute_config', - }, - ] - request, metadata = self._interceptor.pre_update_mute_config(request, metadata) - pb_request = securitycenter_service.UpdateMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_mute_config.MuteConfig() - pb_resp = gcs_mute_config.MuteConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_mute_config(resp) - return resp - - class _UpdateNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_notification_config.NotificationConfig: - r"""Call the update notification - config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateNotificationConfigRequest): - The request object. Request message for updating a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{notification_config.name=organizations/*/locations/*/notificationConfigs/*}', - 'body': 'notification_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{notification_config.name=folders/*/locations/*/notificationConfigs/*}', - 'body': 'notification_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{notification_config.name=projects/*/locations/*/notificationConfigs/*}', - 'body': 'notification_config', - }, - ] - request, metadata = self._interceptor.pre_update_notification_config(request, metadata) - pb_request = securitycenter_service.UpdateNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_notification_config.NotificationConfig() - pb_resp = gcs_notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_notification_config(resp) - return resp - - class _UpdateResourceValueConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateResourceValueConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateResourceValueConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_resource_value_config.ResourceValueConfig: - r"""Call the update resource value - config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateResourceValueConfigRequest): - The request object. Request message to update resource - value config - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_resource_value_config.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{resource_value_config.name=organizations/*/resourceValueConfigs/*}', - 'body': 'resource_value_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{resource_value_config.name=organizations/*/locations/*/resourceValueConfigs/*}', - 'body': 'resource_value_config', - }, - ] - request, metadata = self._interceptor.pre_update_resource_value_config(request, metadata) - pb_request = securitycenter_service.UpdateResourceValueConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_resource_value_config.ResourceValueConfig() - pb_resp = gcs_resource_value_config.ResourceValueConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_resource_value_config(resp) - return resp - - class _UpdateSecurityMarks(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSecurityMarks") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSecurityMarksRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_security_marks.SecurityMarks: - r"""Call the update security marks method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSecurityMarksRequest): - The request object. Request message for updating a - SecurityMarks resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=organizations/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=organizations/*/sources/*/locations/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=folders/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=folders/*/sources/*/locations/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=projects/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=projects/*/sources/*/locations/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, - ] - request, metadata = self._interceptor.pre_update_security_marks(request, metadata) - pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_security_marks.SecurityMarks() - pb_resp = gcs_security_marks.SecurityMarks.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_security_marks(resp) - return resp - - class _UpdateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the update source method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSourceRequest): - The request object. Request message for updating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{source.name=organizations/*/sources/*}', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_update_source(request, metadata) - pb_request = securitycenter_service.UpdateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_source(resp) - return resp - - @property - def batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - securitycenter_service.BatchCreateResourceValueConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchCreateResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - 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._BulkMuteFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - 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._DeleteBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - 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._DeleteMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - 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._DeleteNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - 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._DeleteResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - bigquery_export.BigQueryExport]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - mute_config.MuteConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - resource_value_config.ResourceValueConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - simulation.Simulation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSimulation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - valued_resource.ValuedResource]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetValuedResource(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - securitycenter_service.ListAttackPathsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListAttackPaths(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - securitycenter_service.ListBigQueryExportsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListBigQueryExports(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.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_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - securitycenter_service.ListMuteConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListMuteConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListNotificationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - securitycenter_service.ListResourceValueConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSources(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - securitycenter_service.ListValuedResourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListValuedResources(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - 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._SetMute(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - gcs_external_system.ExternalSystem]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateExternalSystem(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - gcs_resource_value_config.ResourceValueConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=organizations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In 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(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In 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(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), 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(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/operations}', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SecurityCenterRestTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.py deleted file mode 100644 index bb1db5459f13..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.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. -# -from .access import ( - Access, - Geolocation, - ServiceAccountDelegationInfo, -) -from .application import ( - Application, -) -from .attack_exposure import ( - AttackExposure, -) -from .attack_path import ( - AttackPath, -) -from .backup_disaster_recovery import ( - BackupDisasterRecovery, -) -from .bigquery_export import ( - BigQueryExport, -) -from .cloud_armor import ( - AdaptiveProtection, - Attack, - CloudArmor, - Requests, - SecurityPolicy, -) -from .cloud_dlp_data_profile import ( - CloudDlpDataProfile, -) -from .cloud_dlp_inspection import ( - CloudDlpInspection, -) -from .compliance import ( - Compliance, -) -from .connection import ( - Connection, -) -from .contact_details import ( - Contact, - ContactDetails, -) -from .container import ( - Container, -) -from .database import ( - Database, -) -from .exfiltration import ( - ExfilResource, - Exfiltration, -) -from .external_system import ( - ExternalSystem, -) -from .file import ( - File, -) -from .finding import ( - Finding, -) -from .folder import ( - Folder, -) -from .group_membership import ( - GroupMembership, -) -from .iam_binding import ( - IamBinding, -) -from .indicator import ( - Indicator, -) -from .kernel_rootkit import ( - KernelRootkit, -) -from .kubernetes import ( - Kubernetes, -) -from .label import ( - Label, -) -from .load_balancer import ( - LoadBalancer, -) -from .log_entry import ( - CloudLoggingEntry, - LogEntry, -) -from .mitre_attack import ( - MitreAttack, -) -from .mute_config import ( - MuteConfig, -) -from .notebook import ( - Notebook, -) -from .notification_config import ( - NotificationConfig, -) -from .notification_message import ( - NotificationMessage, -) -from .org_policy import ( - OrgPolicy, -) -from .process import ( - EnvironmentVariable, - Process, -) -from .resource import ( - AwsMetadata, - AzureMetadata, - GcpMetadata, - Resource, - ResourcePath, - CloudProvider, -) -from .resource_value_config import ( - ResourceValueConfig, - ResourceValue, -) -from .security_marks import ( - SecurityMarks, -) -from .security_posture import ( - SecurityPosture, -) -from .securitycenter_service import ( - BatchCreateResourceValueConfigsRequest, - BatchCreateResourceValueConfigsResponse, - BulkMuteFindingsRequest, - BulkMuteFindingsResponse, - CreateBigQueryExportRequest, - CreateFindingRequest, - CreateMuteConfigRequest, - CreateNotificationConfigRequest, - CreateResourceValueConfigRequest, - CreateSourceRequest, - DeleteBigQueryExportRequest, - DeleteMuteConfigRequest, - DeleteNotificationConfigRequest, - DeleteResourceValueConfigRequest, - GetBigQueryExportRequest, - GetMuteConfigRequest, - GetNotificationConfigRequest, - GetResourceValueConfigRequest, - GetSimulationRequest, - GetSourceRequest, - GetValuedResourceRequest, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListAttackPathsRequest, - ListAttackPathsResponse, - ListBigQueryExportsRequest, - ListBigQueryExportsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListMuteConfigsRequest, - ListMuteConfigsResponse, - ListNotificationConfigsRequest, - ListNotificationConfigsResponse, - ListResourceValueConfigsRequest, - ListResourceValueConfigsResponse, - ListSourcesRequest, - ListSourcesResponse, - ListValuedResourcesRequest, - ListValuedResourcesResponse, - SetFindingStateRequest, - SetMuteRequest, - UpdateBigQueryExportRequest, - UpdateExternalSystemRequest, - UpdateFindingRequest, - UpdateMuteConfigRequest, - UpdateNotificationConfigRequest, - UpdateResourceValueConfigRequest, - UpdateSecurityMarksRequest, - UpdateSourceRequest, -) -from .simulation import ( - Simulation, -) -from .source import ( - Source, -) -from .toxic_combination import ( - ToxicCombination, -) -from .valued_resource import ( - ResourceValueConfigMetadata, - ValuedResource, -) -from .vulnerability import ( - Cve, - Cvssv3, - Package, - Reference, - SecurityBulletin, - Vulnerability, -) - -__all__ = ( - 'Access', - 'Geolocation', - 'ServiceAccountDelegationInfo', - 'Application', - 'AttackExposure', - 'AttackPath', - 'BackupDisasterRecovery', - 'BigQueryExport', - 'AdaptiveProtection', - 'Attack', - 'CloudArmor', - 'Requests', - 'SecurityPolicy', - 'CloudDlpDataProfile', - 'CloudDlpInspection', - 'Compliance', - 'Connection', - 'Contact', - 'ContactDetails', - 'Container', - 'Database', - 'ExfilResource', - 'Exfiltration', - 'ExternalSystem', - 'File', - 'Finding', - 'Folder', - 'GroupMembership', - 'IamBinding', - 'Indicator', - 'KernelRootkit', - 'Kubernetes', - 'Label', - 'LoadBalancer', - 'CloudLoggingEntry', - 'LogEntry', - 'MitreAttack', - 'MuteConfig', - 'Notebook', - 'NotificationConfig', - 'NotificationMessage', - 'OrgPolicy', - 'EnvironmentVariable', - 'Process', - 'AwsMetadata', - 'AzureMetadata', - 'GcpMetadata', - 'Resource', - 'ResourcePath', - 'CloudProvider', - 'ResourceValueConfig', - 'ResourceValue', - 'SecurityMarks', - 'SecurityPosture', - 'BatchCreateResourceValueConfigsRequest', - 'BatchCreateResourceValueConfigsResponse', - 'BulkMuteFindingsRequest', - 'BulkMuteFindingsResponse', - 'CreateBigQueryExportRequest', - 'CreateFindingRequest', - 'CreateMuteConfigRequest', - 'CreateNotificationConfigRequest', - 'CreateResourceValueConfigRequest', - 'CreateSourceRequest', - 'DeleteBigQueryExportRequest', - 'DeleteMuteConfigRequest', - 'DeleteNotificationConfigRequest', - 'DeleteResourceValueConfigRequest', - 'GetBigQueryExportRequest', - 'GetMuteConfigRequest', - 'GetNotificationConfigRequest', - 'GetResourceValueConfigRequest', - 'GetSimulationRequest', - 'GetSourceRequest', - 'GetValuedResourceRequest', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAttackPathsRequest', - 'ListAttackPathsResponse', - 'ListBigQueryExportsRequest', - 'ListBigQueryExportsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListMuteConfigsRequest', - 'ListMuteConfigsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListResourceValueConfigsRequest', - 'ListResourceValueConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListValuedResourcesRequest', - 'ListValuedResourcesResponse', - 'SetFindingStateRequest', - 'SetMuteRequest', - 'UpdateBigQueryExportRequest', - 'UpdateExternalSystemRequest', - 'UpdateFindingRequest', - 'UpdateMuteConfigRequest', - 'UpdateNotificationConfigRequest', - 'UpdateResourceValueConfigRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Simulation', - 'Source', - 'ToxicCombination', - 'ResourceValueConfigMetadata', - 'ValuedResource', - 'Cve', - 'Cvssv3', - 'Package', - 'Reference', - 'SecurityBulletin', - 'Vulnerability', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py deleted file mode 100644 index e617c4170012..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py +++ /dev/null @@ -1,193 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v2', - manifest={ - 'Access', - 'ServiceAccountDelegationInfo', - 'Geolocation', - }, -) - - -class Access(proto.Message): - r"""Represents an access event. - - Attributes: - principal_email (str): - Associated email, such as "foo@google.com". - - The email address of the authenticated user or a service - account acting on behalf of a third party principal making - the request. For third party identity callers, the - ``principal_subject`` field is populated instead of this - field. For privacy reasons, the principal email address is - sometimes redacted. For more information, see `Caller - identities in audit - logs `__. - caller_ip (str): - Caller's IP address, such as "1.1.1.1". - caller_ip_geo (google.cloud.securitycenter_v2.types.Geolocation): - The caller IP's geolocation, which identifies - where the call came from. - user_agent_family (str): - Type of user agent associated with the - finding. For example, an operating system shell - or an embedded or standalone application. - user_agent (str): - The caller's user agent string associated - with the finding. - service_name (str): - This is the API service that the service - account made a call to, e.g. - "iam.googleapis.com". - method_name (str): - The method that the service account called, - e.g. "SetIamPolicy". - principal_subject (str): - A string that represents the principal_subject that is - associated with the identity. Unlike ``principal_email``, - ``principal_subject`` supports principals that aren't - associated with email addresses, such as third party - principals. For most identities, the format is - ``principal://iam.googleapis.com/{identity pool name}/subject/{subject}``. - Some GKE identities, such as GKE_WORKLOAD, FREEFORM, and - GKE_HUB_WORKLOAD, still use the legacy format - ``serviceAccount:{identity pool name}[{subject}]``. - service_account_key_name (str): - The name of the service account key that was used to create - or exchange credentials when authenticating the service - account that made the request. This is a scheme-less URI - full resource name. For example: - - "//iam.googleapis.com/projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}". - service_account_delegation_info (MutableSequence[google.cloud.securitycenter_v2.types.ServiceAccountDelegationInfo]): - The identity delegation history of an authenticated service - account that made the request. The - ``serviceAccountDelegationInfo[]`` object contains - information about the real authorities that try to access - Google Cloud resources by delegating on a service account. - When multiple authorities are present, they are guaranteed - to be sorted based on the original ordering of the identity - delegation events. - user_name (str): - A string that represents a username. The - username provided depends on the type of the - finding and is likely not an IAM principal. For - example, this can be a system username if the - finding is related to a virtual machine, or it - can be an application login username. - """ - - principal_email: str = proto.Field( - proto.STRING, - number=1, - ) - caller_ip: str = proto.Field( - proto.STRING, - number=2, - ) - caller_ip_geo: 'Geolocation' = proto.Field( - proto.MESSAGE, - number=3, - message='Geolocation', - ) - user_agent_family: str = proto.Field( - proto.STRING, - number=4, - ) - user_agent: str = proto.Field( - proto.STRING, - number=5, - ) - service_name: str = proto.Field( - proto.STRING, - number=6, - ) - method_name: str = proto.Field( - proto.STRING, - number=7, - ) - principal_subject: str = proto.Field( - proto.STRING, - number=8, - ) - service_account_key_name: str = proto.Field( - proto.STRING, - number=9, - ) - service_account_delegation_info: MutableSequence['ServiceAccountDelegationInfo'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='ServiceAccountDelegationInfo', - ) - user_name: str = proto.Field( - proto.STRING, - number=11, - ) - - -class ServiceAccountDelegationInfo(proto.Message): - r"""Identity delegation history of an authenticated service - account. - - Attributes: - principal_email (str): - The email address of a Google account. - principal_subject (str): - A string representing the principal_subject associated with - the identity. As compared to ``principal_email``, supports - principals that aren't associated with email addresses, such - as third party principals. For most identities, the format - will be - ``principal://iam.googleapis.com/{identity pool name}/subjects/{subject}`` - except for some GKE identities (GKE_WORKLOAD, FREEFORM, - GKE_HUB_WORKLOAD) that are still in the legacy format - ``serviceAccount:{identity pool name}[{subject}]`` - """ - - principal_email: str = proto.Field( - proto.STRING, - number=1, - ) - principal_subject: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Geolocation(proto.Message): - r"""Represents a geographical location for a given access. - - Attributes: - region_code (str): - A CLDR. - """ - - region_code: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.py deleted file mode 100644 index b77f5993987b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Application', - }, -) - - -class Application(proto.Message): - r"""Represents an application associated with a finding. - - Attributes: - base_uri (str): - The base URI that identifies the network location of the - application in which the vulnerability was detected. For - example, ``http://example.com``. - full_uri (str): - The full URI with payload that could be used to reproduce - the vulnerability. For example, - ``http://example.com?p=aMmYgI6H``. - """ - - base_uri: str = proto.Field( - proto.STRING, - number=1, - ) - full_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.py deleted file mode 100644 index 600d1a66d91e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'AttackExposure', - }, -) - - -class AttackExposure(proto.Message): - r"""An attack exposure contains the results of an attack path - simulation run. - - Attributes: - score (float): - A number between 0 (inclusive) and infinity - that represents how important this finding is to - remediate. The higher the score, the more - important it is to remediate. - latest_calculation_time (google.protobuf.timestamp_pb2.Timestamp): - The most recent time the attack exposure was - updated on this finding. - attack_exposure_result (str): - The resource name of the attack path simulation result that - contains the details regarding this attack exposure score. - Example: - ``organizations/123/simulations/456/attackExposureResults/789`` - state (google.cloud.securitycenter_v2.types.AttackExposure.State): - Output only. What state this AttackExposure - is in. This captures whether or not an attack - exposure has been calculated or not. - exposed_high_value_resources_count (int): - The number of high value resources that are - exposed as a result of this finding. - exposed_medium_value_resources_count (int): - The number of medium value resources that are - exposed as a result of this finding. - exposed_low_value_resources_count (int): - The number of high value resources that are - exposed as a result of this finding. - """ - class State(proto.Enum): - r"""This enum defines the various states an AttackExposure can be - in. - - Values: - STATE_UNSPECIFIED (0): - The state is not specified. - CALCULATED (1): - The attack exposure has been calculated. - NOT_CALCULATED (2): - The attack exposure has not been calculated. - """ - STATE_UNSPECIFIED = 0 - CALCULATED = 1 - NOT_CALCULATED = 2 - - score: float = proto.Field( - proto.DOUBLE, - number=1, - ) - latest_calculation_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - attack_exposure_result: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - exposed_high_value_resources_count: int = proto.Field( - proto.INT32, - number=5, - ) - exposed_medium_value_resources_count: int = proto.Field( - proto.INT32, - number=6, - ) - exposed_low_value_resources_count: int = proto.Field( - proto.INT32, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py deleted file mode 100644 index 433afe1a5eee..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v2', - manifest={ - 'AttackPath', - }, -) - - -class AttackPath(proto.Message): - r"""A path that an attacker could take to reach an exposed - resource. - - Attributes: - name (str): - The attack path name, for example, - ``organizations/12/simulations/34/valuedResources/56/attackPaths/78`` - path_nodes (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode]): - A list of nodes that exist in this attack - path. - edges (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathEdge]): - A list of the edges between nodes in this - attack path. - """ - - class AttackPathNode(proto.Message): - r"""Represents one point that an attacker passes through in this - attack path. - - Attributes: - resource (str): - The name of the resource at this point in the attack path. - The format of the name follows the Cloud Asset Inventory - `resource name - format `__ - resource_type (str): - The `supported resource - type `__ - display_name (str): - Human-readable name of this resource. - associated_findings (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.PathNodeAssociatedFinding]): - The findings associated with this node in the - attack path. - uuid (str): - Unique id of the attack path node. - attack_steps (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.AttackStepNode]): - A list of attack step nodes that exist in - this attack path node. - """ - class NodeType(proto.Enum): - r"""The type of the incoming attack step node. - - Values: - NODE_TYPE_UNSPECIFIED (0): - Type not specified - NODE_TYPE_AND (1): - Incoming edge joined with AND - NODE_TYPE_OR (2): - Incoming edge joined with OR - NODE_TYPE_DEFENSE (3): - Incoming edge is defense - NODE_TYPE_ATTACKER (4): - Incoming edge is attacker - """ - NODE_TYPE_UNSPECIFIED = 0 - NODE_TYPE_AND = 1 - NODE_TYPE_OR = 2 - NODE_TYPE_DEFENSE = 3 - NODE_TYPE_ATTACKER = 4 - - class PathNodeAssociatedFinding(proto.Message): - r"""A finding that is associated with this node in the attack - path. - - Attributes: - canonical_finding (str): - Canonical name of the associated findings. Example: - ``organizations/123/sources/456/findings/789`` - finding_category (str): - The additional taxonomy group within findings - from a given source. - name (str): - Full resource name of the finding. - """ - - canonical_finding: str = proto.Field( - proto.STRING, - number=1, - ) - finding_category: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - class AttackStepNode(proto.Message): - r"""Detailed steps the attack can take between path nodes. - - Attributes: - uuid (str): - Unique ID for one Node - type_ (google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.NodeType): - Attack step type. Can be either AND, OR or - DEFENSE - display_name (str): - User friendly name of the attack step - labels (MutableMapping[str, str]): - Attack step labels for metadata - description (str): - Attack step description - """ - - uuid: str = proto.Field( - proto.STRING, - number=1, - ) - type_: 'AttackPath.AttackPathNode.NodeType' = proto.Field( - proto.ENUM, - number=2, - enum='AttackPath.AttackPathNode.NodeType', - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - description: str = proto.Field( - proto.STRING, - number=5, - ) - - resource: str = proto.Field( - proto.STRING, - number=1, - ) - resource_type: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - associated_findings: MutableSequence['AttackPath.AttackPathNode.PathNodeAssociatedFinding'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='AttackPath.AttackPathNode.PathNodeAssociatedFinding', - ) - uuid: str = proto.Field( - proto.STRING, - number=5, - ) - attack_steps: MutableSequence['AttackPath.AttackPathNode.AttackStepNode'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='AttackPath.AttackPathNode.AttackStepNode', - ) - - class AttackPathEdge(proto.Message): - r"""Represents a connection between a source node and a - destination node in this attack path. - - Attributes: - source (str): - The attack node uuid of the source node. - destination (str): - The attack node uuid of the destination node. - """ - - source: str = proto.Field( - proto.STRING, - number=1, - ) - destination: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - path_nodes: MutableSequence[AttackPathNode] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=AttackPathNode, - ) - edges: MutableSequence[AttackPathEdge] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=AttackPathEdge, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py deleted file mode 100644 index 0c1d44505179..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py +++ /dev/null @@ -1,137 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v2', - manifest={ - 'BackupDisasterRecovery', - }, -) - - -class BackupDisasterRecovery(proto.Message): - r"""Information related to Google Cloud Backup and DR Service - findings. - - Attributes: - backup_template (str): - The name of a Backup and DR template which comprises one or - more backup policies. See the `Backup and DR - documentation `__ - for more information. For example, ``snap-ov``. - policies (MutableSequence[str]): - The names of Backup and DR policies that are associated with - a template and that define when to run a backup, how - frequently to run a backup, and how long to retain the - backup image. For example, ``onvaults``. - host (str): - The name of a Backup and DR host, which is managed by the - backup and recovery appliance and known to the management - console. The host can be of type Generic (for example, - Compute Engine, SQL Server, Oracle DB, SMB file system, - etc.), vCenter, or an ESX server. See the `Backup and DR - documentation on - hosts `__ - for more information. For example, ``centos7-01``. - applications (MutableSequence[str]): - The names of Backup and DR applications. An application is a - VM, database, or file system on a managed host monitored by - a backup and recovery appliance. For example, - ``centos7-01-vol00``, ``centos7-01-vol01``, - ``centos7-01-vol02``. - storage_pool (str): - The name of the Backup and DR storage pool that the backup - and recovery appliance is storing data in. The storage pool - could be of type Cloud, Primary, Snapshot, or OnVault. See - the `Backup and DR documentation on storage - pools `__. - For example, ``DiskPoolOne``. - policy_options (MutableSequence[str]): - The names of Backup and DR advanced policy options of a - policy applying to an application. See the `Backup and DR - documentation on policy - options `__. - For example, ``skipofflineappsincongrp, nounmap``. - profile (str): - The name of the Backup and DR resource profile that - specifies the storage media for backups of application and - VM data. See the `Backup and DR documentation on - profiles `__. - For example, ``GCP``. - appliance (str): - The name of the Backup and DR appliance that captures, - moves, and manages the lifecycle of backup data. For - example, ``backup-server-57137``. - backup_type (str): - The backup type of the Backup and DR image. For example, - ``Snapshot``, ``Remote Snapshot``, ``OnVault``. - backup_create_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp at which the Backup and DR - backup was created. - """ - - backup_template: str = proto.Field( - proto.STRING, - number=1, - ) - policies: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - host: str = proto.Field( - proto.STRING, - number=3, - ) - applications: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - storage_pool: str = proto.Field( - proto.STRING, - number=5, - ) - policy_options: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - profile: str = proto.Field( - proto.STRING, - number=7, - ) - appliance: str = proto.Field( - proto.STRING, - number=8, - ) - backup_type: str = proto.Field( - proto.STRING, - number=9, - ) - backup_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py deleted file mode 100644 index 01d3971a5bd5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v2', - manifest={ - 'BigQueryExport', - }, -) - - -class BigQueryExport(proto.Message): - r"""Configures how to deliver Findings to BigQuery Instance. - - Attributes: - name (str): - Identifier. The relative resource name of this export. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name. - The following list shows some examples: - - - - - ``organizations/{organization_id}/locations/{location_id}/bigQueryExports/{export_id}`` - - - ``folders/{folder_id}/locations/{location_id}/bigQueryExports/{export_id}`` - - - - ``projects/{project_id}/locations/{location_id}/bigQueryExports/{export_id}`` - - This field is provided in responses, and is ignored when - provided in create requests. - description (str): - The description of the export (max of 1024 - characters). - filter (str): - Expression that defines the filter to apply across - create/update events of findings. The expression is a list - of zero or more restrictions combined via logical operators - ``AND`` and ``OR``. Parentheses are supported, and ``OR`` - has higher precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - dataset (str): - The dataset to write findings' updates to. Its format is - "projects/[project_id]/datasets/[bigquery_dataset_id]". - BigQuery dataset unique ID must contain only letters (a-z, - A-Z), numbers (0-9), or underscores (_). - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the BigQuery - export was created. This field is set by the - server and will be ignored if provided on export - on creation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The most recent time at which - the BigQuery export was updated. This field is - set by the server and will be ignored if - provided on export creation or update. - most_recent_editor (str): - Output only. Email address of the user who - last edited the BigQuery export. This field is - set by the server and will be ignored if - provided on export creation or update. - principal (str): - Output only. The service account that needs - permission to create table and upload data to - the BigQuery dataset. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - filter: str = proto.Field( - proto.STRING, - number=3, - ) - dataset: 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, - ) - most_recent_editor: str = proto.Field( - proto.STRING, - number=7, - ) - principal: str = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.py deleted file mode 100644 index 2bf900e3af1c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.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.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'CloudArmor', - 'SecurityPolicy', - 'Requests', - 'AdaptiveProtection', - 'Attack', - }, -) - - -class CloudArmor(proto.Message): - r"""Fields related to Google Cloud Armor findings. - - Attributes: - security_policy (google.cloud.securitycenter_v2.types.SecurityPolicy): - Information about the `Google Cloud Armor security - policy `__ - relevant to the finding. - requests (google.cloud.securitycenter_v2.types.Requests): - Information about incoming requests evaluated by `Google - Cloud Armor security - policies `__. - adaptive_protection (google.cloud.securitycenter_v2.types.AdaptiveProtection): - Information about potential Layer 7 DDoS attacks identified - by `Google Cloud Armor Adaptive - Protection `__. - attack (google.cloud.securitycenter_v2.types.Attack): - Information about DDoS attack volume and - classification. - threat_vector (str): - Distinguish between volumetric & protocol DDoS attack and - application layer attacks. For example, "L3_4" for Layer 3 - and Layer 4 DDoS attacks, or "L_7" for Layer 7 DDoS attacks. - duration (google.protobuf.duration_pb2.Duration): - Duration of attack from the start until the - current moment (updated every 5 minutes). - """ - - security_policy: 'SecurityPolicy' = proto.Field( - proto.MESSAGE, - number=1, - message='SecurityPolicy', - ) - requests: 'Requests' = proto.Field( - proto.MESSAGE, - number=2, - message='Requests', - ) - adaptive_protection: 'AdaptiveProtection' = proto.Field( - proto.MESSAGE, - number=3, - message='AdaptiveProtection', - ) - attack: 'Attack' = proto.Field( - proto.MESSAGE, - number=4, - message='Attack', - ) - threat_vector: str = proto.Field( - proto.STRING, - number=5, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - - -class SecurityPolicy(proto.Message): - r"""Information about the `Google Cloud Armor security - policy `__ - relevant to the finding. - - Attributes: - name (str): - The name of the Google Cloud Armor security - policy, for example, "my-security-policy". - type_ (str): - The type of Google Cloud Armor security - policy for example, 'backend security policy', - 'edge security policy', 'network edge security - policy', or 'always-on DDoS protection'. - preview (bool): - Whether or not the associated rule or policy - is in preview mode. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - preview: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class Requests(proto.Message): - r"""Information about the requests relevant to the finding. - - Attributes: - ratio (float): - For 'Increasing deny ratio', the ratio is the - denied traffic divided by the allowed traffic. - For 'Allowed traffic spike', the ratio is the - allowed traffic in the short term divided by - allowed traffic in the long term. - short_term_allowed (int): - Allowed RPS (requests per second) in the - short term. - long_term_allowed (int): - Allowed RPS (requests per second) over the - long term. - long_term_denied (int): - Denied RPS (requests per second) over the - long term. - """ - - ratio: float = proto.Field( - proto.DOUBLE, - number=1, - ) - short_term_allowed: int = proto.Field( - proto.INT32, - number=2, - ) - long_term_allowed: int = proto.Field( - proto.INT32, - number=3, - ) - long_term_denied: int = proto.Field( - proto.INT32, - number=4, - ) - - -class AdaptiveProtection(proto.Message): - r"""Information about `Google Cloud Armor Adaptive - Protection `__. - - Attributes: - confidence (float): - A score of 0 means that there is low confidence that the - detected event is an actual attack. A score of 1 means that - there is high confidence that the detected event is an - attack. See the `Adaptive Protection - documentation `__ - for further explanation. - """ - - confidence: float = proto.Field( - proto.DOUBLE, - number=1, - ) - - -class Attack(proto.Message): - r"""Information about DDoS attack volume and classification. - - Attributes: - volume_pps (int): - Total PPS (packets per second) volume of - attack. - volume_bps (int): - Total BPS (bytes per second) volume of - attack. - classification (str): - Type of attack, for example, 'SYN-flood', - 'NTP-udp', or 'CHARGEN-udp'. - """ - - volume_pps: int = proto.Field( - proto.INT32, - number=1, - ) - volume_bps: int = proto.Field( - proto.INT32, - number=2, - ) - classification: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py deleted file mode 100644 index 1b41c5f6d040..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.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.cloud.securitycenter.v2', - manifest={ - 'CloudDlpDataProfile', - }, -) - - -class CloudDlpDataProfile(proto.Message): - r"""The `data - profile `__ - associated with the finding. - - Attributes: - data_profile (str): - Name of the data profile, for example, - ``projects/123/locations/europe/tableProfiles/8383929``. - parent_type (google.cloud.securitycenter_v2.types.CloudDlpDataProfile.ParentType): - The resource hierarchy level at which the - data profile was generated. - """ - class ParentType(proto.Enum): - r"""Parents for configurations that produce data profile - findings. - - Values: - PARENT_TYPE_UNSPECIFIED (0): - Unspecified parent type. - ORGANIZATION (1): - Organization-level configurations. - PROJECT (2): - Project-level configurations. - """ - PARENT_TYPE_UNSPECIFIED = 0 - ORGANIZATION = 1 - PROJECT = 2 - - data_profile: str = proto.Field( - proto.STRING, - number=1, - ) - parent_type: ParentType = proto.Field( - proto.ENUM, - number=2, - enum=ParentType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py deleted file mode 100644 index c98af340d22a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'CloudDlpInspection', - }, -) - - -class CloudDlpInspection(proto.Message): - r"""Details about the Cloud Data Loss Prevention (Cloud DLP) `inspection - job `__ - that produced the finding. - - Attributes: - inspect_job (str): - Name of the inspection job, for example, - ``projects/123/locations/europe/dlpJobs/i-8383929``. - info_type (str): - The type of information (or - `infoType `__) - found, for example, ``EMAIL_ADDRESS`` or ``STREET_ADDRESS``. - info_type_count (int): - The number of times Cloud DLP found this - infoType within this job and resource. - full_scan (bool): - Whether Cloud DLP scanned the complete - resource or a sampled subset. - """ - - inspect_job: str = proto.Field( - proto.STRING, - number=1, - ) - info_type: str = proto.Field( - proto.STRING, - number=2, - ) - info_type_count: int = proto.Field( - proto.INT64, - number=3, - ) - full_scan: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.py deleted file mode 100644 index 64f5c99ef06b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Compliance', - }, -) - - -class Compliance(proto.Message): - r"""Contains compliance information about a security standard - indicating unmet recommendations. - - Attributes: - standard (str): - Industry-wide compliance standards or - benchmarks, such as CIS, PCI, and OWASP. - version (str): - Version of the standard or benchmark, for - example, 1.1 - ids (MutableSequence[str]): - Policies within the standard or benchmark, - for example, A.12.4.1 - """ - - standard: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.py deleted file mode 100644 index 1e0ff52947d5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.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.cloud.securitycenter.v2', - manifest={ - 'Connection', - }, -) - - -class Connection(proto.Message): - r"""Contains information about the IP connection associated with - the finding. - - Attributes: - destination_ip (str): - Destination IP address. Not present for - sockets that are listening and not connected. - destination_port (int): - Destination port. Not present for sockets - that are listening and not connected. - source_ip (str): - Source IP address. - source_port (int): - Source port. - protocol (google.cloud.securitycenter_v2.types.Connection.Protocol): - IANA Internet Protocol Number such as TCP(6) - and UDP(17). - """ - class Protocol(proto.Enum): - r"""IANA Internet Protocol Number such as TCP(6) and UDP(17). - - Values: - PROTOCOL_UNSPECIFIED (0): - Unspecified protocol (not HOPOPT). - ICMP (1): - Internet Control Message Protocol. - TCP (6): - Transmission Control Protocol. - UDP (17): - User Datagram Protocol. - GRE (47): - Generic Routing Encapsulation. - ESP (50): - Encap Security Payload. - """ - PROTOCOL_UNSPECIFIED = 0 - ICMP = 1 - TCP = 6 - UDP = 17 - GRE = 47 - ESP = 50 - - destination_ip: str = proto.Field( - proto.STRING, - number=1, - ) - destination_port: int = proto.Field( - proto.INT32, - number=2, - ) - source_ip: str = proto.Field( - proto.STRING, - number=3, - ) - source_port: int = proto.Field( - proto.INT32, - number=4, - ) - protocol: Protocol = proto.Field( - proto.ENUM, - number=5, - enum=Protocol, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.py deleted file mode 100644 index f7e49e2e4392..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'ContactDetails', - 'Contact', - }, -) - - -class ContactDetails(proto.Message): - r"""Details about specific contacts - - Attributes: - contacts (MutableSequence[google.cloud.securitycenter_v2.types.Contact]): - A list of contacts - """ - - contacts: MutableSequence['Contact'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Contact', - ) - - -class Contact(proto.Message): - r"""The email address of a contact. - - Attributes: - email (str): - An email address. For example, "``person123@company.com``". - """ - - email: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.py deleted file mode 100644 index de1e6fd55be0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v2.types import label -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Container', - }, -) - - -class Container(proto.Message): - r"""Container associated with the finding. - - Attributes: - name (str): - Name of the container. - uri (str): - Container image URI provided when configuring - a pod or container. This string can identify a - container image version using mutable tags. - image_id (str): - Optional container image ID, if provided by - the container runtime. Uniquely identifies the - container image launched using a container image - digest. - labels (MutableSequence[google.cloud.securitycenter_v2.types.Label]): - Container labels, as provided by the - container runtime. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the container was created. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - image_id: str = proto.Field( - proto.STRING, - number=3, - ) - labels: MutableSequence[label.Label] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=label.Label, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.py deleted file mode 100644 index 59f3eefcf9e3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Database', - }, -) - - -class Database(proto.Message): - r"""Represents database access information, such as queries. A database - may be a sub-resource of an instance (as in the case of Cloud SQL - instances or Cloud Spanner instances), or the database instance - itself. Some database resources might not have the `full resource - name `__ populated - because these resource types, such as Cloud SQL databases, are not - yet supported by Cloud Asset Inventory. In these cases only the - display name is provided. - - Attributes: - name (str): - Some database resources may not have the `full resource - name `__ - populated because these resource types are not yet supported - by Cloud Asset Inventory (e.g. Cloud SQL databases). In - these cases only the display name will be provided. The - `full resource - name `__ of - the database that the user connected to, if it is supported - by Cloud Asset Inventory. - display_name (str): - The human-readable name of the database that - the user connected to. - user_name (str): - The username used to connect to the database. - The username might not be an IAM principal and - does not have a set format. - query (str): - The SQL statement that is associated with the - database access. - grantees (MutableSequence[str]): - The target usernames, roles, or groups of an - SQL privilege grant, which is not an IAM policy - change. - version (str): - The version of the database, for example, POSTGRES_14. See - `the complete - list `__. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - user_name: str = proto.Field( - proto.STRING, - number=3, - ) - query: str = proto.Field( - proto.STRING, - number=4, - ) - grantees: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - version: str = proto.Field( - proto.STRING, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.py deleted file mode 100644 index 8a3c83a21200..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Exfiltration', - 'ExfilResource', - }, -) - - -class Exfiltration(proto.Message): - r"""Exfiltration represents a data exfiltration attempt from one or more - sources to one or more targets. The ``sources`` attribute lists the - sources of the exfiltrated data. The ``targets`` attribute lists the - destinations the data was copied to. - - Attributes: - sources (MutableSequence[google.cloud.securitycenter_v2.types.ExfilResource]): - If there are multiple sources, then the data - is considered "joined" between them. For - instance, BigQuery can join multiple tables, and - each table would be considered a source. - targets (MutableSequence[google.cloud.securitycenter_v2.types.ExfilResource]): - If there are multiple targets, each target - would get a complete copy of the "joined" source - data. - total_exfiltrated_bytes (int): - Total exfiltrated bytes processed for the - entire job. - """ - - sources: MutableSequence['ExfilResource'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ExfilResource', - ) - targets: MutableSequence['ExfilResource'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ExfilResource', - ) - total_exfiltrated_bytes: int = proto.Field( - proto.INT64, - number=3, - ) - - -class ExfilResource(proto.Message): - r"""Resource where data was exfiltrated from or exfiltrated to. - - Attributes: - name (str): - The resource's `full resource - name `__. - components (MutableSequence[str]): - Subcomponents of the asset that was - exfiltrated, like URIs used during exfiltration, - table names, databases, and filenames. For - example, multiple tables might have been - exfiltrated from the same Cloud SQL instance, or - multiple files might have been exfiltrated from - the same Cloud Storage bucket. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - components: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py deleted file mode 100644 index 780eb3c24edf..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py +++ /dev/null @@ -1,192 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v2', - manifest={ - 'ExternalSystem', - }, -) - - -class ExternalSystem(proto.Message): - r"""Representation of third party SIEM/SOAR fields within SCC. - - Attributes: - name (str): - Full resource name of the external system. The following - list shows some examples: - - - ``organizations/1234/sources/5678/findings/123456/externalSystems/jira`` - - - - ``organizations/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` - - - ``folders/1234/sources/5678/findings/123456/externalSystems/jira`` - - - - ``folders/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` - - - ``projects/1234/sources/5678/findings/123456/externalSystems/jira`` - - - - ``projects/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` - assignees (MutableSequence[str]): - References primary/secondary etc assignees in - the external system. - external_uid (str): - The identifier that's used to track the - finding's corresponding case in the external - system. - status (str): - The most recent status of the finding's - corresponding case, as reported by the external - system. - external_system_update_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the case was last updated, as - reported by the external system. - case_uri (str): - The link to the finding's corresponding case - in the external system. - case_priority (str): - The priority of the finding's corresponding - case in the external system. - case_sla (google.protobuf.timestamp_pb2.Timestamp): - The SLA of the finding's corresponding case - in the external system. - case_create_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the case was created, as - reported by the external system. - case_close_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the case was closed, as - reported by the external system. - ticket_info (google.cloud.securitycenter_v2.types.ExternalSystem.TicketInfo): - Information about the ticket, if any, that is - being used to track the resolution of the issue - that is identified by this finding. - """ - - class TicketInfo(proto.Message): - r"""Information about the ticket, if any, that is being used to - track the resolution of the issue that is identified by this - finding. - - Attributes: - id (str): - The identifier of the ticket in the ticket - system. - assignee (str): - The assignee of the ticket in the ticket - system. - description (str): - The description of the ticket in the ticket - system. - uri (str): - The link to the ticket in the ticket system. - status (str): - The latest status of the ticket, as reported - by the ticket system. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the ticket was last updated, as - reported by the ticket system. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - assignee: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - uri: str = proto.Field( - proto.STRING, - number=4, - ) - status: str = proto.Field( - proto.STRING, - number=5, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - assignees: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - external_uid: str = proto.Field( - proto.STRING, - number=3, - ) - status: str = proto.Field( - proto.STRING, - number=4, - ) - external_system_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - case_uri: str = proto.Field( - proto.STRING, - number=6, - ) - case_priority: str = proto.Field( - proto.STRING, - number=7, - ) - case_sla: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - case_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - case_close_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - ticket_info: TicketInfo = proto.Field( - proto.MESSAGE, - number=8, - message=TicketInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.py deleted file mode 100644 index 5bb6f2f70ef0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'File', - }, -) - - -class File(proto.Message): - r"""File information about the related binary/library used by an - executable, or the script used by a script interpreter - - Attributes: - path (str): - Absolute path of the file as a JSON encoded - string. - size (int): - Size of the file in bytes. - sha256 (str): - SHA256 hash of the first hashed_size bytes of the file - encoded as a hex string. If hashed_size == size, sha256 - represents the SHA256 hash of the entire file. - hashed_size (int): - The length in bytes of the file prefix that was hashed. If - hashed_size == size, any hashes reported represent the - entire file. - partially_hashed (bool): - True when the hash covers only a prefix of - the file. - contents (str): - Prefix of the file contents as a JSON-encoded - string. - disk_path (google.cloud.securitycenter_v2.types.File.DiskPath): - Path of the file in terms of underlying - disk/partition identifiers. - """ - - class DiskPath(proto.Message): - r"""Path of the file in terms of underlying disk/partition - identifiers. - - Attributes: - partition_uuid (str): - UUID of the partition (format - https://wiki.archlinux.org/title/persistent_block_device_naming#by-uuid) - relative_path (str): - Relative path of the file in the partition as a JSON encoded - string. Example: /home/user1/executable_file.sh - """ - - partition_uuid: str = proto.Field( - proto.STRING, - number=1, - ) - relative_path: str = proto.Field( - proto.STRING, - number=2, - ) - - path: str = proto.Field( - proto.STRING, - number=1, - ) - size: int = proto.Field( - proto.INT64, - number=2, - ) - sha256: str = proto.Field( - proto.STRING, - number=3, - ) - hashed_size: int = proto.Field( - proto.INT64, - number=4, - ) - partially_hashed: bool = proto.Field( - proto.BOOL, - number=5, - ) - contents: str = proto.Field( - proto.STRING, - number=6, - ) - disk_path: DiskPath = proto.Field( - proto.MESSAGE, - number=7, - message=DiskPath, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.py deleted file mode 100644 index 4e18ac0eb8ae..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v2.types import access as gcs_access -from google.cloud.securitycenter_v2.types import application as gcs_application -from google.cloud.securitycenter_v2.types import attack_exposure as gcs_attack_exposure -from google.cloud.securitycenter_v2.types import backup_disaster_recovery as gcs_backup_disaster_recovery -from google.cloud.securitycenter_v2.types import cloud_armor as gcs_cloud_armor -from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile as gcs_cloud_dlp_data_profile -from google.cloud.securitycenter_v2.types import cloud_dlp_inspection as gcs_cloud_dlp_inspection -from google.cloud.securitycenter_v2.types import compliance -from google.cloud.securitycenter_v2.types import connection -from google.cloud.securitycenter_v2.types import contact_details -from google.cloud.securitycenter_v2.types import container -from google.cloud.securitycenter_v2.types import database as gcs_database -from google.cloud.securitycenter_v2.types import exfiltration as gcs_exfiltration -from google.cloud.securitycenter_v2.types import external_system -from google.cloud.securitycenter_v2.types import file -from google.cloud.securitycenter_v2.types import group_membership -from google.cloud.securitycenter_v2.types import iam_binding -from google.cloud.securitycenter_v2.types import indicator as gcs_indicator -from google.cloud.securitycenter_v2.types import kernel_rootkit as gcs_kernel_rootkit -from google.cloud.securitycenter_v2.types import kubernetes as gcs_kubernetes -from google.cloud.securitycenter_v2.types import load_balancer -from google.cloud.securitycenter_v2.types import log_entry -from google.cloud.securitycenter_v2.types import mitre_attack as gcs_mitre_attack -from google.cloud.securitycenter_v2.types import notebook as gcs_notebook -from google.cloud.securitycenter_v2.types import org_policy -from google.cloud.securitycenter_v2.types import process -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import security_posture as gcs_security_posture -from google.cloud.securitycenter_v2.types import toxic_combination as gcs_toxic_combination -from google.cloud.securitycenter_v2.types import vulnerability as gcs_vulnerability -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - - A finding is a record of assessment data like security, risk, - health, or privacy, that is ingested into Security Command - Center for presentation, notification, analysis, policy testing, - and enforcement. For example, a cross-site scripting (XSS) - vulnerability in an App Engine application is a finding. - - Attributes: - name (str): - The `relative resource - name `__ - of the finding. The following list shows some examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - canonical_name (str): - Output only. The canonical name of the finding. The - following list shows some examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - The prefix is the closest CRM ancestor of the resource - associated with the finding. - parent (str): - The relative resource name of the source and location the - finding belongs to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. The following - list shows some examples: - - - ``organizations/{organization_id}/sources/{source_id}`` - - ``folders/{folders_id}/sources/{source_id}`` - - ``projects/{projects_id}/sources/{source_id}`` - - - - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}`` - - - ``folders/{folders_id}/sources/{source_id}/locations/{location_id}`` - - ``projects/{projects_id}/sources/{source_id}/locations/{location_id}`` - resource_name (str): - Immutable. For findings on Google Cloud resources, the full - resource name of the Google Cloud resource this finding is - for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - state (google.cloud.securitycenter_v2.types.Finding.State): - Output only. The state of the finding. - category (str): - Immutable. The additional taxonomy group within findings - from a given source. Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (google.protobuf.timestamp_pb2.Timestamp): - The time the finding was first detected. If - an existing finding is updated, then this is the - time the update occurred. For example, if the - finding represents an open firewall, this - property captures the time the detector believes - the firewall became open. The accuracy is - determined by the detector. If the finding is - later resolved, then this time reflects when the - finding was resolved. This must not be set to a - value greater than the current timestamp. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the finding - was created in Security Command Center. - severity (google.cloud.securitycenter_v2.types.Finding.Severity): - The severity of the finding. This field is - managed by the source that writes the finding. - mute (google.cloud.securitycenter_v2.types.Finding.Mute): - Indicates the mute state of a finding (either - muted, unmuted or undefined). Unlike other - attributes of a finding, a finding provider - shouldn't set the value of mute. - mute_info (google.cloud.securitycenter_v2.types.Finding.MuteInfo): - Output only. The mute information regarding - this finding. - finding_class (google.cloud.securitycenter_v2.types.Finding.FindingClass): - The class of the finding. - indicator (google.cloud.securitycenter_v2.types.Indicator): - Represents what's commonly known as an *indicator of - compromise* (IoC) in computer forensics. This is an artifact - observed on a network or in an operating system that, with - high confidence, indicates a computer intrusion. For more - information, see `Indicator of - compromise `__. - vulnerability (google.cloud.securitycenter_v2.types.Vulnerability): - Represents vulnerability-specific fields like - CVE and CVSS scores. CVE stands for Common - Vulnerabilities and Exposures - (https://cve.mitre.org/about/) - mute_update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The most recent time this - finding was muted or unmuted. - external_systems (MutableMapping[str, google.cloud.securitycenter_v2.types.ExternalSystem]): - Output only. Third party SIEM/SOAR fields - within SCC, contains external system information - and external system finding fields. - mitre_attack (google.cloud.securitycenter_v2.types.MitreAttack): - MITRE ATT&CK tactics and techniques related - to this finding. See: https://attack.mitre.org - access (google.cloud.securitycenter_v2.types.Access): - Access details associated with the finding, - such as more information on the caller, which - method was accessed, and from where. - connections (MutableSequence[google.cloud.securitycenter_v2.types.Connection]): - Contains information about the IP connection - associated with the finding. - mute_initiator (str): - Records additional information about the mute operation, for - example, the `mute - configuration `__ - that muted the finding and the user who muted the finding. - processes (MutableSequence[google.cloud.securitycenter_v2.types.Process]): - Represents operating system processes - associated with the Finding. - contacts (MutableMapping[str, google.cloud.securitycenter_v2.types.ContactDetails]): - Output only. Map containing the points of contact for the - given finding. The key represents the type of contact, while - the value contains a list of all the contacts that pertain. - Please refer to: - https://cloud.google.com/resource-manager/docs/managing-notification-contacts#notification-categories - - :: - - { - "security": { - "contacts": [ - { - "email": "person1@company.com" - }, - { - "email": "person2@company.com" - } - ] - } - } - compliances (MutableSequence[google.cloud.securitycenter_v2.types.Compliance]): - Contains compliance information for security - standards associated to the finding. - parent_display_name (str): - Output only. The human readable display name - of the finding source such as "Event Threat - Detection" or "Security Health Analytics". - description (str): - Contains more details about the finding. - exfiltration (google.cloud.securitycenter_v2.types.Exfiltration): - Represents exfiltrations associated with the - finding. - iam_bindings (MutableSequence[google.cloud.securitycenter_v2.types.IamBinding]): - Represents IAM bindings associated with the - finding. - next_steps (str): - Steps to address the finding. - module_name (str): - Unique identifier of the module which - generated the finding. Example: - - folders/598186756061/securityHealthAnalyticsSettings/customModules/56799441161885 - containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): - Containers associated with the finding. This - field provides information for both Kubernetes - and non-Kubernetes containers. - kubernetes (google.cloud.securitycenter_v2.types.Kubernetes): - Kubernetes resources associated with the - finding. - database (google.cloud.securitycenter_v2.types.Database): - Database associated with the finding. - attack_exposure (google.cloud.securitycenter_v2.types.AttackExposure): - The results of an attack path simulation - relevant to this finding. - files (MutableSequence[google.cloud.securitycenter_v2.types.File]): - File associated with the finding. - cloud_dlp_inspection (google.cloud.securitycenter_v2.types.CloudDlpInspection): - Cloud Data Loss Prevention (Cloud DLP) - inspection results that are associated with the - finding. - cloud_dlp_data_profile (google.cloud.securitycenter_v2.types.CloudDlpDataProfile): - Cloud DLP data profile that is associated - with the finding. - kernel_rootkit (google.cloud.securitycenter_v2.types.KernelRootkit): - Signature of the kernel rootkit. - org_policies (MutableSequence[google.cloud.securitycenter_v2.types.OrgPolicy]): - Contains information about the org policies - associated with the finding. - application (google.cloud.securitycenter_v2.types.Application): - Represents an application associated with the - finding. - backup_disaster_recovery (google.cloud.securitycenter_v2.types.BackupDisasterRecovery): - Fields related to Backup and DR findings. - security_posture (google.cloud.securitycenter_v2.types.SecurityPosture): - The security posture associated with the - finding. - log_entries (MutableSequence[google.cloud.securitycenter_v2.types.LogEntry]): - Log entries that are relevant to the finding. - load_balancers (MutableSequence[google.cloud.securitycenter_v2.types.LoadBalancer]): - The load balancers associated with the - finding. - cloud_armor (google.cloud.securitycenter_v2.types.CloudArmor): - Fields related to Cloud Armor findings. - notebook (google.cloud.securitycenter_v2.types.Notebook): - Notebook associated with the finding. - toxic_combination (google.cloud.securitycenter_v2.types.ToxicCombination): - Contains details about a group of security - issues that, when the issues occur together, - represent a greater risk than when the issues - occur independently. A group of such issues is - referred to as a toxic combination. - This field cannot be updated. Its value is - ignored in all update requests. - group_memberships (MutableSequence[google.cloud.securitycenter_v2.types.GroupMembership]): - Contains details about groups of which this - finding is a member. A group is a collection of - findings that are related in some way. This - field cannot be updated. Its value is ignored in - all update requests. - """ - class State(proto.Enum): - r"""The state of the finding. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - ACTIVE (1): - The finding requires attention and has not - been addressed yet. - INACTIVE (2): - The finding has been fixed, triaged as a - non-issue or otherwise addressed and is no - longer active. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - class Severity(proto.Enum): - r"""The severity of the finding. - - Values: - SEVERITY_UNSPECIFIED (0): - This value is used for findings when a source - doesn't write a severity value. - CRITICAL (1): - Vulnerability: - - A critical vulnerability is easily discoverable - by an external actor, exploitable, and results - in the direct ability to execute arbitrary code, - exfiltrate data, and otherwise gain additional - access and privileges to cloud resources and - workloads. Examples include publicly accessible - unprotected user data and public SSH access with - weak or no passwords. - - Threat: - - Indicates a threat that is able to access, - modify, or delete data or execute unauthorized - code within existing resources. - HIGH (2): - Vulnerability: - - A high risk vulnerability can be easily - discovered and exploited in combination with - other vulnerabilities in order to gain direct - access and the ability to execute arbitrary - code, exfiltrate data, and otherwise gain - additional access and privileges to cloud - resources and workloads. An example is a - database with weak or no passwords that is only - accessible internally. This database could - easily be compromised by an actor that had - access to the internal network. - - Threat: - - Indicates a threat that is able to create new - computational resources in an environment but - not able to access data or execute code in - existing resources. - MEDIUM (3): - Vulnerability: - - A medium risk vulnerability could be used by an - actor to gain access to resources or privileges - that enable them to eventually (through multiple - steps or a complex exploit) gain access and the - ability to execute arbitrary code or exfiltrate - data. An example is a service account with - access to more projects than it should have. If - an actor gains access to the service account, - they could potentially use that access to - manipulate a project the service account was not - intended to. - - Threat: - - Indicates a threat that is able to cause - operational impact but may not access data or - execute unauthorized code. - LOW (4): - Vulnerability: - - A low risk vulnerability hampers a security - organization's ability to detect vulnerabilities - or active threats in their deployment, or - prevents the root cause investigation of - security issues. An example is monitoring and - logs being disabled for resource configurations - and access. - - Threat: - - Indicates a threat that has obtained minimal - access to an environment but is not able to - access data, execute code, or create resources. - """ - SEVERITY_UNSPECIFIED = 0 - CRITICAL = 1 - HIGH = 2 - MEDIUM = 3 - LOW = 4 - - class Mute(proto.Enum): - r"""Mute state a finding can be in. - - Values: - MUTE_UNSPECIFIED (0): - Unspecified. - MUTED (1): - Finding has been muted. - UNMUTED (2): - Finding has been unmuted. - UNDEFINED (3): - Finding has never been muted/unmuted. - """ - MUTE_UNSPECIFIED = 0 - MUTED = 1 - UNMUTED = 2 - UNDEFINED = 3 - - class FindingClass(proto.Enum): - r"""Represents what kind of Finding it is. - - Values: - FINDING_CLASS_UNSPECIFIED (0): - Unspecified finding class. - THREAT (1): - Describes unwanted or malicious activity. - VULNERABILITY (2): - Describes a potential weakness in software - that increases risk to Confidentiality & - Integrity & Availability. - MISCONFIGURATION (3): - Describes a potential weakness in cloud - resource/asset configuration that increases - risk. - OBSERVATION (4): - Describes a security observation that is for - informational purposes. - SCC_ERROR (5): - Describes an error that prevents some SCC - functionality. - POSTURE_VIOLATION (6): - Describes a potential security risk due to a - change in the security posture. - TOXIC_COMBINATION (7): - Describes a combination of security issues - that represent a more severe security problem - when taken together. - """ - FINDING_CLASS_UNSPECIFIED = 0 - THREAT = 1 - VULNERABILITY = 2 - MISCONFIGURATION = 3 - OBSERVATION = 4 - SCC_ERROR = 5 - POSTURE_VIOLATION = 6 - TOXIC_COMBINATION = 7 - - class MuteInfo(proto.Message): - r"""Mute information about the finding, including whether the - finding has a static mute or any matching dynamic mute rules. - - Attributes: - static_mute (google.cloud.securitycenter_v2.types.Finding.MuteInfo.StaticMute): - If set, the static mute applied to this - finding. Static mutes override dynamic mutes. If - unset, there is no static mute. - dynamic_mute_records (MutableSequence[google.cloud.securitycenter_v2.types.Finding.MuteInfo.DynamicMuteRecord]): - The list of dynamic mute rules that currently - match the finding. - """ - - class StaticMute(proto.Message): - r"""Information about the static mute state. A static mute state - overrides any dynamic mute rules that apply to this finding. The - static mute state can be set by a static mute rule or by muting - the finding directly. - - Attributes: - state (google.cloud.securitycenter_v2.types.Finding.Mute): - The static mute state. If the value is ``MUTED`` or - ``UNMUTED``, then the finding's overall mute state will have - the same value. - apply_time (google.protobuf.timestamp_pb2.Timestamp): - When the static mute was applied. - """ - - state: 'Finding.Mute' = proto.Field( - proto.ENUM, - number=1, - enum='Finding.Mute', - ) - apply_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - class DynamicMuteRecord(proto.Message): - r"""The record of a dynamic mute rule that matches the finding. - - Attributes: - mute_config (str): - The relative resource name of the mute rule, represented by - a mute config, that created this record, for example - ``organizations/123/muteConfigs/mymuteconfig`` or - ``organizations/123/locations/global/muteConfigs/mymuteconfig``. - match_time (google.protobuf.timestamp_pb2.Timestamp): - When the dynamic mute rule first matched the - finding. - """ - - mute_config: str = proto.Field( - proto.STRING, - number=1, - ) - match_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - static_mute: 'Finding.MuteInfo.StaticMute' = proto.Field( - proto.MESSAGE, - number=1, - message='Finding.MuteInfo.StaticMute', - ) - dynamic_mute_records: MutableSequence['Finding.MuteInfo.DynamicMuteRecord'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Finding.MuteInfo.DynamicMuteRecord', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=2, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - resource_name: str = proto.Field( - proto.STRING, - number=4, - ) - state: State = proto.Field( - proto.ENUM, - number=6, - enum=State, - ) - category: str = proto.Field( - proto.STRING, - number=7, - ) - external_uri: str = proto.Field( - proto.STRING, - number=8, - ) - source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=9, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=10, - message=gcs_security_marks.SecurityMarks, - ) - event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - severity: Severity = proto.Field( - proto.ENUM, - number=14, - enum=Severity, - ) - mute: Mute = proto.Field( - proto.ENUM, - number=15, - enum=Mute, - ) - mute_info: MuteInfo = proto.Field( - proto.MESSAGE, - number=53, - message=MuteInfo, - ) - finding_class: FindingClass = proto.Field( - proto.ENUM, - number=16, - enum=FindingClass, - ) - indicator: gcs_indicator.Indicator = proto.Field( - proto.MESSAGE, - number=17, - message=gcs_indicator.Indicator, - ) - vulnerability: gcs_vulnerability.Vulnerability = proto.Field( - proto.MESSAGE, - number=18, - message=gcs_vulnerability.Vulnerability, - ) - mute_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=19, - message=timestamp_pb2.Timestamp, - ) - external_systems: MutableMapping[str, external_system.ExternalSystem] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=20, - message=external_system.ExternalSystem, - ) - mitre_attack: gcs_mitre_attack.MitreAttack = proto.Field( - proto.MESSAGE, - number=21, - message=gcs_mitre_attack.MitreAttack, - ) - access: gcs_access.Access = proto.Field( - proto.MESSAGE, - number=22, - message=gcs_access.Access, - ) - connections: MutableSequence[connection.Connection] = proto.RepeatedField( - proto.MESSAGE, - number=23, - message=connection.Connection, - ) - mute_initiator: str = proto.Field( - proto.STRING, - number=24, - ) - processes: MutableSequence[process.Process] = proto.RepeatedField( - proto.MESSAGE, - number=25, - message=process.Process, - ) - contacts: MutableMapping[str, contact_details.ContactDetails] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=26, - message=contact_details.ContactDetails, - ) - compliances: MutableSequence[compliance.Compliance] = proto.RepeatedField( - proto.MESSAGE, - number=27, - message=compliance.Compliance, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=29, - ) - description: str = proto.Field( - proto.STRING, - number=30, - ) - exfiltration: gcs_exfiltration.Exfiltration = proto.Field( - proto.MESSAGE, - number=31, - message=gcs_exfiltration.Exfiltration, - ) - iam_bindings: MutableSequence[iam_binding.IamBinding] = proto.RepeatedField( - proto.MESSAGE, - number=32, - message=iam_binding.IamBinding, - ) - next_steps: str = proto.Field( - proto.STRING, - number=33, - ) - module_name: str = proto.Field( - proto.STRING, - number=34, - ) - containers: MutableSequence[container.Container] = proto.RepeatedField( - proto.MESSAGE, - number=35, - message=container.Container, - ) - kubernetes: gcs_kubernetes.Kubernetes = proto.Field( - proto.MESSAGE, - number=36, - message=gcs_kubernetes.Kubernetes, - ) - database: gcs_database.Database = proto.Field( - proto.MESSAGE, - number=37, - message=gcs_database.Database, - ) - attack_exposure: gcs_attack_exposure.AttackExposure = proto.Field( - proto.MESSAGE, - number=38, - message=gcs_attack_exposure.AttackExposure, - ) - files: MutableSequence[file.File] = proto.RepeatedField( - proto.MESSAGE, - number=39, - message=file.File, - ) - cloud_dlp_inspection: gcs_cloud_dlp_inspection.CloudDlpInspection = proto.Field( - proto.MESSAGE, - number=40, - message=gcs_cloud_dlp_inspection.CloudDlpInspection, - ) - cloud_dlp_data_profile: gcs_cloud_dlp_data_profile.CloudDlpDataProfile = proto.Field( - proto.MESSAGE, - number=41, - message=gcs_cloud_dlp_data_profile.CloudDlpDataProfile, - ) - kernel_rootkit: gcs_kernel_rootkit.KernelRootkit = proto.Field( - proto.MESSAGE, - number=42, - message=gcs_kernel_rootkit.KernelRootkit, - ) - org_policies: MutableSequence[org_policy.OrgPolicy] = proto.RepeatedField( - proto.MESSAGE, - number=43, - message=org_policy.OrgPolicy, - ) - application: gcs_application.Application = proto.Field( - proto.MESSAGE, - number=45, - message=gcs_application.Application, - ) - backup_disaster_recovery: gcs_backup_disaster_recovery.BackupDisasterRecovery = proto.Field( - proto.MESSAGE, - number=47, - message=gcs_backup_disaster_recovery.BackupDisasterRecovery, - ) - security_posture: gcs_security_posture.SecurityPosture = proto.Field( - proto.MESSAGE, - number=48, - message=gcs_security_posture.SecurityPosture, - ) - log_entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( - proto.MESSAGE, - number=49, - message=log_entry.LogEntry, - ) - load_balancers: MutableSequence[load_balancer.LoadBalancer] = proto.RepeatedField( - proto.MESSAGE, - number=50, - message=load_balancer.LoadBalancer, - ) - cloud_armor: gcs_cloud_armor.CloudArmor = proto.Field( - proto.MESSAGE, - number=51, - message=gcs_cloud_armor.CloudArmor, - ) - notebook: gcs_notebook.Notebook = proto.Field( - proto.MESSAGE, - number=55, - message=gcs_notebook.Notebook, - ) - toxic_combination: gcs_toxic_combination.ToxicCombination = proto.Field( - proto.MESSAGE, - number=56, - message=gcs_toxic_combination.ToxicCombination, - ) - group_memberships: MutableSequence[group_membership.GroupMembership] = proto.RepeatedField( - proto.MESSAGE, - number=57, - message=group_membership.GroupMembership, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.py deleted file mode 100644 index 2f26d5d13947..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.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.securitycenter.v2', - manifest={ - 'Folder', - }, -) - - -class Folder(proto.Message): - r"""Message that contains the resource name and display name of a - folder resource. - - Attributes: - resource_folder (str): - Full resource name of this folder. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_folder_display_name (str): - The user defined display name for this - folder. - """ - - resource_folder: str = proto.Field( - proto.STRING, - number=1, - ) - resource_folder_display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.py deleted file mode 100644 index bfe69eac6001..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.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.cloud.securitycenter.v2', - manifest={ - 'GroupMembership', - }, -) - - -class GroupMembership(proto.Message): - r"""Contains details about groups of which this finding is a - member. A group is a collection of findings that are related in - some way. - - Attributes: - group_type (google.cloud.securitycenter_v2.types.GroupMembership.GroupType): - Type of group. - group_id (str): - ID of the group. - """ - class GroupType(proto.Enum): - r"""Possible types of groups. - - Values: - GROUP_TYPE_UNSPECIFIED (0): - Default value. - GROUP_TYPE_TOXIC_COMBINATION (1): - Group represents a toxic combination. - """ - GROUP_TYPE_UNSPECIFIED = 0 - GROUP_TYPE_TOXIC_COMBINATION = 1 - - group_type: GroupType = proto.Field( - proto.ENUM, - number=1, - enum=GroupType, - ) - group_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py deleted file mode 100644 index 17591c35825f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py +++ /dev/null @@ -1,77 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v2', - manifest={ - 'IamBinding', - }, -) - - -class IamBinding(proto.Message): - r"""Represents a particular IAM binding, which captures a - member's role addition, removal, or state. - - Attributes: - action (google.cloud.securitycenter_v2.types.IamBinding.Action): - The action that was performed on a Binding. - role (str): - Role that is assigned to "members". - For example, "roles/viewer", "roles/editor", or - "roles/owner". - member (str): - A single identity requesting access for a - Cloud Platform resource, for example, - "foo@google.com". - """ - class Action(proto.Enum): - r"""The type of action performed on a Binding in a policy. - - Values: - ACTION_UNSPECIFIED (0): - Unspecified. - ADD (1): - Addition of a Binding. - REMOVE (2): - Removal of a Binding. - """ - ACTION_UNSPECIFIED = 0 - ADD = 1 - REMOVE = 2 - - action: Action = proto.Field( - proto.ENUM, - number=1, - enum=Action, - ) - role: str = proto.Field( - proto.STRING, - number=2, - ) - member: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py deleted file mode 100644 index 01b0184ef591..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py +++ /dev/null @@ -1,186 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v2', - manifest={ - 'Indicator', - }, -) - - -class Indicator(proto.Message): - r"""Represents what's commonly known as an *indicator of compromise* - (IoC) in computer forensics. This is an artifact observed on a - network or in an operating system that, with high confidence, - indicates a computer intrusion. For more information, see `Indicator - of - compromise `__. - - Attributes: - ip_addresses (MutableSequence[str]): - The list of IP addresses that are associated - with the finding. - domains (MutableSequence[str]): - List of domains associated to the Finding. - signatures (MutableSequence[google.cloud.securitycenter_v2.types.Indicator.ProcessSignature]): - The list of matched signatures indicating - that the given process is present in the - environment. - uris (MutableSequence[str]): - The list of URIs associated to the Findings. - """ - - class ProcessSignature(proto.Message): - r"""Indicates what signature matched this process. - - 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: - memory_hash_signature (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.MemoryHashSignature): - Signature indicating that a binary family was - matched. - - This field is a member of `oneof`_ ``signature``. - yara_rule_signature (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.YaraRuleSignature): - Signature indicating that a YARA rule was - matched. - - This field is a member of `oneof`_ ``signature``. - signature_type (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.SignatureType): - Describes the type of resource associated - with the signature. - """ - class SignatureType(proto.Enum): - r"""Possible resource types to be associated with a signature. - - Values: - SIGNATURE_TYPE_UNSPECIFIED (0): - The default signature type. - SIGNATURE_TYPE_PROCESS (1): - Used for signatures concerning processes. - SIGNATURE_TYPE_FILE (2): - Used for signatures concerning disks. - """ - SIGNATURE_TYPE_UNSPECIFIED = 0 - SIGNATURE_TYPE_PROCESS = 1 - SIGNATURE_TYPE_FILE = 2 - - class MemoryHashSignature(proto.Message): - r"""A signature corresponding to memory page hashes. - - Attributes: - binary_family (str): - The binary family. - detections (MutableSequence[google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.MemoryHashSignature.Detection]): - The list of memory hash detections - contributing to the binary family match. - """ - - class Detection(proto.Message): - r"""Memory hash detection contributing to the binary family - match. - - Attributes: - binary (str): - The name of the binary associated with the - memory hash signature detection. - percent_pages_matched (float): - The percentage of memory page hashes in the - signature that were matched. - """ - - binary: str = proto.Field( - proto.STRING, - number=2, - ) - percent_pages_matched: float = proto.Field( - proto.DOUBLE, - number=3, - ) - - binary_family: str = proto.Field( - proto.STRING, - number=1, - ) - detections: MutableSequence['Indicator.ProcessSignature.MemoryHashSignature.Detection'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Indicator.ProcessSignature.MemoryHashSignature.Detection', - ) - - class YaraRuleSignature(proto.Message): - r"""A signature corresponding to a YARA rule. - - Attributes: - yara_rule (str): - The name of the YARA rule. - """ - - yara_rule: str = proto.Field( - proto.STRING, - number=5, - ) - - memory_hash_signature: 'Indicator.ProcessSignature.MemoryHashSignature' = proto.Field( - proto.MESSAGE, - number=6, - oneof='signature', - message='Indicator.ProcessSignature.MemoryHashSignature', - ) - yara_rule_signature: 'Indicator.ProcessSignature.YaraRuleSignature' = proto.Field( - proto.MESSAGE, - number=7, - oneof='signature', - message='Indicator.ProcessSignature.YaraRuleSignature', - ) - signature_type: 'Indicator.ProcessSignature.SignatureType' = proto.Field( - proto.ENUM, - number=8, - enum='Indicator.ProcessSignature.SignatureType', - ) - - ip_addresses: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - domains: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - signatures: MutableSequence[ProcessSignature] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=ProcessSignature, - ) - uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.py deleted file mode 100644 index c57d1db94570..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'KernelRootkit', - }, -) - - -class KernelRootkit(proto.Message): - r"""Kernel mode rootkit signatures. - - Attributes: - name (str): - Rootkit name, when available. - unexpected_code_modification (bool): - True if unexpected modifications of kernel - code memory are present. - unexpected_read_only_data_modification (bool): - True if unexpected modifications of kernel - read-only data memory are present. - unexpected_ftrace_handler (bool): - True if ``ftrace`` points are present with callbacks - pointing to regions that are not in the expected kernel or - module code range. - unexpected_kprobe_handler (bool): - True if ``kprobe`` points are present with callbacks - pointing to regions that are not in the expected kernel or - module code range. - unexpected_kernel_code_pages (bool): - True if kernel code pages that are not in the - expected kernel or module code regions are - present. - unexpected_system_call_handler (bool): - True if system call handlers that are are not - in the expected kernel or module code regions - are present. - unexpected_interrupt_handler (bool): - True if interrupt handlers that are are not - in the expected kernel or module code regions - are present. - unexpected_processes_in_runqueue (bool): - True if unexpected processes in the scheduler - run queue are present. Such processes are in the - run queue, but not in the process task list. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - unexpected_code_modification: bool = proto.Field( - proto.BOOL, - number=2, - ) - unexpected_read_only_data_modification: bool = proto.Field( - proto.BOOL, - number=3, - ) - unexpected_ftrace_handler: bool = proto.Field( - proto.BOOL, - number=4, - ) - unexpected_kprobe_handler: bool = proto.Field( - proto.BOOL, - number=5, - ) - unexpected_kernel_code_pages: bool = proto.Field( - proto.BOOL, - number=6, - ) - unexpected_system_call_handler: bool = proto.Field( - proto.BOOL, - number=7, - ) - unexpected_interrupt_handler: bool = proto.Field( - proto.BOOL, - number=8, - ) - unexpected_processes_in_runqueue: bool = proto.Field( - proto.BOOL, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.py deleted file mode 100644 index 8bc758c1f961..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v2.types import container -from google.cloud.securitycenter_v2.types import label - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Kubernetes', - }, -) - - -class Kubernetes(proto.Message): - r"""Kubernetes-related attributes. - - Attributes: - pods (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Pod]): - Kubernetes - `Pods `__ - associated with the finding. This field contains Pod records - for each container that is owned by a Pod. - nodes (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Node]): - Provides Kubernetes - `node `__ - information. - node_pools (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.NodePool]): - GKE `node - pools `__ - associated with the finding. This field contains node pool - information for each node, when it is available. - roles (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Role]): - Provides Kubernetes role information for findings that - involve `Roles or - ClusterRoles `__. - bindings (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Binding]): - Provides Kubernetes role binding information for findings - that involve `RoleBindings or - ClusterRoleBindings `__. - access_reviews (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.AccessReview]): - Provides information on any Kubernetes access - reviews (privilege checks) relevant to the - finding. - objects (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Object]): - Kubernetes objects related to the finding. - """ - - class Pod(proto.Message): - r"""A Kubernetes Pod. - - Attributes: - ns (str): - Kubernetes Pod namespace. - name (str): - Kubernetes Pod name. - labels (MutableSequence[google.cloud.securitycenter_v2.types.Label]): - Pod labels. For Kubernetes containers, these - are applied to the container. - containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): - Pod containers associated with this finding, - if any. - """ - - ns: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - labels: MutableSequence[label.Label] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=label.Label, - ) - containers: MutableSequence[container.Container] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=container.Container, - ) - - class Node(proto.Message): - r"""Kubernetes nodes associated with the finding. - - Attributes: - name (str): - `Full resource - name `__ of - the Compute Engine VM running the cluster node. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - class NodePool(proto.Message): - r"""Provides GKE node pool information. - - Attributes: - name (str): - Kubernetes node pool name. - nodes (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Node]): - Nodes associated with the finding. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - nodes: MutableSequence['Kubernetes.Node'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Kubernetes.Node', - ) - - class Role(proto.Message): - r"""Kubernetes Role or ClusterRole. - - Attributes: - kind (google.cloud.securitycenter_v2.types.Kubernetes.Role.Kind): - Role type. - ns (str): - Role namespace. - name (str): - Role name. - """ - class Kind(proto.Enum): - r"""Types of Kubernetes roles. - - Values: - KIND_UNSPECIFIED (0): - Role type is not specified. - ROLE (1): - Kubernetes Role. - CLUSTER_ROLE (2): - Kubernetes ClusterRole. - """ - KIND_UNSPECIFIED = 0 - ROLE = 1 - CLUSTER_ROLE = 2 - - kind: 'Kubernetes.Role.Kind' = proto.Field( - proto.ENUM, - number=1, - enum='Kubernetes.Role.Kind', - ) - ns: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - class Binding(proto.Message): - r"""Represents a Kubernetes RoleBinding or ClusterRoleBinding. - - Attributes: - ns (str): - Namespace for the binding. - name (str): - Name for the binding. - role (google.cloud.securitycenter_v2.types.Kubernetes.Role): - The Role or ClusterRole referenced by the - binding. - subjects (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Subject]): - Represents one or more subjects that are - bound to the role. Not always available for - PATCH requests. - """ - - ns: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - role: 'Kubernetes.Role' = proto.Field( - proto.MESSAGE, - number=3, - message='Kubernetes.Role', - ) - subjects: MutableSequence['Kubernetes.Subject'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Kubernetes.Subject', - ) - - class Subject(proto.Message): - r"""Represents a Kubernetes subject. - - Attributes: - kind (google.cloud.securitycenter_v2.types.Kubernetes.Subject.AuthType): - Authentication type for the subject. - ns (str): - Namespace for the subject. - name (str): - Name for the subject. - """ - class AuthType(proto.Enum): - r"""Auth types that can be used for the subject's kind field. - - Values: - AUTH_TYPE_UNSPECIFIED (0): - Authentication is not specified. - USER (1): - User with valid certificate. - SERVICEACCOUNT (2): - Users managed by Kubernetes API with - credentials stored as secrets. - GROUP (3): - Collection of users. - """ - AUTH_TYPE_UNSPECIFIED = 0 - USER = 1 - SERVICEACCOUNT = 2 - GROUP = 3 - - kind: 'Kubernetes.Subject.AuthType' = proto.Field( - proto.ENUM, - number=1, - enum='Kubernetes.Subject.AuthType', - ) - ns: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - class AccessReview(proto.Message): - r"""Conveys information about a Kubernetes access review (such as one - returned by a - ```kubectl auth can-i`` `__ - command) that was involved in a finding. - - Attributes: - group (str): - The API group of the resource. "*" means all. - ns (str): - Namespace of the action being requested. - Currently, there is no distinction between no - namespace and all namespaces. Both are - represented by "" (empty). - name (str): - The name of the resource being requested. - Empty means all. - resource (str): - The optional resource type requested. "*" means all. - subresource (str): - The optional subresource type. - verb (str): - A Kubernetes resource API verb, like get, list, watch, - create, update, delete, proxy. "*" means all. - version (str): - The API version of the resource. "*" means all. - """ - - group: str = proto.Field( - proto.STRING, - number=1, - ) - ns: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - resource: str = proto.Field( - proto.STRING, - number=4, - ) - subresource: str = proto.Field( - proto.STRING, - number=5, - ) - verb: str = proto.Field( - proto.STRING, - number=6, - ) - version: str = proto.Field( - proto.STRING, - number=7, - ) - - class Object(proto.Message): - r"""Kubernetes object related to the finding, uniquely identified - by GKNN. Used if the object Kind is not one of Pod, Node, - NodePool, Binding, or AccessReview. - - Attributes: - group (str): - Kubernetes object group, such as - "policy.k8s.io/v1". - kind (str): - Kubernetes object kind, such as "Namespace". - ns (str): - Kubernetes object namespace. Must be a valid - DNS label. Named "ns" to avoid collision with - C++ namespace keyword. For details see - https://kubernetes.io/docs/tasks/administer-cluster/namespaces/. - name (str): - Kubernetes object name. For details see - https://kubernetes.io/docs/concepts/overview/working-with-objects/names/. - containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): - Pod containers associated with this finding, - if any. - """ - - group: str = proto.Field( - proto.STRING, - number=1, - ) - kind: str = proto.Field( - proto.STRING, - number=2, - ) - ns: str = proto.Field( - proto.STRING, - number=3, - ) - name: str = proto.Field( - proto.STRING, - number=4, - ) - containers: MutableSequence[container.Container] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=container.Container, - ) - - pods: MutableSequence[Pod] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Pod, - ) - nodes: MutableSequence[Node] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Node, - ) - node_pools: MutableSequence[NodePool] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=NodePool, - ) - roles: MutableSequence[Role] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=Role, - ) - bindings: MutableSequence[Binding] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Binding, - ) - access_reviews: MutableSequence[AccessReview] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=AccessReview, - ) - objects: MutableSequence[Object] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Object, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.py deleted file mode 100644 index d2f158e10cf6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.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.securitycenter.v2', - manifest={ - 'Label', - }, -) - - -class Label(proto.Message): - r"""Represents a generic name-value label. A label has separate name and - value fields to support filtering with the ``contains()`` function. - For more information, see `Filtering on array-type - fields `__. - - Attributes: - name (str): - Name of the label. - value (str): - Value that corresponds to the label's name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.py deleted file mode 100644 index 95c16ba76680..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.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.cloud.securitycenter.v2', - manifest={ - 'LoadBalancer', - }, -) - - -class LoadBalancer(proto.Message): - r"""Contains information related to the load balancer associated - with the finding. - - Attributes: - name (str): - The name of the load balancer associated with - the finding. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py deleted file mode 100644 index 673caf996bad..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py +++ /dev/null @@ -1,95 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'LogEntry', - 'CloudLoggingEntry', - }, -) - - -class LogEntry(proto.Message): - r"""An individual entry in a log. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - cloud_logging_entry (google.cloud.securitycenter_v2.types.CloudLoggingEntry): - An individual entry in a log stored in Cloud - Logging. - - This field is a member of `oneof`_ ``log_entry``. - """ - - cloud_logging_entry: 'CloudLoggingEntry' = proto.Field( - proto.MESSAGE, - number=1, - oneof='log_entry', - message='CloudLoggingEntry', - ) - - -class CloudLoggingEntry(proto.Message): - r"""Metadata taken from a `Cloud Logging - LogEntry `__ - - Attributes: - insert_id (str): - A unique identifier for the log entry. - log_id (str): - The type of the log (part of ``log_name``. ``log_name`` is - the resource name of the log to which this log entry - belongs). For example: - ``cloudresourcemanager.googleapis.com/activity`` Note that - this field is not URL-encoded, unlike in ``LogEntry``. - resource_container (str): - The organization, folder, or project of the - monitored resource that produced this log entry. - timestamp (google.protobuf.timestamp_pb2.Timestamp): - The time the event described by the log entry - occurred. - """ - - insert_id: str = proto.Field( - proto.STRING, - number=1, - ) - log_id: str = proto.Field( - proto.STRING, - number=2, - ) - resource_container: str = proto.Field( - proto.STRING, - number=3, - ) - timestamp: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.py deleted file mode 100644 index d0a5c04b7853..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'MitreAttack', - }, -) - - -class MitreAttack(proto.Message): - r"""MITRE ATT&CK tactics and techniques related to this finding. - See: https://attack.mitre.org - - Attributes: - primary_tactic (google.cloud.securitycenter_v2.types.MitreAttack.Tactic): - The MITRE ATT&CK tactic most closely - represented by this finding, if any. - primary_techniques (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Technique]): - The MITRE ATT&CK technique most closely represented by this - finding, if any. primary_techniques is a repeated field - because there are multiple levels of MITRE ATT&CK - techniques. If the technique most closely represented by - this finding is a sub-technique (e.g. - ``SCANNING_IP_BLOCKS``), both the sub-technique and its - parent technique(s) will be listed (e.g. - ``SCANNING_IP_BLOCKS``, ``ACTIVE_SCANNING``). - additional_tactics (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Tactic]): - Additional MITRE ATT&CK tactics related to - this finding, if any. - additional_techniques (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Technique]): - Additional MITRE ATT&CK techniques related to - this finding, if any, along with any of their - respective parent techniques. - version (str): - The MITRE ATT&CK version referenced by the - above fields. E.g. "8". - """ - class Tactic(proto.Enum): - r"""MITRE ATT&CK tactics that can be referenced by SCC findings. - See: https://attack.mitre.org/tactics/enterprise/ - - Values: - TACTIC_UNSPECIFIED (0): - Unspecified value. - RECONNAISSANCE (1): - TA0043 - RESOURCE_DEVELOPMENT (2): - TA0042 - INITIAL_ACCESS (5): - TA0001 - EXECUTION (3): - TA0002 - PERSISTENCE (6): - TA0003 - PRIVILEGE_ESCALATION (8): - TA0004 - DEFENSE_EVASION (7): - TA0005 - CREDENTIAL_ACCESS (9): - TA0006 - DISCOVERY (10): - TA0007 - LATERAL_MOVEMENT (11): - TA0008 - COLLECTION (12): - TA0009 - COMMAND_AND_CONTROL (4): - TA0011 - EXFILTRATION (13): - TA0010 - IMPACT (14): - TA0040 - """ - TACTIC_UNSPECIFIED = 0 - RECONNAISSANCE = 1 - RESOURCE_DEVELOPMENT = 2 - INITIAL_ACCESS = 5 - EXECUTION = 3 - PERSISTENCE = 6 - PRIVILEGE_ESCALATION = 8 - DEFENSE_EVASION = 7 - CREDENTIAL_ACCESS = 9 - DISCOVERY = 10 - LATERAL_MOVEMENT = 11 - COLLECTION = 12 - COMMAND_AND_CONTROL = 4 - EXFILTRATION = 13 - IMPACT = 14 - - class Technique(proto.Enum): - r"""MITRE ATT&CK techniques that can be referenced by SCC - findings. See: https://attack.mitre.org/techniques/enterprise/ - Next ID: 65 - - Values: - TECHNIQUE_UNSPECIFIED (0): - Unspecified value. - MASQUERADING (49): - T1036 - MATCH_LEGITIMATE_NAME_OR_LOCATION (50): - T1036.005 - BOOT_OR_LOGON_INITIALIZATION_SCRIPTS (37): - T1037 - STARTUP_ITEMS (38): - T1037.005 - NETWORK_SERVICE_DISCOVERY (32): - T1046 - PROCESS_DISCOVERY (56): - T1057 - COMMAND_AND_SCRIPTING_INTERPRETER (6): - T1059 - UNIX_SHELL (7): - T1059.004 - PYTHON (59): - T1059.006 - EXPLOITATION_FOR_PRIVILEGE_ESCALATION (63): - T1068 - PERMISSION_GROUPS_DISCOVERY (18): - T1069 - CLOUD_GROUPS (19): - T1069.003 - INDICATOR_REMOVAL_FILE_DELETION (64): - T1070.004 - APPLICATION_LAYER_PROTOCOL (45): - T1071 - DNS (46): - T1071.004 - SOFTWARE_DEPLOYMENT_TOOLS (47): - T1072 - VALID_ACCOUNTS (14): - T1078 - DEFAULT_ACCOUNTS (35): - T1078.001 - LOCAL_ACCOUNTS (15): - T1078.003 - CLOUD_ACCOUNTS (16): - T1078.004 - PROXY (9): - T1090 - EXTERNAL_PROXY (10): - T1090.002 - MULTI_HOP_PROXY (11): - T1090.003 - ACCOUNT_MANIPULATION (22): - T1098 - ADDITIONAL_CLOUD_CREDENTIALS (40): - T1098.001 - SSH_AUTHORIZED_KEYS (23): - T1098.004 - ADDITIONAL_CONTAINER_CLUSTER_ROLES (58): - T1098.006 - INGRESS_TOOL_TRANSFER (3): - T1105 - NATIVE_API (4): - T1106 - BRUTE_FORCE (44): - T1110 - SHARED_MODULES (5): - T1129 - ACCESS_TOKEN_MANIPULATION (33): - T1134 - TOKEN_IMPERSONATION_OR_THEFT (39): - T1134.001 - EXPLOIT_PUBLIC_FACING_APPLICATION (27): - T1190 - DOMAIN_POLICY_MODIFICATION (30): - T1484 - DATA_DESTRUCTION (29): - T1485 - SERVICE_STOP (52): - T1489 - INHIBIT_SYSTEM_RECOVERY (36): - T1490 - RESOURCE_HIJACKING (8): - T1496 - NETWORK_DENIAL_OF_SERVICE (17): - T1498 - CLOUD_SERVICE_DISCOVERY (48): - T1526 - STEAL_APPLICATION_ACCESS_TOKEN (42): - T1528 - ACCOUNT_ACCESS_REMOVAL (51): - T1531 - STEAL_WEB_SESSION_COOKIE (25): - T1539 - CREATE_OR_MODIFY_SYSTEM_PROCESS (24): - T1543 - ABUSE_ELEVATION_CONTROL_MECHANISM (34): - T1548 - UNSECURED_CREDENTIALS (13): - T1552 - MODIFY_AUTHENTICATION_PROCESS (28): - T1556 - IMPAIR_DEFENSES (31): - T1562 - DISABLE_OR_MODIFY_TOOLS (55): - T1562.001 - EXFILTRATION_OVER_WEB_SERVICE (20): - T1567 - EXFILTRATION_TO_CLOUD_STORAGE (21): - T1567.002 - DYNAMIC_RESOLUTION (12): - T1568 - LATERAL_TOOL_TRANSFER (41): - T1570 - MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE (26): - T1578 - CREATE_SNAPSHOT (54): - T1578.001 - CLOUD_INFRASTRUCTURE_DISCOVERY (53): - T1580 - OBTAIN_CAPABILITIES (43): - T1588 - ACTIVE_SCANNING (1): - T1595 - SCANNING_IP_BLOCKS (2): - T1595.001 - CONTAINER_ADMINISTRATION_COMMAND (60): - T1609 - ESCAPE_TO_HOST (61): - T1611 - CONTAINER_AND_RESOURCE_DISCOVERY (57): - T1613 - STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES (62): - T1649 - """ - TECHNIQUE_UNSPECIFIED = 0 - MASQUERADING = 49 - MATCH_LEGITIMATE_NAME_OR_LOCATION = 50 - BOOT_OR_LOGON_INITIALIZATION_SCRIPTS = 37 - STARTUP_ITEMS = 38 - NETWORK_SERVICE_DISCOVERY = 32 - PROCESS_DISCOVERY = 56 - COMMAND_AND_SCRIPTING_INTERPRETER = 6 - UNIX_SHELL = 7 - PYTHON = 59 - EXPLOITATION_FOR_PRIVILEGE_ESCALATION = 63 - PERMISSION_GROUPS_DISCOVERY = 18 - CLOUD_GROUPS = 19 - INDICATOR_REMOVAL_FILE_DELETION = 64 - APPLICATION_LAYER_PROTOCOL = 45 - DNS = 46 - SOFTWARE_DEPLOYMENT_TOOLS = 47 - VALID_ACCOUNTS = 14 - DEFAULT_ACCOUNTS = 35 - LOCAL_ACCOUNTS = 15 - CLOUD_ACCOUNTS = 16 - PROXY = 9 - EXTERNAL_PROXY = 10 - MULTI_HOP_PROXY = 11 - ACCOUNT_MANIPULATION = 22 - ADDITIONAL_CLOUD_CREDENTIALS = 40 - SSH_AUTHORIZED_KEYS = 23 - ADDITIONAL_CONTAINER_CLUSTER_ROLES = 58 - INGRESS_TOOL_TRANSFER = 3 - NATIVE_API = 4 - BRUTE_FORCE = 44 - SHARED_MODULES = 5 - ACCESS_TOKEN_MANIPULATION = 33 - TOKEN_IMPERSONATION_OR_THEFT = 39 - EXPLOIT_PUBLIC_FACING_APPLICATION = 27 - DOMAIN_POLICY_MODIFICATION = 30 - DATA_DESTRUCTION = 29 - SERVICE_STOP = 52 - INHIBIT_SYSTEM_RECOVERY = 36 - RESOURCE_HIJACKING = 8 - NETWORK_DENIAL_OF_SERVICE = 17 - CLOUD_SERVICE_DISCOVERY = 48 - STEAL_APPLICATION_ACCESS_TOKEN = 42 - ACCOUNT_ACCESS_REMOVAL = 51 - STEAL_WEB_SESSION_COOKIE = 25 - CREATE_OR_MODIFY_SYSTEM_PROCESS = 24 - ABUSE_ELEVATION_CONTROL_MECHANISM = 34 - UNSECURED_CREDENTIALS = 13 - MODIFY_AUTHENTICATION_PROCESS = 28 - IMPAIR_DEFENSES = 31 - DISABLE_OR_MODIFY_TOOLS = 55 - EXFILTRATION_OVER_WEB_SERVICE = 20 - EXFILTRATION_TO_CLOUD_STORAGE = 21 - DYNAMIC_RESOLUTION = 12 - LATERAL_TOOL_TRANSFER = 41 - MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE = 26 - CREATE_SNAPSHOT = 54 - CLOUD_INFRASTRUCTURE_DISCOVERY = 53 - OBTAIN_CAPABILITIES = 43 - ACTIVE_SCANNING = 1 - SCANNING_IP_BLOCKS = 2 - CONTAINER_ADMINISTRATION_COMMAND = 60 - ESCAPE_TO_HOST = 61 - CONTAINER_AND_RESOURCE_DISCOVERY = 57 - STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES = 62 - - primary_tactic: Tactic = proto.Field( - proto.ENUM, - number=1, - enum=Tactic, - ) - primary_techniques: MutableSequence[Technique] = proto.RepeatedField( - proto.ENUM, - number=2, - enum=Technique, - ) - additional_tactics: MutableSequence[Tactic] = proto.RepeatedField( - proto.ENUM, - number=3, - enum=Tactic, - ) - additional_techniques: MutableSequence[Technique] = proto.RepeatedField( - proto.ENUM, - number=4, - enum=Technique, - ) - version: str = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.py deleted file mode 100644 index 47f95ac38c38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.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.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'MuteConfig', - }, -) - - -class MuteConfig(proto.Message): - r"""A mute config is a Cloud SCC resource that contains the - configuration to mute create/update events of findings. - - Attributes: - name (str): - Identifier. This field will be ignored if provided on config - creation. The following list shows some examples of the - format: - - - ``organizations/{organization}/muteConfigs/{mute_config}`` - - - - ``organizations/{organization}locations/{location}//muteConfigs/{mute_config}`` - - - ``folders/{folder}/muteConfigs/{mute_config}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{mute_config}`` - - ``projects/{project}/muteConfigs/{mute_config}`` - - ``projects/{project}/locations/{location}/muteConfigs/{mute_config}`` - description (str): - A description of the mute config. - filter (str): - Required. An expression that defines the filter to apply - across create/update events of findings. While creating a - filter string, be mindful of the scope in which the mute - configuration is being created. E.g., If a filter contains - project = X but is created under the project = Y scope, it - might not match any findings. - - The following field and operator combinations are supported: - - - severity: ``=``, ``:`` - - category: ``=``, ``:`` - - resource.name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.folders.resource_folder: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - - finding_class: ``=``, ``:`` - - indicator.ip_addresses: ``=``, ``:`` - - indicator.domains: ``=``, ``:`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the mute - config was created. This field is set by the - server and will be ignored if provided on config - creation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The most recent time at which - the mute config was updated. This field is set - by the server and will be ignored if provided on - config creation or update. - most_recent_editor (str): - Output only. Email address of the user who - last edited the mute config. This field is set - by the server and will be ignored if provided on - config creation or update. - type_ (google.cloud.securitycenter_v2.types.MuteConfig.MuteConfigType): - Required. The type of the mute config, which - determines what type of mute state the config - affects. Immutable after creation. - expiry_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The expiry of the mute config. Only - applicable for dynamic configs. If the expiry is - set, when the config expires, it is removed from - all findings. - """ - class MuteConfigType(proto.Enum): - r"""The type of MuteConfig. - - Values: - MUTE_CONFIG_TYPE_UNSPECIFIED (0): - Unused. - STATIC (1): - A static mute config, which sets the static - mute state of future matching findings to muted. - Once the static mute state has been set, finding - or config modifications will not affect the - state. - DYNAMIC (2): - A dynamic mute config, which is applied to - existing and future matching findings, setting - their dynamic mute state to "muted". If the - config is updated or deleted, or a matching - finding is updated, such that the finding - doesn't match the config, the config will be - removed from the finding, and the finding's - dynamic mute state may become "unmuted" (unless - other configs still match). - """ - MUTE_CONFIG_TYPE_UNSPECIFIED = 0 - STATIC = 1 - DYNAMIC = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - filter: str = proto.Field( - proto.STRING, - number=3, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - most_recent_editor: str = proto.Field( - proto.STRING, - number=6, - ) - type_: MuteConfigType = proto.Field( - proto.ENUM, - number=8, - enum=MuteConfigType, - ) - expiry_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py deleted file mode 100644 index 6fe873edc33e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py +++ /dev/null @@ -1,72 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v2', - manifest={ - 'Notebook', - }, -) - - -class Notebook(proto.Message): - r"""Represents a Jupyter notebook IPYNB file, such as a `Colab - Enterprise - notebook `__ file, - that is associated with a finding. - - Attributes: - name (str): - The name of the notebook. - service (str): - The source notebook service, for example, - "Colab Enterprise". - last_author (str): - The user ID of the latest author to modify - the notebook. - notebook_update_time (google.protobuf.timestamp_pb2.Timestamp): - The most recent time the notebook was - updated. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - service: str = proto.Field( - proto.STRING, - number=2, - ) - last_author: str = proto.Field( - proto.STRING, - number=3, - ) - notebook_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py deleted file mode 100644 index 73797dfbbbb8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py +++ /dev/null @@ -1,129 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v2', - manifest={ - 'NotificationConfig', - }, -) - - -class NotificationConfig(proto.Message): - r"""Cloud Security Command Center (Cloud SCC) notification - configs. - A notification config is a Cloud SCC resource that contains the - configuration to send notifications for create/update events of - findings, assets and etc. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Identifier. The relative resource name of this notification - config. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - The following list shows some examples: + - ``organizations/{organization_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` - + - ``folders/{folder_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` - + - ``projects/{project_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` - description (str): - The description of the notification config - (max of 1024 characters). - pubsub_topic (str): - The Pub/Sub topic to send notifications to. Its format is - "projects/[project_id]/topics/[topic]". - service_account (str): - Output only. The service account that needs - "pubsub.topics.publish" permission to publish to - the Pub/Sub topic. - streaming_config (google.cloud.securitycenter_v2.types.NotificationConfig.StreamingConfig): - The config for triggering streaming-based - notifications. - - This field is a member of `oneof`_ ``notify_config``. - """ - - class StreamingConfig(proto.Message): - r"""The config for streaming-based notifications, which send each - event as soon as it is detected. - - Attributes: - filter (str): - Expression that defines the filter to apply across - create/update events of assets or findings as specified by - the event type. The expression is a list of zero or more - restrictions combined via logical operators ``AND`` and - ``OR``. Parentheses are supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - """ - - filter: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - pubsub_topic: str = proto.Field( - proto.STRING, - number=3, - ) - service_account: str = proto.Field( - proto.STRING, - number=4, - ) - streaming_config: StreamingConfig = proto.Field( - proto.MESSAGE, - number=5, - oneof='notify_config', - message=StreamingConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.py deleted file mode 100644 index cbe17b52c42a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import resource as gcs_resource - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'NotificationMessage', - }, -) - - -class NotificationMessage(proto.Message): - r"""Cloud SCC's Notification - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - notification_config_name (str): - Name of the notification config that - generated current notification. - finding (google.cloud.securitycenter_v2.types.Finding): - If it's a Finding based notification config, - this field will be populated. - - This field is a member of `oneof`_ ``event``. - resource (google.cloud.securitycenter_v2.types.Resource): - The Cloud resource tied to this - notification's Finding. - """ - - notification_config_name: str = proto.Field( - proto.STRING, - number=1, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=2, - oneof='event', - message=gcs_finding.Finding, - ) - resource: gcs_resource.Resource = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_resource.Resource, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.py deleted file mode 100644 index afd2ecb275f7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.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.cloud.securitycenter.v2', - manifest={ - 'OrgPolicy', - }, -) - - -class OrgPolicy(proto.Message): - r"""Contains information about the org policies associated with - the finding. - - Attributes: - name (str): - The resource name of the org policy. Example: - "organizations/{organization_id}/policies/{constraint_name}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py deleted file mode 100644 index 567e7cceaa35..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py +++ /dev/null @@ -1,136 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v2.types import file - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Process', - 'EnvironmentVariable', - }, -) - - -class Process(proto.Message): - r"""Represents an operating system process. - - Attributes: - name (str): - The process name, as displayed in utilities like ``top`` and - ``ps``. This name can be accessed through - ``/proc/[pid]/comm`` and changed with - ``prctl(PR_SET_NAME)``. - binary (google.cloud.securitycenter_v2.types.File): - File information for the process executable. - libraries (MutableSequence[google.cloud.securitycenter_v2.types.File]): - File information for libraries loaded by the - process. - script (google.cloud.securitycenter_v2.types.File): - When the process represents the invocation of a script, - ``binary`` provides information about the interpreter, while - ``script`` provides information about the script file - provided to the interpreter. - args (MutableSequence[str]): - Process arguments as JSON encoded strings. - arguments_truncated (bool): - True if ``args`` is incomplete. - env_variables (MutableSequence[google.cloud.securitycenter_v2.types.EnvironmentVariable]): - Process environment variables. - env_variables_truncated (bool): - True if ``env_variables`` is incomplete. - pid (int): - The process ID. - parent_pid (int): - The parent process ID. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - binary: file.File = proto.Field( - proto.MESSAGE, - number=2, - message=file.File, - ) - libraries: MutableSequence[file.File] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=file.File, - ) - script: file.File = proto.Field( - proto.MESSAGE, - number=4, - message=file.File, - ) - args: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - arguments_truncated: bool = proto.Field( - proto.BOOL, - number=6, - ) - env_variables: MutableSequence['EnvironmentVariable'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='EnvironmentVariable', - ) - env_variables_truncated: bool = proto.Field( - proto.BOOL, - number=8, - ) - pid: int = proto.Field( - proto.INT64, - number=9, - ) - parent_pid: int = proto.Field( - proto.INT64, - number=10, - ) - - -class EnvironmentVariable(proto.Message): - r"""A name-value pair representing an environment variable used - in an operating system process. - - Attributes: - name (str): - Environment variable name as a JSON encoded - string. - val (str): - Environment variable value as a JSON encoded - string. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - val: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.py deleted file mode 100644 index 491062813849..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.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 - -from google.cloud.securitycenter_v2.types import folder - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'CloudProvider', - 'Resource', - 'GcpMetadata', - 'AwsMetadata', - 'AzureMetadata', - 'ResourcePath', - }, -) - - -class CloudProvider(proto.Enum): - r"""The cloud provider the finding pertains to. - - Values: - CLOUD_PROVIDER_UNSPECIFIED (0): - The cloud provider is unspecified. - GOOGLE_CLOUD_PLATFORM (1): - The cloud provider is Google Cloud Platform. - AMAZON_WEB_SERVICES (2): - The cloud provider is Amazon Web Services. - MICROSOFT_AZURE (3): - The cloud provider is Microsoft Azure. - """ - CLOUD_PROVIDER_UNSPECIFIED = 0 - GOOGLE_CLOUD_PLATFORM = 1 - AMAZON_WEB_SERVICES = 2 - MICROSOFT_AZURE = 3 - - -class Resource(proto.Message): - r"""Information related to the Google Cloud 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): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - display_name (str): - The human readable name of the resource. - type_ (str): - The full resource type of the resource. - cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): - Indicates which cloud provider the finding is - from. - service (str): - The service or resource provider associated - with the resource. - location (str): - The region or location of the service (if - applicable). - gcp_metadata (google.cloud.securitycenter_v2.types.GcpMetadata): - The GCP metadata associated with the finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - aws_metadata (google.cloud.securitycenter_v2.types.AwsMetadata): - The AWS metadata associated with the finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - azure_metadata (google.cloud.securitycenter_v2.types.AzureMetadata): - The Azure metadata associated with the - finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - resource_path (google.cloud.securitycenter_v2.types.ResourcePath): - Provides the path to the resource within the - resource hierarchy. - resource_path_string (str): - A string representation of the resource path. For Google - Cloud, it has the format of - ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` - where there can be any number of folders. For AWS, it has - the format of - ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` - where there can be any number of organizational units. For - Azure, it has the format of - ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` - where there can be any number of management groups. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - type_: str = proto.Field( - proto.STRING, - number=3, - ) - cloud_provider: 'CloudProvider' = proto.Field( - proto.ENUM, - number=4, - enum='CloudProvider', - ) - service: str = proto.Field( - proto.STRING, - number=5, - ) - location: str = proto.Field( - proto.STRING, - number=6, - ) - gcp_metadata: 'GcpMetadata' = proto.Field( - proto.MESSAGE, - number=7, - oneof='cloud_provider_metadata', - message='GcpMetadata', - ) - aws_metadata: 'AwsMetadata' = proto.Field( - proto.MESSAGE, - number=8, - oneof='cloud_provider_metadata', - message='AwsMetadata', - ) - azure_metadata: 'AzureMetadata' = proto.Field( - proto.MESSAGE, - number=9, - oneof='cloud_provider_metadata', - message='AzureMetadata', - ) - resource_path: 'ResourcePath' = proto.Field( - proto.MESSAGE, - number=10, - message='ResourcePath', - ) - resource_path_string: str = proto.Field( - proto.STRING, - number=11, - ) - - -class GcpMetadata(proto.Message): - r"""GCP metadata associated with the resource, only applicable if - the finding's cloud provider is Google Cloud Platform. - - Attributes: - project (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The project ID that the resource belongs to. - parent (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (MutableSequence[google.cloud.securitycenter_v2.types.Folder]): - Output only. Contains a Folder message for - each folder in the assets ancestry. The first - folder is the deepest nested folder, and the - last folder is the folder directly under the - Organization. - organization (str): - The name of the organization that the - resource belongs to. - """ - - project: str = proto.Field( - proto.STRING, - number=1, - ) - project_display_name: str = proto.Field( - proto.STRING, - number=2, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=4, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=folder.Folder, - ) - organization: str = proto.Field( - proto.STRING, - number=6, - ) - - -class AwsMetadata(proto.Message): - r"""AWS metadata associated with the resource, only applicable if - the finding's cloud provider is Amazon Web Services. - - Attributes: - organization (google.cloud.securitycenter_v2.types.AwsMetadata.AwsOrganization): - The AWS organization associated with the - resource. - organizational_units (MutableSequence[google.cloud.securitycenter_v2.types.AwsMetadata.AwsOrganizationalUnit]): - A list of AWS organizational units associated - with the resource, ordered from lowest level - (closest to the account) to highest level. - account (google.cloud.securitycenter_v2.types.AwsMetadata.AwsAccount): - The AWS account associated with the resource. - """ - - class AwsOrganization(proto.Message): - r"""An organization is a collection of accounts that are - centrally managed together using consolidated billing, organized - hierarchically with organizational units (OUs), and controlled - with policies. - - Attributes: - id (str): - The unique identifier (ID) for the - organization. The regex pattern for an - organization ID string requires "o-" followed by - from 10 to 32 lowercase letters or digits. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - - class AwsOrganizationalUnit(proto.Message): - r"""An Organizational Unit (OU) is a container of AWS accounts - within a root of an organization. Policies that are attached to - an OU apply to all accounts contained in that OU and in any - child OUs. - - Attributes: - id (str): - The unique identifier (ID) associated with - this OU. The regex pattern for an organizational - unit ID string requires "ou-" followed by from 4 - to 32 lowercase letters or digits (the ID of the - root that contains the OU). This string is - followed by a second "-" dash and from 8 to 32 - additional lowercase letters or digits. For - example, "ou-ab12-cd34ef56". - name (str): - The friendly name of the OU. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - - class AwsAccount(proto.Message): - r"""An AWS account that is a member of an organization. - - Attributes: - id (str): - The unique identifier (ID) of the account, - containing exactly 12 digits. - name (str): - The friendly name of this account. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - - organization: AwsOrganization = proto.Field( - proto.MESSAGE, - number=1, - message=AwsOrganization, - ) - organizational_units: MutableSequence[AwsOrganizationalUnit] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=AwsOrganizationalUnit, - ) - account: AwsAccount = proto.Field( - proto.MESSAGE, - number=3, - message=AwsAccount, - ) - - -class AzureMetadata(proto.Message): - r"""Azure metadata associated with the resource, only applicable - if the finding's cloud provider is Microsoft Azure. - - Attributes: - management_groups (MutableSequence[google.cloud.securitycenter_v2.types.AzureMetadata.AzureManagementGroup]): - A list of Azure management groups associated - with the resource, ordered from lowest level - (closest to the subscription) to highest level. - subscription (google.cloud.securitycenter_v2.types.AzureMetadata.AzureSubscription): - The Azure subscription associated with the - resource. - resource_group (google.cloud.securitycenter_v2.types.AzureMetadata.AzureResourceGroup): - The Azure resource group associated with the - resource. - """ - - class AzureManagementGroup(proto.Message): - r"""Represents an Azure management group. - - Attributes: - id (str): - The UUID of the Azure management group, for example, - ``20000000-0001-0000-0000-000000000000``. - display_name (str): - The display name of the Azure management - group. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - class AzureSubscription(proto.Message): - r"""Represents an Azure subscription. - - Attributes: - id (str): - The UUID of the Azure subscription, for example, - ``291bba3f-e0a5-47bc-a099-3bdcb2a50a05``. - display_name (str): - The display name of the Azure subscription. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - class AzureResourceGroup(proto.Message): - r"""Represents an Azure resource group. - - Attributes: - name (str): - The name of the Azure resource group. This is - not a UUID. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - management_groups: MutableSequence[AzureManagementGroup] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=AzureManagementGroup, - ) - subscription: AzureSubscription = proto.Field( - proto.MESSAGE, - number=2, - message=AzureSubscription, - ) - resource_group: AzureResourceGroup = proto.Field( - proto.MESSAGE, - number=3, - message=AzureResourceGroup, - ) - - -class ResourcePath(proto.Message): - r"""Represents the path of resources leading up to the resource - this finding is about. - - Attributes: - nodes (MutableSequence[google.cloud.securitycenter_v2.types.ResourcePath.ResourcePathNode]): - The list of nodes that make the up resource - path, ordered from lowest level to highest - level. - """ - class ResourcePathNodeType(proto.Enum): - r"""The type of resource the node represents. - - Values: - RESOURCE_PATH_NODE_TYPE_UNSPECIFIED (0): - Node type is unspecified. - GCP_ORGANIZATION (1): - The node represents a Google Cloud - organization. - GCP_FOLDER (2): - The node represents a Google Cloud folder. - GCP_PROJECT (3): - The node represents a Google Cloud project. - AWS_ORGANIZATION (4): - The node represents an AWS organization. - AWS_ORGANIZATIONAL_UNIT (5): - The node represents an AWS organizational - unit. - AWS_ACCOUNT (6): - The node represents an AWS account. - AZURE_MANAGEMENT_GROUP (7): - The node represents an Azure management - group. - AZURE_SUBSCRIPTION (8): - The node represents an Azure subscription. - AZURE_RESOURCE_GROUP (9): - The node represents an Azure resource group. - """ - RESOURCE_PATH_NODE_TYPE_UNSPECIFIED = 0 - GCP_ORGANIZATION = 1 - GCP_FOLDER = 2 - GCP_PROJECT = 3 - AWS_ORGANIZATION = 4 - AWS_ORGANIZATIONAL_UNIT = 5 - AWS_ACCOUNT = 6 - AZURE_MANAGEMENT_GROUP = 7 - AZURE_SUBSCRIPTION = 8 - AZURE_RESOURCE_GROUP = 9 - - class ResourcePathNode(proto.Message): - r"""A node within the resource path. Each node represents a - resource within the resource hierarchy. - - Attributes: - node_type (google.cloud.securitycenter_v2.types.ResourcePath.ResourcePathNodeType): - The type of resource this node represents. - id (str): - The ID of the resource this node represents. - display_name (str): - The display name of the resource this node - represents. - """ - - node_type: 'ResourcePath.ResourcePathNodeType' = proto.Field( - proto.ENUM, - number=1, - enum='ResourcePath.ResourcePathNodeType', - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - - nodes: MutableSequence[ResourcePathNode] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ResourcePathNode, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py deleted file mode 100644 index 49a600dd79e3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py +++ /dev/null @@ -1,190 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v2.types import resource -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'ResourceValue', - 'ResourceValueConfig', - }, -) - - -class ResourceValue(proto.Enum): - r"""Value enum to map to a resource - - Values: - RESOURCE_VALUE_UNSPECIFIED (0): - Unspecific value - HIGH (1): - High resource value - MEDIUM (2): - Medium resource value - LOW (3): - Low resource value - NONE (4): - No resource value, e.g. ignore these - resources - """ - RESOURCE_VALUE_UNSPECIFIED = 0 - HIGH = 1 - MEDIUM = 2 - LOW = 3 - NONE = 4 - - -class ResourceValueConfig(proto.Message): - r"""A resource value configuration (RVC) is a mapping - configuration of user's resources to resource values. Used in - Attack path simulations. - - Attributes: - name (str): - Identifier. Name for the resource value - configuration - resource_value (google.cloud.securitycenter_v2.types.ResourceValue): - Resource value level this expression - represents Only required when there is no - Sensitive Data Protection mapping in the request - tag_values (MutableSequence[str]): - Tag values combined with ``AND`` to check against. Values in - the form "tagValues/123" Example: - ``[ "tagValues/123", "tagValues/456", "tagValues/789" ]`` - https://cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing - resource_type (str): - Apply resource_value only to resources that match - resource_type. resource_type will be checked with ``AND`` of - other resources. For example, - "storage.googleapis.com/Bucket" with resource_value "HIGH" - will apply "HIGH" value only to - "storage.googleapis.com/Bucket" resources. - scope (str): - Project or folder to scope this configuration to. For - example, "project/456" would apply this configuration only - to resources in "project/456" scope and will be checked with - ``AND`` of other resources. - resource_labels_selector (MutableMapping[str, str]): - List of resource labels to search for, evaluated with - ``AND``. For example, "resource_labels_selector": {"key": - "value", "env": "prod"} will match resources with labels - "key": "value" ``AND`` "env": "prod" - https://cloud.google.com/resource-manager/docs/creating-managing-labels - description (str): - Description of the resource value - configuration. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp this resource value - configuration was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp this resource value - configuration was last updated. - cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): - Cloud provider this configuration applies to - sensitive_data_protection_mapping (google.cloud.securitycenter_v2.types.ResourceValueConfig.SensitiveDataProtectionMapping): - A mapping of the sensitivity on Sensitive Data Protection - finding to resource values. This mapping can only be used in - combination with a resource_type that is related to - BigQuery, e.g. "bigquery.googleapis.com/Dataset". - """ - - class SensitiveDataProtectionMapping(proto.Message): - r"""Resource value mapping for Sensitive Data Protection findings If any - of these mappings have a resource value that is not unspecified, the - resource_value field will be ignored when reading this - configuration. - - Attributes: - high_sensitivity_mapping (google.cloud.securitycenter_v2.types.ResourceValue): - Resource value mapping for high-sensitivity - Sensitive Data Protection findings - medium_sensitivity_mapping (google.cloud.securitycenter_v2.types.ResourceValue): - Resource value mapping for medium-sensitivity - Sensitive Data Protection findings - """ - - high_sensitivity_mapping: 'ResourceValue' = proto.Field( - proto.ENUM, - number=1, - enum='ResourceValue', - ) - medium_sensitivity_mapping: 'ResourceValue' = proto.Field( - proto.ENUM, - number=2, - enum='ResourceValue', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - resource_value: 'ResourceValue' = proto.Field( - proto.ENUM, - number=2, - enum='ResourceValue', - ) - tag_values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - resource_type: str = proto.Field( - proto.STRING, - number=4, - ) - scope: str = proto.Field( - proto.STRING, - number=5, - ) - resource_labels_selector: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=6, - ) - description: str = proto.Field( - proto.STRING, - number=7, - ) - 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, - ) - cloud_provider: resource.CloudProvider = proto.Field( - proto.ENUM, - number=10, - enum=resource.CloudProvider, - ) - sensitive_data_protection_mapping: SensitiveDataProtectionMapping = proto.Field( - proto.MESSAGE, - number=11, - message=SensitiveDataProtectionMapping, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py deleted file mode 100644 index 69a449132422..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py +++ /dev/null @@ -1,101 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v2', - manifest={ - 'SecurityMarks', - }, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - The following list shows some examples: - - - ``organizations/{organization_id}/assets/{asset_id}/securityMarks`` - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` - marks (MutableMapping[str, str]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - canonical_name (str): - The canonical name of the marks. The following list shows - some examples: - - - ``organizations/{organization_id}/assets/{asset_id}/securityMarks`` - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` - - - ``folders/{folder_id}/assets/{asset_id}/securityMarks`` - - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks`` - + - ``folders/{folder_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` - - - ``projects/{project_number}/assets/{asset_id}/securityMarks`` - - - - ``projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks`` - + - ``projects/{project_number}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - marks: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.py deleted file mode 100644 index efa7cfc0b14d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'SecurityPosture', - }, -) - - -class SecurityPosture(proto.Message): - r"""Represents a posture that is deployed on Google Cloud by the - Security Command Center Posture Management service. A posture - contains one or more policy sets. A policy set is a group of - policies that enforce a set of security rules on Google Cloud. - - Attributes: - name (str): - Name of the posture, for example, ``CIS-Posture``. - revision_id (str): - The version of the posture, for example, ``c7cfa2a8``. - posture_deployment_resource (str): - The project, folder, or organization on which the posture is - deployed, for example, ``projects/{project_number}``. - posture_deployment (str): - The name of the posture deployment, for example, - ``organizations/{org_id}/posturedeployments/{posture_deployment_id}``. - changed_policy (str): - The name of the updated policy, for example, - ``projects/{project_id}/policies/{constraint_name}``. - policy_set (str): - The name of the updated policy set, for example, - ``cis-policyset``. - policy (str): - The ID of the updated policy, for example, - ``compute-policy-1``. - policy_drift_details (MutableSequence[google.cloud.securitycenter_v2.types.SecurityPosture.PolicyDriftDetails]): - The details about a change in an updated - policy that violates the deployed posture. - """ - - class PolicyDriftDetails(proto.Message): - r"""The policy field that violates the deployed posture and its - expected and detected values. - - Attributes: - field (str): - The name of the updated field, for example - constraint.implementation.policy_rules[0].enforce - expected_value (str): - The value of this field that was configured in a posture, - for example, ``true`` or - ``allowed_values={"projects/29831892"}``. - detected_value (str): - The detected value that violates the deployed posture, for - example, ``false`` or - ``allowed_values={"projects/22831892"}``. - """ - - field: str = proto.Field( - proto.STRING, - number=1, - ) - expected_value: str = proto.Field( - proto.STRING, - number=2, - ) - detected_value: str = proto.Field( - proto.STRING, - number=3, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - ) - posture_deployment_resource: str = proto.Field( - proto.STRING, - number=3, - ) - posture_deployment: str = proto.Field( - proto.STRING, - number=4, - ) - changed_policy: str = proto.Field( - proto.STRING, - number=5, - ) - policy_set: str = proto.Field( - proto.STRING, - number=6, - ) - policy: str = proto.Field( - proto.STRING, - number=7, - ) - policy_drift_details: MutableSequence[PolicyDriftDetails] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=PolicyDriftDetails, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py deleted file mode 100644 index fdc56c6556a4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py +++ /dev/null @@ -1,1932 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v2.types import attack_path -from google.cloud.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import resource as gcs_resource -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import valued_resource -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'BatchCreateResourceValueConfigsRequest', - 'BatchCreateResourceValueConfigsResponse', - 'BulkMuteFindingsRequest', - 'BulkMuteFindingsResponse', - 'CreateBigQueryExportRequest', - 'CreateFindingRequest', - 'CreateMuteConfigRequest', - 'CreateNotificationConfigRequest', - 'CreateResourceValueConfigRequest', - 'CreateSourceRequest', - 'DeleteBigQueryExportRequest', - 'DeleteMuteConfigRequest', - 'DeleteNotificationConfigRequest', - 'DeleteResourceValueConfigRequest', - 'GetBigQueryExportRequest', - 'GetMuteConfigRequest', - 'GetNotificationConfigRequest', - 'GetResourceValueConfigRequest', - 'GetSourceRequest', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAttackPathsRequest', - 'ListAttackPathsResponse', - 'GetSimulationRequest', - 'GetValuedResourceRequest', - 'ListBigQueryExportsRequest', - 'ListBigQueryExportsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListMuteConfigsRequest', - 'ListMuteConfigsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListResourceValueConfigsRequest', - 'ListResourceValueConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListValuedResourcesRequest', - 'ListValuedResourcesResponse', - 'SetFindingStateRequest', - 'SetMuteRequest', - 'UpdateBigQueryExportRequest', - 'UpdateExternalSystemRequest', - 'UpdateFindingRequest', - 'UpdateMuteConfigRequest', - 'UpdateNotificationConfigRequest', - 'UpdateResourceValueConfigRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - }, -) - - -class BatchCreateResourceValueConfigsRequest(proto.Message): - r"""Request message to create multiple resource value configs - - Attributes: - parent (str): - Required. Resource name of the new - ResourceValueConfig's parent. The parent field - in the CreateResourceValueConfigRequest messages - must either be empty or match this field. - requests (MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]): - Required. The resource value configs to be - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - requests: MutableSequence['CreateResourceValueConfigRequest'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='CreateResourceValueConfigRequest', - ) - - -class BatchCreateResourceValueConfigsResponse(proto.Message): - r"""Response message for BatchCreateResourceValueConfigs - - Attributes: - resource_value_configs (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfig]): - The resource value configs created - """ - - resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_resource_value_config.ResourceValueConfig, - ) - - -class BulkMuteFindingsRequest(proto.Message): - r"""Request message for bulk findings update. - - Note: - - 1. If multiple bulk update requests match the same resource, the - order in which they get executed is not defined. - 2. Once a bulk operation is started, there is no way to stop it. - - Attributes: - parent (str): - Required. The parent, at which bulk action needs to be - applied. If no location is specified, findings are updated - in global. The following list shows some examples: - - - ``organizations/[organization_id]`` - - ``organizations/[organization_id]/locations/[location_id]`` - - ``folders/[folder_id]`` - - ``folders/[folder_id]/locations/[location_id]`` - - ``projects/[project_id]`` - - ``projects/[project_id]/locations/[location_id]`` - filter (str): - Expression that identifies findings that should be updated. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - mute_state (google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest.MuteState): - Optional. All findings matching the given filter will have - their mute state set to this value. The default value is - ``MUTED``. Setting this to ``UNDEFINED`` will clear the mute - state on all matching findings. - """ - class MuteState(proto.Enum): - r"""The mute state. - - Values: - MUTE_STATE_UNSPECIFIED (0): - Unused. - MUTED (1): - Matching findings will be muted (default). - UNDEFINED (2): - Matching findings will have their mute state - cleared. - """ - MUTE_STATE_UNSPECIFIED = 0 - MUTED = 1 - UNDEFINED = 2 - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - mute_state: MuteState = proto.Field( - proto.ENUM, - number=3, - enum=MuteState, - ) - - -class BulkMuteFindingsResponse(proto.Message): - r"""The response to a BulkMute request. Contains the LRO - information. - - """ - - -class CreateBigQueryExportRequest(proto.Message): - r"""Request message for creating a BigQuery export. - - Attributes: - parent (str): - Required. The name of the parent resource of the new - BigQuery export. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): - Required. The BigQuery export being created. - big_query_export_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must consist - of only lowercase letters, numbers, and hyphens, - must start with a letter, must end with either a - letter or a number, and must be 63 characters or - less. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - big_query_export: bigquery_export.BigQueryExport = proto.Field( - proto.MESSAGE, - number=2, - message=bigquery_export.BigQueryExport, - ) - big_query_export_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - - Attributes: - parent (str): - Required. Resource name of the new finding's parent. The - following list shows some examples of the format: + - ``organizations/[organization_id]/sources/[source_id]`` + - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - alphanumeric and less than or equal to 32 - characters and greater than 0 characters in - length. - finding (google.cloud.securitycenter_v2.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - finding_id: str = proto.Field( - proto.STRING, - number=2, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_finding.Finding, - ) - - -class CreateMuteConfigRequest(proto.Message): - r"""Request message for creating a mute config. - - Attributes: - parent (str): - Required. Resource name of the new mute configs's parent. - Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - mute_config (google.cloud.securitycenter_v2.types.MuteConfig): - Required. The mute config being created. - mute_config_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must consist - of only lowercase letters, numbers, and hyphens, - must start with a letter, must end with either a - letter or a number, and must be 63 characters or - less. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - mute_config: gcs_mute_config.MuteConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_mute_config.MuteConfig, - ) - mute_config_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class CreateNotificationConfigRequest(proto.Message): - r"""Request message for creating a notification config. - - Attributes: - parent (str): - Required. Resource name of the new notification config's - parent. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - config_id (str): - Required. - Unique identifier provided by the client within - the parent scope. It must be between 1 and 128 - characters and contain alphanumeric characters, - underscores, or hyphens only. - notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): - Required. The notification config being - created. The name and the service account will - be ignored as they are both output only fields - on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - config_id: str = proto.Field( - proto.STRING, - number=2, - ) - notification_config: gcs_notification_config.NotificationConfig = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_notification_config.NotificationConfig, - ) - - -class CreateResourceValueConfigRequest(proto.Message): - r"""Request message to create single resource value config - - Attributes: - parent (str): - Required. Resource name of the new - ResourceValueConfig's parent. - resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): - Required. The resource value config being - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_resource_value_config.ResourceValueConfig, - ) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be ``organizations/[organization_id]``. - source (google.cloud.securitycenter_v2.types.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_source.Source, - ) - - -class DeleteBigQueryExportRequest(proto.Message): - r"""Request message for deleting a BigQuery export. - - Attributes: - name (str): - Required. The name of the BigQuery export to delete. The - following list shows some examples of the format: - - - - - ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` - - - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` - - ``projects/{project}/locations/{location}/bigQueryExports/{export_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteMuteConfigRequest(proto.Message): - r"""Request message for deleting a mute config. If no location is - specified, default is global. - - Attributes: - name (str): - Required. Name of the mute config to delete. The following - list shows some examples of the format: - - - ``organizations/{organization}/muteConfigs/{config_id}`` - - - - ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` - - - ``folders/{folder}/muteConfigs/{config_id}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` - - ``projects/{project}/muteConfigs/{config_id}`` - - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteNotificationConfigRequest(proto.Message): - r"""Request message for deleting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to delete. The - following list shows some examples of the format: - - - - - ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` - + - ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_id]`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteResourceValueConfigRequest(proto.Message): - r"""Request message to delete resource value config - - Attributes: - name (str): - Required. Name of the ResourceValueConfig to - delete - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetBigQueryExportRequest(proto.Message): - r"""Request message for retrieving a BigQuery export. - - Attributes: - name (str): - Required. Name of the BigQuery export to retrieve. The - following list shows some examples of the format: - - - - - ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` - - - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` - - ``projects/{project}locations/{location}//bigQueryExports/{export_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetMuteConfigRequest(proto.Message): - r"""Request message for retrieving a mute config. If no location - is specified, default is global. - - Attributes: - name (str): - Required. Name of the mute config to retrieve. The following - list shows some examples of the format: - - - ``organizations/{organization}/muteConfigs/{config_id}`` - - - - ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` - - - ``folders/{folder}/muteConfigs/{config_id}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` - - ``projects/{project}/muteConfigs/{config_id}`` - - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetNotificationConfigRequest(proto.Message): - r"""Request message for getting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to get. The - following list shows some examples of the format: - - - - - ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_id]`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetResourceValueConfigRequest(proto.Message): - r"""Request message to get resource value config - - Attributes: - name (str): - Required. Name of the resource value config to retrieve. Its - format is - organizations/{organization}/resourceValueConfigs/{config_id}. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is ``organizations/[organization_id]/source/[source_id]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - - Attributes: - parent (str): - Required. Name of the source to groupBy. If no location is - specified, finding is assumed to be in global. The following - list shows some examples: - - - ``organizations/[organization_id]/sources/[source_id]`` - - - - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - - ``folders/[folder_id]/sources/[source_id]`` - - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` - - ``projects/[project_id]/sources/[source_id]`` - - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` - - To groupBy across all sources provide a source_id of ``-``. - The following list shows some examples: - - - ``organizations/{organization_id}/sources/-`` - - ``organizations/{organization_id}/sources/-/locations/[location_id]`` - - ``folders/{folder_id}/sources/-`` - - ``folders/{folder_id}/sources/-/locations/[location_id]`` - - ``projects/{project_id}/sources/-`` - - ``projects/{project_id}/sources/-/locations/[location_id]`` - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - severity: ``=``, ``:`` - - - security_marks.marks: ``=``, ``:`` - - - resource: - - - resource.name: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "parent,resource_name". - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - page_size: int = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v2.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message=struct_pb2.Value, - ) - count: int = proto.Field( - proto.INT64, - number=2, - ) - - -class ListAttackPathsRequest(proto.Message): - r"""Request message for listing the attack paths for a given - simulation or valued resource. - - Attributes: - parent (str): - Required. Name of parent to list attack paths. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - filter (str): - The filter expression that filters the attack path in the - response. Supported fields: - - - ``valued_resources`` supports = - page_token (str): - The value returned by the last ``ListAttackPathsResponse``; - indicates that this is a continuation of a prior - ``ListAttackPaths`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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 ListAttackPathsResponse(proto.Message): - r"""Response message for listing the attack paths for a given - simulation or valued resource. - - Attributes: - attack_paths (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath]): - The attack paths that the attack path - simulation identified. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - attack_paths: MutableSequence[attack_path.AttackPath] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=attack_path.AttackPath, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetSimulationRequest(proto.Message): - r"""Request message for getting simulation. - Simulation name can include "latest" to retrieve the latest - simulation For example, "organizations/123/simulations/latest" - - Attributes: - name (str): - Required. The organization name or simulation name of this - simulation - - Valid format: - ``organizations/{organization}/simulations/latest`` - ``organizations/{organization}/simulations/{simulation}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetValuedResourceRequest(proto.Message): - r"""Request message for getting a valued resource. - - Attributes: - name (str): - Required. The name of this valued resource - - Valid format: - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListBigQueryExportsRequest(proto.Message): - r"""Request message for listing BigQuery exports at a given scope - e.g. organization, folder or project. - - Attributes: - parent (str): - Required. The parent, which owns the collection of BigQuery - exports. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - page_size (int): - The maximum number of configs to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - A page token, received from a previous - ``ListBigQueryExports`` call. Provide this to retrieve the - subsequent page. When paginating, all other parameters - provided to ``ListBigQueryExports`` 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 ListBigQueryExportsResponse(proto.Message): - r"""Response message for listing BigQuery exports. - - Attributes: - big_query_exports (MutableSequence[google.cloud.securitycenter_v2.types.BigQueryExport]): - The BigQuery exports from the specified - parent. - 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 - - big_query_exports: MutableSequence[bigquery_export.BigQueryExport] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=bigquery_export.BigQueryExport, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - - Attributes: - parent (str): - Required. Name of the source the findings belong to. If no - location is specified, the default is global. The following - list shows some examples: - - - ``organizations/[organization_id]/sources/[source_id]`` - - - - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - - ``folders/[folder_id]/sources/[source_id]`` - - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` - - ``projects/[project_id]/sources/[source_id]`` - - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` - - To list across all sources provide a source_id of ``-``. The - following list shows some examples: - - - ``organizations/{organization_id}/sources/-`` - - ``organizations/{organization_id}/sources/-/locations/{location_id}`` - - ``folders/{folder_id}/sources/-`` - - ``folders/{folder_id}/sources/-locations/{location_id}`` - - ``projects/{projects_id}/sources/-`` - - ``projects/{projects_id}/sources/-/locations/{location_id}`` - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - severity: ``=``, ``:`` - - - security_marks.marks: ``=``, ``:`` - - - resource: - - - resource.name: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - - resource.folders.resource_folder: ``=``, ``:`` - - resource.display_name: ``=``, ``:`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: "name,parent". The - default sorting order is ascending. To specify descending - order for a field, a suffix " desc" should be appended to - the field name. For example: "name desc,parent". Redundant - space characters in the syntax are insignificant. "name - desc,parent" and " name desc , parent " are equivalent. - - The following fields are supported: name parent state - category resource_name event_time security_marks.marks - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the Finding fields to - be listed in the response. An empty field mask - will list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=8, - ) - page_size: int = proto.Field( - proto.INT32, - number=9, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - - Attributes: - list_findings_results (MutableSequence[google.cloud.securitycenter_v2.types.ListFindingsResponse.ListFindingsResult]): - Findings matching the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - class ListFindingsResult(proto.Message): - r"""Result containing the Finding. - - Attributes: - finding (google.cloud.securitycenter_v2.types.Finding): - Finding matching the search request. - resource (google.cloud.securitycenter_v2.types.ListFindingsResponse.ListFindingsResult.Resource): - Output only. Resource that is associated with - this finding. - """ - - class Resource(proto.Message): - r"""Information related to the Google Cloud resource that is - associated with this finding. - - 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): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - display_name (str): - The human readable name of the resource. - type_ (str): - The full resource type of the resource. - cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): - Indicates which cloud provider the finding is - from. - service (str): - The service or resource provider associated - with the resource. - location (str): - The region or location of the service (if - applicable). - gcp_metadata (google.cloud.securitycenter_v2.types.GcpMetadata): - The GCP metadata associated with the finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - aws_metadata (google.cloud.securitycenter_v2.types.AwsMetadata): - The AWS metadata associated with the finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - azure_metadata (google.cloud.securitycenter_v2.types.AzureMetadata): - The Azure metadata associated with the - finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - resource_path (google.cloud.securitycenter_v2.types.ResourcePath): - Provides the path to the resource within the - resource hierarchy. - resource_path_string (str): - A string representation of the resource path. For Google - Cloud, it has the format of - ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` - where there can be any number of folders. For AWS, it has - the format of - ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` - where there can be any number of organizational units. For - Azure, it has the format of - ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` - where there can be any number of management groups. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - type_: str = proto.Field( - proto.STRING, - number=3, - ) - cloud_provider: gcs_resource.CloudProvider = proto.Field( - proto.ENUM, - number=4, - enum=gcs_resource.CloudProvider, - ) - service: str = proto.Field( - proto.STRING, - number=5, - ) - location: str = proto.Field( - proto.STRING, - number=6, - ) - gcp_metadata: gcs_resource.GcpMetadata = proto.Field( - proto.MESSAGE, - number=7, - oneof='cloud_provider_metadata', - message=gcs_resource.GcpMetadata, - ) - aws_metadata: gcs_resource.AwsMetadata = proto.Field( - proto.MESSAGE, - number=8, - oneof='cloud_provider_metadata', - message=gcs_resource.AwsMetadata, - ) - azure_metadata: gcs_resource.AzureMetadata = proto.Field( - proto.MESSAGE, - number=9, - oneof='cloud_provider_metadata', - message=gcs_resource.AzureMetadata, - ) - resource_path: gcs_resource.ResourcePath = proto.Field( - proto.MESSAGE, - number=10, - message=gcs_resource.ResourcePath, - ) - resource_path_string: str = proto.Field( - proto.STRING, - number=11, - ) - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - resource: 'ListFindingsResponse.ListFindingsResult.Resource' = proto.Field( - proto.MESSAGE, - number=3, - message='ListFindingsResponse.ListFindingsResult.Resource', - ) - - @property - def raw_page(self): - return self - - list_findings_results: MutableSequence[ListFindingsResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListFindingsResult, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class ListMuteConfigsRequest(proto.Message): - r"""Request message for listing mute configs at a given scope - e.g. organization, folder or project. If no location is - specified, default is global. - - Attributes: - parent (str): - Required. The parent, which owns the collection of mute - configs. Its format is - ``organizations/[organization_id]", "folders/[folder_id]``, - ``projects/[project_id]``, - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, - ``projects/[project_id]/locations/[location_id]``. - page_size (int): - The maximum number of configs to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - A page token, received from a previous ``ListMuteConfigs`` - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListMuteConfigs`` 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 ListMuteConfigsResponse(proto.Message): - r"""Response message for listing mute configs. - - Attributes: - mute_configs (MutableSequence[google.cloud.securitycenter_v2.types.MuteConfig]): - The mute configs from the specified parent. - 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 - - mute_configs: MutableSequence[gcs_mute_config.MuteConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_mute_config.MuteConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListNotificationConfigsRequest(proto.Message): - r"""Request message for listing notification configs. - - Attributes: - parent (str): - Required. The name of the parent in which to list the - notification configurations. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". - page_token (str): - The value returned by the last - ``ListNotificationConfigsResponse``; indicates that this is - a continuation of a prior ``ListNotificationConfigs`` call, - and that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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 ListNotificationConfigsResponse(proto.Message): - r"""Response message for listing notification configs. - - Attributes: - notification_configs (MutableSequence[google.cloud.securitycenter_v2.types.NotificationConfig]): - Notification configs belonging to the - requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - notification_configs: MutableSequence[gcs_notification_config.NotificationConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListResourceValueConfigsRequest(proto.Message): - r"""Request message to list resource value configs of a parent - - Attributes: - parent (str): - Required. The parent, which owns the collection of resource - value configs. Its format is - ``organizations/[organization_id]`` - page_size (int): - The maximum number of configs to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - A page token, received from a previous - ``ListResourceValueConfigs`` call. Provide this to retrieve - the subsequent page. - - When paginating, all other parameters provided to - ``ListResourceValueConfigs`` must match the call that - provided the page token. - - page_size can be specified, and the new page_size 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, - ) - - -class ListResourceValueConfigsResponse(proto.Message): - r"""Response message to list resource value configs - - Attributes: - resource_value_configs (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfig]): - The resource value configs from the specified - parent. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is empty, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_resource_value_config.ResourceValueConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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=7, - ) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - - Attributes: - sources (MutableSequence[google.cloud.securitycenter_v2.types.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListValuedResourcesRequest(proto.Message): - r"""Request message for listing the valued resources for a given - simulation. - - Attributes: - parent (str): - Required. Name of parent to list exposed resources. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - filter (str): - The filter expression that filters the valued resources in - the response. Supported fields: - - - ``resource_value`` supports = - - ``resource_type`` supports = - page_token (str): - The value returned by the last - ``ListValuedResourcesResponse``; indicates that this is a - continuation of a prior ``ListValuedResources`` call, and - that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - order_by (str): - Optional. The fields by which to order the valued resources - response. - - Supported fields: - - - ``exposed_score`` - - - ``resource_value`` - - - ``resource_type`` - - Values should be a comma separated list of fields. For - example: ``exposed_score,resource_value``. - - The default sorting order is descending. To specify - ascending or descending order for a field, append a " ASC" - or a " DESC" suffix, respectively; for example: - ``exposed_score DESC``. - """ - - 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, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListValuedResourcesResponse(proto.Message): - r"""Response message for listing the valued resources for a given - simulation. - - Attributes: - valued_resources (MutableSequence[google.cloud.securitycenter_v2.types.ValuedResource]): - The valued resources that the attack path - simulation identified. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The estimated total number of results - matching the query. - """ - - @property - def raw_page(self): - return self - - valued_resources: MutableSequence[valued_resource.ValuedResource] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=valued_resource.ValuedResource, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - - Attributes: - name (str): - Required. The `relative resource - name `__ - of the finding. If no location is specified, finding is - assumed to be in global. The following list shows some - examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - state (google.cloud.securitycenter_v2.types.Finding.State): - Required. The desired State of the finding. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: gcs_finding.Finding.State = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.State, - ) - - -class SetMuteRequest(proto.Message): - r"""Request message for updating a finding's mute status. - - Attributes: - name (str): - Required. The `relative resource - name `__ - of the finding. If no location is specified, finding is - assumed to be in global. The following list shows some - examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - mute (google.cloud.securitycenter_v2.types.Finding.Mute): - Required. The desired state of the Mute. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - mute: gcs_finding.Finding.Mute = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.Mute, - ) - - -class UpdateBigQueryExportRequest(proto.Message): - r"""Request message for updating a BigQuery export. - - Attributes: - big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): - Required. The BigQuery export being updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - If empty all mutable fields will be updated. - """ - - big_query_export: bigquery_export.BigQueryExport = proto.Field( - proto.MESSAGE, - number=1, - message=bigquery_export.BigQueryExport, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateExternalSystemRequest(proto.Message): - r"""Request message for updating a ExternalSystem resource. - - Attributes: - external_system (google.cloud.securitycenter_v2.types.ExternalSystem): - Required. The external system resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - external system resource. - If empty all mutable fields will be updated. - """ - - external_system: gcs_external_system.ExternalSystem = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_external_system.ExternalSystem, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - - Attributes: - finding (google.cloud.securitycenter_v2.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must be alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing source_properties. - Individual source_properties can be added/updated by using - "source_properties." in the field mask. - """ - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateMuteConfigRequest(proto.Message): - r"""Request message for updating a mute config. - - Attributes: - mute_config (google.cloud.securitycenter_v2.types.MuteConfig): - Required. The mute config being updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - If empty all mutable fields will be updated. - """ - - mute_config: gcs_mute_config.MuteConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_mute_config.MuteConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateNotificationConfigRequest(proto.Message): - r"""Request message for updating a notification config. - - Attributes: - notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): - Required. The notification config to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - notification config. - If empty all mutable fields will be updated. - """ - - notification_config: gcs_notification_config.NotificationConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateResourceValueConfigRequest(proto.Message): - r"""Request message to update resource value config - - Attributes: - resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): - Required. The resource value config being - updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. If empty all mutable - fields will be updated. - - To update nested fields, include the top level field in the - mask For example, to update gcp_metadata.resource_type, - include the "gcp_metadata" field mask - """ - - resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_resource_value_config.ResourceValueConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - - Attributes: - security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): - Required. The security marks resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If empty - or set to "marks", all marks will be replaced. Individual - marks can be updated using "marks.". - """ - - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_security_marks.SecurityMarks, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - - Attributes: - source (google.cloud.securitycenter_v2.types.Source): - Required. The source resource to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the source - resource. - If empty all mutable fields will be updated. - """ - - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - 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-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py deleted file mode 100644 index 5c64646490da..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py +++ /dev/null @@ -1,73 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v2.types import resource -from google.cloud.securitycenter_v2.types import valued_resource -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Simulation', - }, -) - - -class Simulation(proto.Message): - r"""Attack path simulation - - Attributes: - name (str): - Full resource name of the Simulation: - ``organizations/123/simulations/456`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time simulation was created - resource_value_configs_metadata (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfigMetadata]): - Resource value configurations' metadata used - in this simulation. Maximum of 100. - cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): - Indicates which cloud provider was used in - this simulation. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - resource_value_configs_metadata: MutableSequence[valued_resource.ResourceValueConfigMetadata] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=valued_resource.ResourceValueConfigMetadata, - ) - cloud_provider: resource.CloudProvider = proto.Field( - proto.ENUM, - number=4, - enum=resource.CloudProvider, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.py deleted file mode 100644 index 006e16a02f4a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Source', - }, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, and other tools. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and outdated or - insecure libraries.". - canonical_name (str): - The canonical name of the finding source. It's either - "organizations/{organization_id}/sources/{source_id}", - "folders/{folder_id}/sources/{source_id}", or - "projects/{project_number}/sources/{source_id}", depending - on the closest CRM ancestor of the resource associated with - the finding. - """ - - 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, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.py deleted file mode 100644 index e70d9aa2e281..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'ToxicCombination', - }, -) - - -class ToxicCombination(proto.Message): - r"""Contains details about a group of security issues that, when - the issues occur together, represent a greater risk than when - the issues occur independently. A group of such issues is - referred to as a toxic combination. - - Attributes: - attack_exposure_score (float): - The `Attack exposure - score `__ - of this toxic combination. The score is a measure of how - much this toxic combination exposes one or more high-value - resources to potential attack. - related_findings (MutableSequence[str]): - List of resource names of findings associated with this - toxic combination. For example, - ``organizations/123/sources/456/findings/789``. - """ - - attack_exposure_score: float = proto.Field( - proto.DOUBLE, - number=1, - ) - related_findings: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.py deleted file mode 100644 index ed481ba587b6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'ValuedResource', - 'ResourceValueConfigMetadata', - }, -) - - -class ValuedResource(proto.Message): - r"""A resource that is determined to have value to a user's - system - - Attributes: - name (str): - Valued resource name, for example, e.g.: - ``organizations/123/simulations/456/valuedResources/789`` - resource (str): - The `full resource - name `__ - of the valued resource. - resource_type (str): - The `resource - type `__ - of the valued resource. - display_name (str): - Human-readable name of the valued resource. - resource_value (google.cloud.securitycenter_v2.types.ValuedResource.ResourceValue): - How valuable this resource is. - exposed_score (float): - Exposed score for this valued resource. A - value of 0 means no exposure was detected - exposure. - resource_value_configs_used (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfigMetadata]): - List of resource value configurations' - metadata used to determine the value of this - resource. Maximum of 100. - """ - class ResourceValue(proto.Enum): - r"""How valuable the resource is. - - Values: - RESOURCE_VALUE_UNSPECIFIED (0): - The resource value isn't specified. - RESOURCE_VALUE_LOW (1): - This is a low-value resource. - RESOURCE_VALUE_MEDIUM (2): - This is a medium-value resource. - RESOURCE_VALUE_HIGH (3): - This is a high-value resource. - """ - RESOURCE_VALUE_UNSPECIFIED = 0 - RESOURCE_VALUE_LOW = 1 - RESOURCE_VALUE_MEDIUM = 2 - RESOURCE_VALUE_HIGH = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - resource: str = proto.Field( - proto.STRING, - number=2, - ) - resource_type: str = proto.Field( - proto.STRING, - number=3, - ) - display_name: str = proto.Field( - proto.STRING, - number=4, - ) - resource_value: ResourceValue = proto.Field( - proto.ENUM, - number=5, - enum=ResourceValue, - ) - exposed_score: float = proto.Field( - proto.DOUBLE, - number=6, - ) - resource_value_configs_used: MutableSequence['ResourceValueConfigMetadata'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='ResourceValueConfigMetadata', - ) - - -class ResourceValueConfigMetadata(proto.Message): - r"""Metadata about a ResourceValueConfig. For example, id and - name. - - Attributes: - name (str): - Resource value config name - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.py deleted file mode 100644 index 79c7e06db637..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.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. -# -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.securitycenter.v2', - manifest={ - 'Vulnerability', - 'Cve', - 'Reference', - 'Cvssv3', - 'Package', - 'SecurityBulletin', - }, -) - - -class Vulnerability(proto.Message): - r"""Refers to common vulnerability fields e.g. cve, cvss, cwe - etc. - - Attributes: - cve (google.cloud.securitycenter_v2.types.Cve): - CVE stands for Common Vulnerabilities and - Exposures (https://cve.mitre.org/about/) - offending_package (google.cloud.securitycenter_v2.types.Package): - The offending package is relevant to the - finding. - fixed_package (google.cloud.securitycenter_v2.types.Package): - The fixed package is relevant to the finding. - security_bulletin (google.cloud.securitycenter_v2.types.SecurityBulletin): - The security bulletin is relevant to this - finding. - """ - - cve: 'Cve' = proto.Field( - proto.MESSAGE, - number=1, - message='Cve', - ) - offending_package: 'Package' = proto.Field( - proto.MESSAGE, - number=2, - message='Package', - ) - fixed_package: 'Package' = proto.Field( - proto.MESSAGE, - number=3, - message='Package', - ) - security_bulletin: 'SecurityBulletin' = proto.Field( - proto.MESSAGE, - number=4, - message='SecurityBulletin', - ) - - -class Cve(proto.Message): - r"""CVE stands for Common Vulnerabilities and Exposures. Information - from the `CVE - record `__ that - describes this vulnerability. - - Attributes: - id (str): - The unique identifier for the vulnerability. - e.g. CVE-2021-34527 - references (MutableSequence[google.cloud.securitycenter_v2.types.Reference]): - Additional information about the CVE. - e.g. - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527 - cvssv3 (google.cloud.securitycenter_v2.types.Cvssv3): - Describe Common Vulnerability Scoring System - specified at - https://www.first.org/cvss/v3.1/specification-document - upstream_fix_available (bool): - Whether upstream fix is available for the - CVE. - impact (google.cloud.securitycenter_v2.types.Cve.RiskRating): - The potential impact of the vulnerability if - it was to be exploited. - exploitation_activity (google.cloud.securitycenter_v2.types.Cve.ExploitationActivity): - The exploitation activity of the - vulnerability in the wild. - observed_in_the_wild (bool): - Whether or not the vulnerability has been - observed in the wild. - zero_day (bool): - Whether or not the vulnerability was zero day - when the finding was published. - exploit_release_date (google.protobuf.timestamp_pb2.Timestamp): - Date the first publicly available exploit or - PoC was released. - """ - class RiskRating(proto.Enum): - r"""The possible values of impact of the vulnerability if it was - to be exploited. - - Values: - RISK_RATING_UNSPECIFIED (0): - Invalid or empty value. - LOW (1): - Exploitation would have little to no security - impact. - MEDIUM (2): - Exploitation would enable attackers to - perform activities, or could allow attackers to - have a direct impact, but would require - additional steps. - HIGH (3): - Exploitation would enable attackers to have a - notable direct impact without needing to - overcome any major mitigating factors. - CRITICAL (4): - Exploitation would fundamentally undermine - the security of affected systems, enable actors - to perform significant attacks with minimal - effort, with little to no mitigating factors to - overcome. - """ - RISK_RATING_UNSPECIFIED = 0 - LOW = 1 - MEDIUM = 2 - HIGH = 3 - CRITICAL = 4 - - class ExploitationActivity(proto.Enum): - r"""The possible values of exploitation activity of the - vulnerability in the wild. - - Values: - EXPLOITATION_ACTIVITY_UNSPECIFIED (0): - Invalid or empty value. - WIDE (1): - Exploitation has been reported or confirmed - to widely occur. - CONFIRMED (2): - Limited reported or confirmed exploitation - activities. - AVAILABLE (3): - Exploit is publicly available. - ANTICIPATED (4): - No known exploitation activity, but has a - high potential for exploitation. - NO_KNOWN (5): - No known exploitation activity. - """ - EXPLOITATION_ACTIVITY_UNSPECIFIED = 0 - WIDE = 1 - CONFIRMED = 2 - AVAILABLE = 3 - ANTICIPATED = 4 - NO_KNOWN = 5 - - id: str = proto.Field( - proto.STRING, - number=1, - ) - references: MutableSequence['Reference'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Reference', - ) - cvssv3: 'Cvssv3' = proto.Field( - proto.MESSAGE, - number=3, - message='Cvssv3', - ) - upstream_fix_available: bool = proto.Field( - proto.BOOL, - number=4, - ) - impact: RiskRating = proto.Field( - proto.ENUM, - number=5, - enum=RiskRating, - ) - exploitation_activity: ExploitationActivity = proto.Field( - proto.ENUM, - number=6, - enum=ExploitationActivity, - ) - observed_in_the_wild: bool = proto.Field( - proto.BOOL, - number=7, - ) - zero_day: bool = proto.Field( - proto.BOOL, - number=8, - ) - exploit_release_date: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - - -class Reference(proto.Message): - r"""Additional Links - - Attributes: - source (str): - Source of the reference e.g. NVD - uri (str): - Uri for the mentioned source e.g. - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527. - """ - - source: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Cvssv3(proto.Message): - r"""Common Vulnerability Scoring System version 3. - - Attributes: - base_score (float): - The base score is a function of the base - metric scores. - attack_vector (google.cloud.securitycenter_v2.types.Cvssv3.AttackVector): - Base Metrics - Represents the intrinsic characteristics of a - vulnerability that are constant over time and - across user environments. This metric reflects - the context by which vulnerability exploitation - is possible. - attack_complexity (google.cloud.securitycenter_v2.types.Cvssv3.AttackComplexity): - This metric describes the conditions beyond - the attacker's control that must exist in order - to exploit the vulnerability. - privileges_required (google.cloud.securitycenter_v2.types.Cvssv3.PrivilegesRequired): - This metric describes the level of privileges - an attacker must possess before successfully - exploiting the vulnerability. - user_interaction (google.cloud.securitycenter_v2.types.Cvssv3.UserInteraction): - This metric captures the requirement for a - human user, other than the attacker, to - participate in the successful compromise of the - vulnerable component. - scope (google.cloud.securitycenter_v2.types.Cvssv3.Scope): - The Scope metric captures whether a - vulnerability in one vulnerable component - impacts resources in components beyond its - security scope. - confidentiality_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): - This metric measures the impact to the - confidentiality of the information resources - managed by a software component due to a - successfully exploited vulnerability. - integrity_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): - This metric measures the impact to integrity - of a successfully exploited vulnerability. - availability_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): - This metric measures the impact to the - availability of the impacted component resulting - from a successfully exploited vulnerability. - """ - class AttackVector(proto.Enum): - r"""This metric reflects the context by which vulnerability - exploitation is possible. - - Values: - ATTACK_VECTOR_UNSPECIFIED (0): - Invalid value. - ATTACK_VECTOR_NETWORK (1): - The vulnerable component is bound to the - network stack and the set of possible attackers - extends beyond the other options listed below, - up to and including the entire Internet. - ATTACK_VECTOR_ADJACENT (2): - The vulnerable component is bound to the - network stack, but the attack is limited at the - protocol level to a logically adjacent topology. - ATTACK_VECTOR_LOCAL (3): - The vulnerable component is not bound to the - network stack and the attacker's path is via - read/write/execute capabilities. - ATTACK_VECTOR_PHYSICAL (4): - The attack requires the attacker to - physically touch or manipulate the vulnerable - component. - """ - ATTACK_VECTOR_UNSPECIFIED = 0 - ATTACK_VECTOR_NETWORK = 1 - ATTACK_VECTOR_ADJACENT = 2 - ATTACK_VECTOR_LOCAL = 3 - ATTACK_VECTOR_PHYSICAL = 4 - - class AttackComplexity(proto.Enum): - r"""This metric describes the conditions beyond the attacker's - control that must exist in order to exploit the vulnerability. - - Values: - ATTACK_COMPLEXITY_UNSPECIFIED (0): - Invalid value. - ATTACK_COMPLEXITY_LOW (1): - Specialized access conditions or extenuating - circumstances do not exist. An attacker can - expect repeatable success when attacking the - vulnerable component. - ATTACK_COMPLEXITY_HIGH (2): - A successful attack depends on conditions - beyond the attacker's control. That is, a - successful attack cannot be accomplished at - will, but requires the attacker to invest in - some measurable amount of effort in preparation - or execution against the vulnerable component - before a successful attack can be expected. - """ - ATTACK_COMPLEXITY_UNSPECIFIED = 0 - ATTACK_COMPLEXITY_LOW = 1 - ATTACK_COMPLEXITY_HIGH = 2 - - class PrivilegesRequired(proto.Enum): - r"""This metric describes the level of privileges an attacker - must possess before successfully exploiting the vulnerability. - - Values: - PRIVILEGES_REQUIRED_UNSPECIFIED (0): - Invalid value. - PRIVILEGES_REQUIRED_NONE (1): - The attacker is unauthorized prior to attack, - and therefore does not require any access to - settings or files of the vulnerable system to - carry out an attack. - PRIVILEGES_REQUIRED_LOW (2): - The attacker requires privileges that provide - basic user capabilities that could normally - affect only settings and files owned by a user. - Alternatively, an attacker with Low privileges - has the ability to access only non-sensitive - resources. - PRIVILEGES_REQUIRED_HIGH (3): - The attacker requires privileges that provide - significant (e.g., administrative) control over - the vulnerable component allowing access to - component-wide settings and files. - """ - PRIVILEGES_REQUIRED_UNSPECIFIED = 0 - PRIVILEGES_REQUIRED_NONE = 1 - PRIVILEGES_REQUIRED_LOW = 2 - PRIVILEGES_REQUIRED_HIGH = 3 - - class UserInteraction(proto.Enum): - r"""This metric captures the requirement for a human user, other - than the attacker, to participate in the successful compromise - of the vulnerable component. - - Values: - USER_INTERACTION_UNSPECIFIED (0): - Invalid value. - USER_INTERACTION_NONE (1): - The vulnerable system can be exploited - without interaction from any user. - USER_INTERACTION_REQUIRED (2): - Successful exploitation of this vulnerability - requires a user to take some action before the - vulnerability can be exploited. - """ - USER_INTERACTION_UNSPECIFIED = 0 - USER_INTERACTION_NONE = 1 - USER_INTERACTION_REQUIRED = 2 - - class Scope(proto.Enum): - r"""The Scope metric captures whether a vulnerability in one - vulnerable component impacts resources in components beyond its - security scope. - - Values: - SCOPE_UNSPECIFIED (0): - Invalid value. - SCOPE_UNCHANGED (1): - An exploited vulnerability can only affect - resources managed by the same security - authority. - SCOPE_CHANGED (2): - An exploited vulnerability can affect - resources beyond the security scope managed by - the security authority of the vulnerable - component. - """ - SCOPE_UNSPECIFIED = 0 - SCOPE_UNCHANGED = 1 - SCOPE_CHANGED = 2 - - class Impact(proto.Enum): - r"""The Impact metrics capture the effects of a successfully - exploited vulnerability on the component that suffers the worst - outcome that is most directly and predictably associated with - the attack. - - Values: - IMPACT_UNSPECIFIED (0): - Invalid value. - IMPACT_HIGH (1): - High impact. - IMPACT_LOW (2): - Low impact. - IMPACT_NONE (3): - No impact. - """ - IMPACT_UNSPECIFIED = 0 - IMPACT_HIGH = 1 - IMPACT_LOW = 2 - IMPACT_NONE = 3 - - base_score: float = proto.Field( - proto.DOUBLE, - number=1, - ) - attack_vector: AttackVector = proto.Field( - proto.ENUM, - number=2, - enum=AttackVector, - ) - attack_complexity: AttackComplexity = proto.Field( - proto.ENUM, - number=3, - enum=AttackComplexity, - ) - privileges_required: PrivilegesRequired = proto.Field( - proto.ENUM, - number=4, - enum=PrivilegesRequired, - ) - user_interaction: UserInteraction = proto.Field( - proto.ENUM, - number=5, - enum=UserInteraction, - ) - scope: Scope = proto.Field( - proto.ENUM, - number=6, - enum=Scope, - ) - confidentiality_impact: Impact = proto.Field( - proto.ENUM, - number=7, - enum=Impact, - ) - integrity_impact: Impact = proto.Field( - proto.ENUM, - number=8, - enum=Impact, - ) - availability_impact: Impact = proto.Field( - proto.ENUM, - number=9, - enum=Impact, - ) - - -class Package(proto.Message): - r"""Package is a generic definition of a package. - - Attributes: - package_name (str): - The name of the package where the - vulnerability was detected. - cpe_uri (str): - The CPE URI where the vulnerability was - detected. - package_type (str): - Type of package, for example, os, maven, or - go. - package_version (str): - The version of the package. - """ - - package_name: str = proto.Field( - proto.STRING, - number=1, - ) - cpe_uri: str = proto.Field( - proto.STRING, - number=2, - ) - package_type: str = proto.Field( - proto.STRING, - number=3, - ) - package_version: str = proto.Field( - proto.STRING, - number=4, - ) - - -class SecurityBulletin(proto.Message): - r"""SecurityBulletin are notifications of vulnerabilities of - Google products. - - Attributes: - bulletin_id (str): - ID of the bulletin corresponding to the - vulnerability. - submission_time (google.protobuf.timestamp_pb2.Timestamp): - Submission time of this Security Bulletin. - suggested_upgrade_version (str): - This represents a version that the cluster - receiving this notification should be upgraded - to, based on its current version. For example, - 1.15.0 - """ - - bulletin_id: str = proto.Field( - proto.STRING, - number=1, - ) - submission_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - suggested_upgrade_version: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v2/noxfile.py deleted file mode 100644 index cd78e7c39a06..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-securitycenter' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -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"): - 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/securitycenter_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"): - 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", - "grpcio", - "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/securitycenter_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( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): - # Ignore release of mypy 1.11.0 which may have a regression - 'mypy!=1.11.0', - '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-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py deleted file mode 100644 index e74e57a22631..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - requests = securitycenter_v2.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - - request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py deleted file mode 100644 index d6c2ad8428ff..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - requests = securitycenter_v2.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - - request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py deleted file mode 100644 index 4b2fd03c3f02..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_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 BulkMuteFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py deleted file mode 100644 index 743d1302b400..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_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 BulkMuteFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py deleted file mode 100644 index 1698ad6adc92..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_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 CreateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_create_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = await client.create_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py deleted file mode 100644 index becab1857b3c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_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 CreateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_create_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = client.create_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py deleted file mode 100644 index 3a2c089e9019..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_create_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py deleted file mode 100644 index 4294f4ffd397..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_create_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py deleted file mode 100644 index c858b59a6586..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_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 CreateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_create_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = await client.create_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py deleted file mode 100644 index a0de28b38bbd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_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 CreateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_create_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = client.create_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py deleted file mode 100644 index ae681f4e8f3e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_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 CreateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_create_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.create_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py deleted file mode 100644 index 0bf75d6458fd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_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 CreateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_create_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = client.create_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py deleted file mode 100644 index 9afb50b6e83e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_create_source(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py deleted file mode 100644 index af9c2b763cc6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_create_source(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py deleted file mode 100644 index 4aac72fa5605..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - await client.delete_big_query_export(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py deleted file mode 100644 index b278bde5e5ae..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - client.delete_big_query_export(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py deleted file mode 100644 index 10ceee02e146..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_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 DeleteMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_delete_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_mute_config(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py deleted file mode 100644 index a051c7c17741..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_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 DeleteMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_delete_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_mute_config(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py deleted file mode 100644 index fceb0255c2bd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_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 DeleteNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_delete_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_config(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py deleted file mode 100644 index 906f2a39092c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_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 DeleteNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_delete_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_config(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py deleted file mode 100644 index 191842b98c8f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_resource_value_config(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py deleted file mode 100644 index e8aac97d4f8d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_resource_value_config(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py deleted file mode 100644 index 14de594a963c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_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 GetBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = await client.get_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py deleted file mode 100644 index a8d4416456ab..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_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 GetBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = client.get_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py deleted file mode 100644 index 04061abcf9a4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py deleted file mode 100644 index 4d9d6d45b825..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py deleted file mode 100644 index 348376a0b9b4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_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 GetMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py deleted file mode 100644 index 84adb2a92f59..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_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 GetMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py deleted file mode 100644 index 73885369a61e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_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 GetNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py deleted file mode 100644 index 84d892dabf5f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_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 GetNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py deleted file mode 100644 index 4076aa39fbc6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_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 GetResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py deleted file mode 100644 index 814ba5a717d0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_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 GetResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py deleted file mode 100644 index 4cf61313cb96..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_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 GetSimulation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetSimulation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_simulation(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_simulation(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetSimulation_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py deleted file mode 100644 index 572655cf48c9..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_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 GetSimulation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetSimulation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_simulation(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = client.get_simulation(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetSimulation_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py deleted file mode 100644 index 685b7f0cc423..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_source(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py deleted file mode 100644 index a33bef8b910d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_source(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py deleted file mode 100644 index b0601f503c25..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_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 GetValuedResource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetValuedResource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_valued_resource(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_valued_resource(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetValuedResource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py deleted file mode 100644 index ed7d7630288d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_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 GetValuedResource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetValuedResource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_valued_resource(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_valued_resource(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetValuedResource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py deleted file mode 100644 index d829f16c868e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GroupFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_group_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py deleted file mode 100644 index d7e8c0a21523..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GroupFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_group_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py deleted file mode 100644 index ed648fdea30d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_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 ListAttackPaths -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListAttackPaths_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_attack_paths(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListAttackPaths_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py deleted file mode 100644 index bdecd1972ff1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_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 ListAttackPaths -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListAttackPaths_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_attack_paths(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListAttackPaths_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py deleted file mode 100644 index 405bc21b0f37..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_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 ListBigQueryExports -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py deleted file mode 100644 index ccb98f95fa3c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_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 ListBigQueryExports -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py deleted file mode 100644 index bb6c9e3c9bc9..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_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 securitycenter_v2 - - -async def sample_list_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py deleted file mode 100644 index 190548636c6f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_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 securitycenter_v2 - - -def sample_list_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py deleted file mode 100644 index 50ec2b1fd631..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_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 ListMuteConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_mute_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py deleted file mode 100644 index d28a0e6adb61..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_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 ListMuteConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_mute_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py deleted file mode 100644 index 7b12a639c763..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_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 ListNotificationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_notification_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py deleted file mode 100644 index d1cffc2d7793..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_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 ListNotificationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_notification_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py deleted file mode 100644 index 9f8a6124f4d6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_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 ListResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py deleted file mode 100644 index cfc3651b5540..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_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 ListResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py deleted file mode 100644 index 447f27ccaa16..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListSources_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_sources(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py deleted file mode 100644 index 9447d7eb91ee..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListSources_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_sources(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py deleted file mode 100644 index 1c17d84f91cb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_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 ListValuedResources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListValuedResources_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_valued_resources(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListValuedResources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py deleted file mode 100644 index 616675828d82..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_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 ListValuedResources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListValuedResources_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_valued_resources(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListValuedResources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py deleted file mode 100644 index 905eb5d7db22..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_SetFindingState_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_set_finding_state(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py deleted file mode 100644 index 339e22bde563..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_SetFindingState_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_set_finding_state(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py deleted file mode 100644 index 2c74d459d83f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py deleted file mode 100644 index 4e5ef3b13cbf..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py deleted file mode 100644 index fa80c37c66ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_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 SetMute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_SetMute_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_set_mute(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = await client.set_mute(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_SetMute_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py deleted file mode 100644 index 9355527a6bac..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_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 SetMute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_SetMute_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_set_mute(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = client.set_mute(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_SetMute_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py deleted file mode 100644 index 3ccd4f4848bb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py deleted file mode 100644 index 6df1fda9cf90..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py deleted file mode 100644 index 365c17bd2756..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_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 UpdateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateBigQueryExportRequest( - ) - - # Make the request - response = await client.update_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py deleted file mode 100644 index 18b99ec2462e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_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 UpdateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateBigQueryExportRequest( - ) - - # Make the request - response = client.update_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py deleted file mode 100644 index 179da29467bb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_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 UpdateExternalSystem -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_external_system(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateExternalSystemRequest( - ) - - # Make the request - response = await client.update_external_system(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py deleted file mode 100644 index 6a68970514cc..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_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 UpdateExternalSystem -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_external_system(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateExternalSystemRequest( - ) - - # Make the request - response = client.update_external_system(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py deleted file mode 100644 index 245e358b0eea..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py deleted file mode 100644 index 512e315aa049..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py deleted file mode 100644 index 7796c39566e2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_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 UpdateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = await client.update_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py deleted file mode 100644 index 920f6986fb3b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_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 UpdateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = client.update_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py deleted file mode 100644 index bed9621bb2ea..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_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 UpdateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateNotificationConfigRequest( - ) - - # Make the request - response = await client.update_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py deleted file mode 100644 index ed5516437b4d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_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 UpdateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateNotificationConfigRequest( - ) - - # Make the request - response = client.update_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py deleted file mode 100644 index 0ecd6b7d2fd5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_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 UpdateResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateResourceValueConfigRequest( - ) - - # Make the request - response = await client.update_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py deleted file mode 100644 index 2508104c843d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_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 UpdateResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateResourceValueConfigRequest( - ) - - # Make the request - response = client.update_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py deleted file mode 100644 index faf2900ce05c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_security_marks(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py deleted file mode 100644 index 9843735d4ad6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_security_marks(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py deleted file mode 100644 index 39f5bd6e19c2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_source(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py deleted file mode 100644 index f138fd97e1ec..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_source(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json deleted file mode 100644 index 3ebbbfe28b50..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json +++ /dev/null @@ -1,6607 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.securitycenter.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-cloud-securitycenter", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.batch_create_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BatchCreateResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BatchCreateResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "requests", - "type": "MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse", - "shortName": "batch_create_resource_value_configs" - }, - "description": "Sample for BatchCreateResourceValueConfigs", - "file": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.batch_create_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BatchCreateResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BatchCreateResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "requests", - "type": "MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse", - "shortName": "batch_create_resource_value_configs" - }, - "description": "Sample for BatchCreateResourceValueConfigs", - "file": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.bulk_mute_findings", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BulkMuteFindings", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BulkMuteFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "bulk_mute_findings" - }, - "description": "Sample for BulkMuteFindings", - "file": "securitycenter_v2_generated_security_center_bulk_mute_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v2_generated_security_center_bulk_mute_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.bulk_mute_findings", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BulkMuteFindings", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BulkMuteFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "bulk_mute_findings" - }, - "description": "Sample for BulkMuteFindings", - "file": "securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v2.types.BigQueryExport" - }, - { - "name": "big_query_export_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.BigQueryExport", - "shortName": "create_big_query_export" - }, - "description": "Sample for CreateBigQueryExport", - "file": "securitycenter_v2_generated_security_center_create_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v2_generated_security_center_create_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v2.types.BigQueryExport" - }, - { - "name": "big_query_export_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.BigQueryExport", - "shortName": "create_big_query_export" - }, - "description": "Sample for CreateBigQueryExport", - "file": "securitycenter_v2_generated_security_center_create_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v2_generated_security_center_create_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v2.types.Finding" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v2_generated_security_center_create_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateFinding_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": "securitycenter_v2_generated_security_center_create_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v2.types.Finding" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v2_generated_security_center_create_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateFinding_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": "securitycenter_v2_generated_security_center_create_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateMuteConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v2.types.MuteConfig" - }, - { - "name": "mute_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.cloud.securitycenter_v2.types.MuteConfig", - "shortName": "create_mute_config" - }, - "description": "Sample for CreateMuteConfig", - "file": "securitycenter_v2_generated_security_center_create_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v2_generated_security_center_create_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateMuteConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v2.types.MuteConfig" - }, - { - "name": "mute_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.cloud.securitycenter_v2.types.MuteConfig", - "shortName": "create_mute_config" - }, - "description": "Sample for CreateMuteConfig", - "file": "securitycenter_v2_generated_security_center_create_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v2_generated_security_center_create_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v2.types.NotificationConfig" - }, - { - "name": "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.cloud.securitycenter_v2.types.NotificationConfig", - "shortName": "create_notification_config" - }, - "description": "Sample for CreateNotificationConfig", - "file": "securitycenter_v2_generated_security_center_create_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v2_generated_security_center_create_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v2.types.NotificationConfig" - }, - { - "name": "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.cloud.securitycenter_v2.types.NotificationConfig", - "shortName": "create_notification_config" - }, - "description": "Sample for CreateNotificationConfig", - "file": "securitycenter_v2_generated_security_center_create_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v2_generated_security_center_create_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v2.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v2_generated_security_center_create_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_create_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v2.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v2_generated_security_center_create_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_create_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest" - }, - { - "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_big_query_export" - }, - "description": "Sample for DeleteBigQueryExport", - "file": "securitycenter_v2_generated_security_center_delete_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v2_generated_security_center_delete_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest" - }, - { - "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_big_query_export" - }, - "description": "Sample for DeleteBigQueryExport", - "file": "securitycenter_v2_generated_security_center_delete_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v2_generated_security_center_delete_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest" - }, - { - "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_mute_config" - }, - "description": "Sample for DeleteMuteConfig", - "file": "securitycenter_v2_generated_security_center_delete_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v2_generated_security_center_delete_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest" - }, - { - "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_mute_config" - }, - "description": "Sample for DeleteMuteConfig", - "file": "securitycenter_v2_generated_security_center_delete_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v2_generated_security_center_delete_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest" - }, - { - "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_config" - }, - "description": "Sample for DeleteNotificationConfig", - "file": "securitycenter_v2_generated_security_center_delete_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v2_generated_security_center_delete_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest" - }, - { - "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_config" - }, - "description": "Sample for DeleteNotificationConfig", - "file": "securitycenter_v2_generated_security_center_delete_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v2_generated_security_center_delete_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest" - }, - { - "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_resource_value_config" - }, - "description": "Sample for DeleteResourceValueConfig", - "file": "securitycenter_v2_generated_security_center_delete_resource_value_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v2_generated_security_center_delete_resource_value_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest" - }, - { - "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_resource_value_config" - }, - "description": "Sample for DeleteResourceValueConfig", - "file": "securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetBigQueryExportRequest" - }, - { - "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.securitycenter_v2.types.BigQueryExport", - "shortName": "get_big_query_export" - }, - "description": "Sample for GetBigQueryExport", - "file": "securitycenter_v2_generated_security_center_get_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetBigQueryExportRequest" - }, - { - "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.securitycenter_v2.types.BigQueryExport", - "shortName": "get_big_query_export" - }, - "description": "Sample for GetBigQueryExport", - "file": "securitycenter_v2_generated_security_center_get_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v2_generated_security_center_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v2_generated_security_center_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetMuteConfigRequest" - }, - { - "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.securitycenter_v2.types.MuteConfig", - "shortName": "get_mute_config" - }, - "description": "Sample for GetMuteConfig", - "file": "securitycenter_v2_generated_security_center_get_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetMuteConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetMuteConfigRequest" - }, - { - "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.securitycenter_v2.types.MuteConfig", - "shortName": "get_mute_config" - }, - "description": "Sample for GetMuteConfig", - "file": "securitycenter_v2_generated_security_center_get_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetMuteConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetNotificationConfigRequest" - }, - { - "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.securitycenter_v2.types.NotificationConfig", - "shortName": "get_notification_config" - }, - "description": "Sample for GetNotificationConfig", - "file": "securitycenter_v2_generated_security_center_get_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetNotificationConfigRequest" - }, - { - "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.securitycenter_v2.types.NotificationConfig", - "shortName": "get_notification_config" - }, - "description": "Sample for GetNotificationConfig", - "file": "securitycenter_v2_generated_security_center_get_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest" - }, - { - "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.securitycenter_v2.types.ResourceValueConfig", - "shortName": "get_resource_value_config" - }, - "description": "Sample for GetResourceValueConfig", - "file": "securitycenter_v2_generated_security_center_get_resource_value_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_resource_value_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest" - }, - { - "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.securitycenter_v2.types.ResourceValueConfig", - "shortName": "get_resource_value_config" - }, - "description": "Sample for GetResourceValueConfig", - "file": "securitycenter_v2_generated_security_center_get_resource_value_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_resource_value_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_simulation", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSimulation", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSimulation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetSimulationRequest" - }, - { - "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.securitycenter_v2.types.Simulation", - "shortName": "get_simulation" - }, - "description": "Sample for GetSimulation", - "file": "securitycenter_v2_generated_security_center_get_simulation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSimulation_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_simulation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_simulation", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSimulation", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSimulation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetSimulationRequest" - }, - { - "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.securitycenter_v2.types.Simulation", - "shortName": "get_simulation" - }, - "description": "Sample for GetSimulation", - "file": "securitycenter_v2_generated_security_center_get_simulation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSimulation_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_simulation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetSourceRequest" - }, - { - "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.securitycenter_v2.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v2_generated_security_center_get_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetSourceRequest" - }, - { - "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.securitycenter_v2.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v2_generated_security_center_get_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_valued_resource", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetValuedResource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetValuedResource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetValuedResourceRequest" - }, - { - "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.securitycenter_v2.types.ValuedResource", - "shortName": "get_valued_resource" - }, - "description": "Sample for GetValuedResource", - "file": "securitycenter_v2_generated_security_center_get_valued_resource_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetValuedResource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_valued_resource_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_valued_resource", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetValuedResource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetValuedResource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetValuedResourceRequest" - }, - { - "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.securitycenter_v2.types.ValuedResource", - "shortName": "get_valued_resource" - }, - "description": "Sample for GetValuedResource", - "file": "securitycenter_v2_generated_security_center_get_valued_resource_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetValuedResource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_valued_resource_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsAsyncPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v2_generated_security_center_group_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GroupFindings_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": "securitycenter_v2_generated_security_center_group_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v2_generated_security_center_group_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GroupFindings_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": "securitycenter_v2_generated_security_center_group_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_attack_paths", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListAttackPaths", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAttackPaths" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListAttackPathsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListAttackPathsAsyncPager", - "shortName": "list_attack_paths" - }, - "description": "Sample for ListAttackPaths", - "file": "securitycenter_v2_generated_security_center_list_attack_paths_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v2_generated_security_center_list_attack_paths_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_attack_paths", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListAttackPaths", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAttackPaths" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListAttackPathsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListAttackPathsPager", - "shortName": "list_attack_paths" - }, - "description": "Sample for ListAttackPaths", - "file": "securitycenter_v2_generated_security_center_list_attack_paths_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v2_generated_security_center_list_attack_paths_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_big_query_exports", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListBigQueryExports", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListBigQueryExports" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsAsyncPager", - "shortName": "list_big_query_exports" - }, - "description": "Sample for ListBigQueryExports", - "file": "securitycenter_v2_generated_security_center_list_big_query_exports_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v2_generated_security_center_list_big_query_exports_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_big_query_exports", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListBigQueryExports", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListBigQueryExports" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsPager", - "shortName": "list_big_query_exports" - }, - "description": "Sample for ListBigQueryExports", - "file": "securitycenter_v2_generated_security_center_list_big_query_exports_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v2_generated_security_center_list_big_query_exports_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListFindingsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListFindingsAsyncPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v2_generated_security_center_list_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListFindings_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": "securitycenter_v2_generated_security_center_list_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListFindingsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListFindingsPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v2_generated_security_center_list_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListFindings_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": "securitycenter_v2_generated_security_center_list_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_mute_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListMuteConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListMuteConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListMuteConfigsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsAsyncPager", - "shortName": "list_mute_configs" - }, - "description": "Sample for ListMuteConfigs", - "file": "securitycenter_v2_generated_security_center_list_mute_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v2_generated_security_center_list_mute_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_mute_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListMuteConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListMuteConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListMuteConfigsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsPager", - "shortName": "list_mute_configs" - }, - "description": "Sample for ListMuteConfigs", - "file": "securitycenter_v2_generated_security_center_list_mute_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v2_generated_security_center_list_mute_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_notification_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListNotificationConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListNotificationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsAsyncPager", - "shortName": "list_notification_configs" - }, - "description": "Sample for ListNotificationConfigs", - "file": "securitycenter_v2_generated_security_center_list_notification_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v2_generated_security_center_list_notification_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_notification_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListNotificationConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListNotificationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsPager", - "shortName": "list_notification_configs" - }, - "description": "Sample for ListNotificationConfigs", - "file": "securitycenter_v2_generated_security_center_list_notification_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v2_generated_security_center_list_notification_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsAsyncPager", - "shortName": "list_resource_value_configs" - }, - "description": "Sample for ListResourceValueConfigs", - "file": "securitycenter_v2_generated_security_center_list_resource_value_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v2_generated_security_center_list_resource_value_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsPager", - "shortName": "list_resource_value_configs" - }, - "description": "Sample for ListResourceValueConfigs", - "file": "securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListSourcesRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListSourcesAsyncPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v2_generated_security_center_list_sources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListSources_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": "securitycenter_v2_generated_security_center_list_sources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListSourcesRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListSourcesPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v2_generated_security_center_list_sources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListSources_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": "securitycenter_v2_generated_security_center_list_sources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_valued_resources", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListValuedResources", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListValuedResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListValuedResourcesRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesAsyncPager", - "shortName": "list_valued_resources" - }, - "description": "Sample for ListValuedResources", - "file": "securitycenter_v2_generated_security_center_list_valued_resources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v2_generated_security_center_list_valued_resources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_valued_resources", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListValuedResources", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListValuedResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListValuedResourcesRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesPager", - "shortName": "list_valued_resources" - }, - "description": "Sample for ListValuedResources", - "file": "securitycenter_v2_generated_security_center_list_valued_resources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v2_generated_security_center_list_valued_resources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v2.types.Finding.State" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v2_generated_security_center_set_finding_state_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_SetFindingState_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": "securitycenter_v2_generated_security_center_set_finding_state_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v2.types.Finding.State" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v2_generated_security_center_set_finding_state_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_SetFindingState_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": "securitycenter_v2_generated_security_center_set_finding_state_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v2_generated_security_center_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v2_generated_security_center_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_mute", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetMute", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetMute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.SetMuteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "mute", - "type": "google.cloud.securitycenter_v2.types.Finding.Mute" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Finding", - "shortName": "set_mute" - }, - "description": "Sample for SetMute", - "file": "securitycenter_v2_generated_security_center_set_mute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_SetMute_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": "securitycenter_v2_generated_security_center_set_mute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_mute", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetMute", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetMute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.SetMuteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "mute", - "type": "google.cloud.securitycenter_v2.types.Finding.Mute" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Finding", - "shortName": "set_mute" - }, - "description": "Sample for SetMute", - "file": "securitycenter_v2_generated_security_center_set_mute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_SetMute_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": "securitycenter_v2_generated_security_center_set_mute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v2_generated_security_center_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v2_generated_security_center_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v2.types.BigQueryExport" - }, - { - "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.securitycenter_v2.types.BigQueryExport", - "shortName": "update_big_query_export" - }, - "description": "Sample for UpdateBigQueryExport", - "file": "securitycenter_v2_generated_security_center_update_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v2_generated_security_center_update_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v2.types.BigQueryExport" - }, - { - "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.securitycenter_v2.types.BigQueryExport", - "shortName": "update_big_query_export" - }, - "description": "Sample for UpdateBigQueryExport", - "file": "securitycenter_v2_generated_security_center_update_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v2_generated_security_center_update_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_external_system", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateExternalSystem", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateExternalSystem" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest" - }, - { - "name": "external_system", - "type": "google.cloud.securitycenter_v2.types.ExternalSystem" - }, - { - "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.securitycenter_v2.types.ExternalSystem", - "shortName": "update_external_system" - }, - "description": "Sample for UpdateExternalSystem", - "file": "securitycenter_v2_generated_security_center_update_external_system_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v2_generated_security_center_update_external_system_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_external_system", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateExternalSystem", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateExternalSystem" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest" - }, - { - "name": "external_system", - "type": "google.cloud.securitycenter_v2.types.ExternalSystem" - }, - { - "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.securitycenter_v2.types.ExternalSystem", - "shortName": "update_external_system" - }, - "description": "Sample for UpdateExternalSystem", - "file": "securitycenter_v2_generated_security_center_update_external_system_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v2_generated_security_center_update_external_system_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v2.types.Finding" - }, - { - "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.securitycenter_v2.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v2_generated_security_center_update_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v2_generated_security_center_update_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v2.types.Finding" - }, - { - "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.securitycenter_v2.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v2_generated_security_center_update_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v2_generated_security_center_update_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v2.types.MuteConfig" - }, - { - "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.securitycenter_v2.types.MuteConfig", - "shortName": "update_mute_config" - }, - "description": "Sample for UpdateMuteConfig", - "file": "securitycenter_v2_generated_security_center_update_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v2_generated_security_center_update_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v2.types.MuteConfig" - }, - { - "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.securitycenter_v2.types.MuteConfig", - "shortName": "update_mute_config" - }, - "description": "Sample for UpdateMuteConfig", - "file": "securitycenter_v2_generated_security_center_update_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v2_generated_security_center_update_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v2.types.NotificationConfig" - }, - { - "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.securitycenter_v2.types.NotificationConfig", - "shortName": "update_notification_config" - }, - "description": "Sample for UpdateNotificationConfig", - "file": "securitycenter_v2_generated_security_center_update_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v2_generated_security_center_update_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v2.types.NotificationConfig" - }, - { - "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.securitycenter_v2.types.NotificationConfig", - "shortName": "update_notification_config" - }, - "description": "Sample for UpdateNotificationConfig", - "file": "securitycenter_v2_generated_security_center_update_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v2_generated_security_center_update_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest" - }, - { - "name": "resource_value_config", - "type": "google.cloud.securitycenter_v2.types.ResourceValueConfig" - }, - { - "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.securitycenter_v2.types.ResourceValueConfig", - "shortName": "update_resource_value_config" - }, - "description": "Sample for UpdateResourceValueConfig", - "file": "securitycenter_v2_generated_security_center_update_resource_value_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v2_generated_security_center_update_resource_value_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest" - }, - { - "name": "resource_value_config", - "type": "google.cloud.securitycenter_v2.types.ResourceValueConfig" - }, - { - "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.securitycenter_v2.types.ResourceValueConfig", - "shortName": "update_resource_value_config" - }, - "description": "Sample for UpdateResourceValueConfig", - "file": "securitycenter_v2_generated_security_center_update_resource_value_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v2_generated_security_center_update_resource_value_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v2.types.SecurityMarks" - }, - { - "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.securitycenter_v2.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v2_generated_security_center_update_security_marks_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v2_generated_security_center_update_security_marks_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v2.types.SecurityMarks" - }, - { - "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.securitycenter_v2.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v2_generated_security_center_update_security_marks_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v2_generated_security_center_update_security_marks_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v2.types.Source" - }, - { - "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.securitycenter_v2.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v2_generated_security_center_update_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSource_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": "securitycenter_v2_generated_security_center_update_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v2.types.Source" - }, - { - "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.securitycenter_v2.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v2_generated_security_center_update_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSource_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": "securitycenter_v2_generated_security_center_update_source_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py deleted file mode 100644 index f95da838422b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py +++ /dev/null @@ -1,215 +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 securitycenterCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_create_resource_value_configs': ('parent', 'requests', ), - 'bulk_mute_findings': ('parent', 'filter', 'mute_state', ), - 'create_big_query_export': ('parent', 'big_query_export', 'big_query_export_id', ), - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_mute_config': ('parent', 'mute_config', 'mute_config_id', ), - 'create_notification_config': ('parent', 'config_id', 'notification_config', ), - 'create_source': ('parent', 'source', ), - 'delete_big_query_export': ('name', ), - 'delete_mute_config': ('name', ), - 'delete_notification_config': ('name', ), - 'delete_resource_value_config': ('name', ), - 'get_big_query_export': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_mute_config': ('name', ), - 'get_notification_config': ('name', ), - 'get_resource_value_config': ('name', ), - 'get_simulation': ('name', ), - 'get_source': ('name', ), - 'get_valued_resource': ('name', ), - 'group_findings': ('parent', 'group_by', 'filter', 'page_token', 'page_size', ), - 'list_attack_paths': ('parent', 'filter', 'page_token', 'page_size', ), - 'list_big_query_exports': ('parent', 'page_size', 'page_token', ), - 'list_findings': ('parent', 'filter', 'order_by', 'field_mask', 'page_token', 'page_size', ), - 'list_mute_configs': ('parent', 'page_size', 'page_token', ), - 'list_notification_configs': ('parent', 'page_token', 'page_size', ), - 'list_resource_value_configs': ('parent', 'page_size', 'page_token', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'list_valued_resources': ('parent', 'filter', 'page_token', 'page_size', 'order_by', ), - 'set_finding_state': ('name', 'state', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'set_mute': ('name', 'mute', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_big_query_export': ('big_query_export', 'update_mask', ), - 'update_external_system': ('external_system', 'update_mask', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_mute_config': ('mute_config', 'update_mask', ), - 'update_notification_config': ('notification_config', 'update_mask', ), - 'update_resource_value_config': ('resource_value_config', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', ), - 'update_source': ('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=securitycenterCallTransformer(), -): - """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 securitycenter 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-securitycenter/v2/setup.py b/owl-bot-staging/google-cloud-securitycenter/v2/setup.py deleted file mode 100644 index c4538ec101f3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/setup.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. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-securitycenter' - - -description = "Google Cloud Securitycenter API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/securitycenter/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", - "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", -] -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" - -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_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-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py deleted file mode 100644 index 6104ead93daa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py +++ /dev/null @@ -1,31716 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -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 - -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.securitycenter_v2.services.security_center import SecurityCenterAsyncClient -from google.cloud.securitycenter_v2.services.security_center import SecurityCenterClient -from google.cloud.securitycenter_v2.services.security_center import pagers -from google.cloud.securitycenter_v2.services.security_center import transports -from google.cloud.securitycenter_v2.types import access -from google.cloud.securitycenter_v2.types import application -from google.cloud.securitycenter_v2.types import attack_exposure -from google.cloud.securitycenter_v2.types import attack_path -from google.cloud.securitycenter_v2.types import backup_disaster_recovery -from google.cloud.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import cloud_armor -from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile -from google.cloud.securitycenter_v2.types import cloud_dlp_inspection -from google.cloud.securitycenter_v2.types import compliance -from google.cloud.securitycenter_v2.types import connection -from google.cloud.securitycenter_v2.types import contact_details -from google.cloud.securitycenter_v2.types import container -from google.cloud.securitycenter_v2.types import database -from google.cloud.securitycenter_v2.types import exfiltration -from google.cloud.securitycenter_v2.types import external_system -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import file -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import group_membership -from google.cloud.securitycenter_v2.types import iam_binding -from google.cloud.securitycenter_v2.types import indicator -from google.cloud.securitycenter_v2.types import kernel_rootkit -from google.cloud.securitycenter_v2.types import kubernetes -from google.cloud.securitycenter_v2.types import label -from google.cloud.securitycenter_v2.types import load_balancer -from google.cloud.securitycenter_v2.types import log_entry -from google.cloud.securitycenter_v2.types import mitre_attack -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notebook -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import org_policy -from google.cloud.securitycenter_v2.types import process -from google.cloud.securitycenter_v2.types import resource -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import security_posture -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import toxic_combination -from google.cloud.securitycenter_v2.types import valued_resource -from google.cloud.securitycenter_v2.types import vulnerability -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 duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None - assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert SecurityCenterClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SecurityCenterGrpcTransport, "grpc"), - (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - 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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -def test_security_center_client_get_transport_class(): - transport = SecurityCenterClient.get_transport_class() - available_transports = [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterRestTransport, - ] - assert transport in available_transports - - transport = SecurityCenterClient.get_transport_class("grpc") - assert transport == transports.SecurityCenterGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, 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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), -]) -def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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_security_center_client_client_options_from_dict(): - with mock.patch('google.cloud.securitycenter_v2.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.BatchCreateResourceValueConfigsRequest, - dict, -]) -def test_batch_create_resource_value_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse( - ) - response = client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) - - -def test_batch_create_resource_value_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_create_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() - - -def test_batch_create_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.BatchCreateResourceValueConfigsRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_create_resource_value_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest( - parent='parent_value', - ) - -def test_batch_create_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc - request = {} - client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_resource_value_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_batch_create_resource_value_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( - )) - response = await client.batch_create_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() - -@pytest.mark.asyncio -async def test_batch_create_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.batch_create_resource_value_configs] = mock_object - - request = {} - await client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.batch_create_resource_value_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( - )) - response = await client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) - - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_async_from_dict(): - await test_batch_create_resource_value_configs_async(request_type=dict) - - -def test_batch_create_resource_value_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - client.batch_create_resource_value_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_batch_create_resource_value_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) - await client.batch_create_resource_value_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_batch_create_resource_value_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.batch_create_resource_value_configs( - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(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 - arg = args[0].requests - mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] - assert arg == mock_val - - -def test_batch_create_resource_value_configs_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_create_resource_value_configs( - securitycenter_service.BatchCreateResourceValueConfigsRequest(), - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], - ) - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_create_resource_value_configs( - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(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 - arg = args[0].requests - mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.batch_create_resource_value_configs( - securitycenter_service.BatchCreateResourceValueConfigsRequest(), - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.BulkMuteFindingsRequest, - dict, -]) -def test_bulk_mute_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.bulk_mute_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BulkMuteFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_bulk_mute_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.bulk_mute_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BulkMuteFindingsRequest() - - -def test_bulk_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.BulkMuteFindingsRequest( - parent='parent_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.bulk_mute_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BulkMuteFindingsRequest( - parent='parent_value', - filter='filter_value', - ) - -def test_bulk_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc - request = {} - client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BulkMuteFindingsRequest() - -@pytest.mark.asyncio -async def test_bulk_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.bulk_mute_findings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.bulk_mute_findings] = mock_object - - request = {} - await client.bulk_mute_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.bulk_mute_findings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_bulk_mute_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BulkMuteFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BulkMuteFindingsRequest() - 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_bulk_mute_findings_async_from_dict(): - await test_bulk_mute_findings_async(request_type=dict) - - -def test_bulk_mute_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BulkMuteFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.bulk_mute_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_bulk_mute_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BulkMuteFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.bulk_mute_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_bulk_mute_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings( - 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_bulk_mute_findings_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.bulk_mute_findings( - securitycenter_service.BulkMuteFindingsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_bulk_mute_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings( - 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_bulk_mute_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.bulk_mute_findings( - securitycenter_service.BulkMuteFindingsRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateBigQueryExportRequest, - dict, -]) -def test_create_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - response = client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -def test_create_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateBigQueryExportRequest() - - -def test_create_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateBigQueryExportRequest( - parent='parent_value', - big_query_export_id='big_query_export_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateBigQueryExportRequest( - parent='parent_value', - big_query_export_id='big_query_export_id_value', - ) - -def test_create_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - request = {} - client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_big_query_export(request) - - # Establish that a new wrapper 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_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.create_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_create_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_big_query_export] = mock_object - - request = {} - await client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -@pytest.mark.asyncio -async def test_create_big_query_export_async_from_dict(): - await test_create_big_query_export_async(request_type=dict) - - -def test_create_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateBigQueryExportRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value = bigquery_export.BigQueryExport() - client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateBigQueryExportRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - await client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_big_query_export( - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_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].big_query_export - mock_val = bigquery_export.BigQueryExport(name='name_value') - assert arg == mock_val - arg = args[0].big_query_export_id - mock_val = 'big_query_export_id_value' - assert arg == mock_val - - -def test_create_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.CreateBigQueryExportRequest(), - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_id_value', - ) - -@pytest.mark.asyncio -async def test_create_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_big_query_export( - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_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].big_query_export - mock_val = bigquery_export.BigQueryExport(name='name_value') - assert arg == mock_val - arg = args[0].big_query_export_id - mock_val = 'big_query_export_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_big_query_export( - securitycenter_service.CreateBigQueryExportRequest(), - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_create_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.create_finding] = mock_rpc - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object - - request = {} - await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_create_finding_async_from_dict(): - await test_create_finding_async(request_type=dict) - - -def test_create_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_finding( - parent='parent_value', - finding=gcs_finding.Finding(name='name_value'), - finding_id='finding_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].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - - -def test_create_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding=gcs_finding.Finding(name='name_value'), - finding_id='finding_id_value', - ) - -@pytest.mark.asyncio -async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_finding( - parent='parent_value', - finding=gcs_finding.Finding(name='name_value'), - finding_id='finding_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].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding=gcs_finding.Finding(name='name_value'), - finding_id='finding_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateMuteConfigRequest, - dict, -]) -def test_create_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - ) - response = client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - - -def test_create_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateMuteConfigRequest() - - -def test_create_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateMuteConfigRequest( - parent='parent_value', - mute_config_id='mute_config_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateMuteConfigRequest( - parent='parent_value', - mute_config_id='mute_config_id_value', - ) - -def test_create_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - request = {} - client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.create_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateMuteConfigRequest() - -@pytest.mark.asyncio -async def test_create_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_mute_config] = mock_object - - request = {} - await client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - - -@pytest.mark.asyncio -async def test_create_mute_config_async_from_dict(): - await test_create_mute_config_async(request_type=dict) - -def test_create_mute_config_routing_parameters(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateMuteConfigRequest(**{"parent": "projects/sample1/locations/sample2"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.create_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateMuteConfigRequest(**{"parent": "organizations/sample1/locations/sample2"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.create_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateMuteConfigRequest(**{"parent": "folders/sample1/locations/sample2"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.create_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_create_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_mute_config( - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_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].mute_config - mock_val = gcs_mute_config.MuteConfig(name='name_value') - assert arg == mock_val - arg = args[0].mute_config_id - mock_val = 'mute_config_id_value' - assert arg == mock_val - - -def test_create_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.CreateMuteConfigRequest(), - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_mute_config( - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_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].mute_config - mock_val = gcs_mute_config.MuteConfig(name='name_value') - assert arg == mock_val - arg = args[0].mute_config_id - mock_val = 'mute_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_mute_config( - securitycenter_service.CreateMuteConfigRequest(), - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateNotificationConfigRequest, - dict, -]) -def test_create_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_create_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateNotificationConfigRequest( - parent='parent_value', - config_id='config_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest( - parent='parent_value', - config_id='config_id_value', - ) - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_create_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_notification_config] = mock_object - - request = {} - await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_create_notification_config_async_from_dict(): - await test_create_notification_config_async(request_type=dict) - - -def test_create_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.create_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.create_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_notification_config( - parent='parent_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - config_id='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].notification_config - mock_val = gcs_notification_config.NotificationConfig(name='name_value') - assert arg == mock_val - arg = args[0].config_id - mock_val = 'config_id_value' - assert arg == mock_val - - -def test_create_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - config_id='config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_notification_config( - parent='parent_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - config_id='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].notification_config - mock_val = gcs_notification_config.NotificationConfig(name='name_value') - assert arg == mock_val - arg = args[0].config_id - mock_val = 'config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_notification_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - config_id='config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_create_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object - - request = {} - await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_create_source_async_from_dict(): - await test_create_source_async(request_type=dict) - - -def test_create_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.create_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - - -def test_create_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteBigQueryExportRequest, - dict, -]) -def test_delete_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() - - -def test_delete_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteBigQueryExportRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteBigQueryExportRequest( - name='name_value', - ) - -def test_delete_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - request = {} - client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_big_query_export(request) - - # Establish that a new wrapper 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_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_delete_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_big_query_export] = mock_object - - request = {} - await client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteBigQueryExportRequest() - 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_big_query_export_async_from_dict(): - await test_delete_big_query_export_async(request_type=dict) - - -def test_delete_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value = None - client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__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_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.DeleteBigQueryExportRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__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_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_big_query_export( - securitycenter_service.DeleteBigQueryExportRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteMuteConfigRequest, - dict, -]) -def test_delete_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteMuteConfigRequest() - - -def test_delete_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteMuteConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteMuteConfigRequest( - name='name_value', - ) - -def test_delete_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - request = {} - client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteMuteConfigRequest() - -@pytest.mark.asyncio -async def test_delete_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_mute_config] = mock_object - - request = {} - await client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteMuteConfigRequest() - 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_mute_config_async_from_dict(): - await test_delete_mute_config_async(request_type=dict) - -def test_delete_mute_config_routing_parameters(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteMuteConfigRequest(**{"name": "projects/sample1/locations/sample2/muteConfigs/sample3"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value = None - client.delete_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteMuteConfigRequest(**{"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value = None - client.delete_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteMuteConfigRequest(**{"name": "folders/sample1/locations/sample2/muteConfigs/sample3"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value = None - client.delete_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_delete_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.DeleteMuteConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_mute_config( - securitycenter_service.DeleteMuteConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteNotificationConfigRequest, - dict, -]) -def test_delete_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteNotificationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest( - name='name_value', - ) - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_delete_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_notification_config] = mock_object - - request = {} - await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteNotificationConfigRequest() - 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_config_async_from_dict(): - await test_delete_notification_config_async(request_type=dict) - - -def test_delete_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = None - client.delete_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_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_notification_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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_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_notification_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_notification_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteResourceValueConfigRequest, - dict, -]) -def test_delete_resource_value_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_resource_value_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() - - -def test_delete_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteResourceValueConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_resource_value_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest( - name='name_value', - ) - -def test_delete_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - request = {} - client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_resource_value_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_resource_value_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() - -@pytest.mark.asyncio -async def test_delete_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_resource_value_config] = mock_object - - request = {} - await client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_resource_value_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteResourceValueConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteResourceValueConfigRequest() - 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_resource_value_config_async_from_dict(): - await test_delete_resource_value_config_async(request_type=dict) - - -def test_delete_resource_value_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value = None - client.delete_resource_value_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_resource_value_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_resource_value_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_resource_value_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_config( - securitycenter_service.DeleteResourceValueConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_resource_value_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_resource_value_config( - securitycenter_service.DeleteResourceValueConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetBigQueryExportRequest, - dict, -]) -def test_get_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - response = client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -def test_get_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetBigQueryExportRequest() - - -def test_get_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetBigQueryExportRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetBigQueryExportRequest( - name='name_value', - ) - -def test_get_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc - request = {} - client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.get_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_get_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_big_query_export] = mock_object - - request = {} - await client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -@pytest.mark.asyncio -async def test_get_big_query_export_async_from_dict(): - await test_get_big_query_export_async(request_type=dict) - - -def test_get_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value = bigquery_export.BigQueryExport() - client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - await client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.GetBigQueryExportRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_big_query_export( - securitycenter_service.GetBigQueryExportRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSimulationRequest, - dict, -]) -def test_get_simulation(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - response = client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSimulationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, simulation.Simulation) - assert response.name == 'name_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -def test_get_simulation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_simulation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSimulationRequest() - - -def test_get_simulation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSimulationRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_simulation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSimulationRequest( - name='name_value', - ) - -def test_get_simulation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_simulation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc - request = {} - client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_simulation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_simulation_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_simulation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSimulationRequest() - -@pytest.mark.asyncio -async def test_get_simulation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_simulation in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_simulation] = mock_object - - request = {} - await client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_simulation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_simulation_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSimulationRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSimulationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, simulation.Simulation) - assert response.name == 'name_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -@pytest.mark.asyncio -async def test_get_simulation_async_from_dict(): - await test_get_simulation_async(request_type=dict) - - -def test_get_simulation_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSimulationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value = simulation.Simulation() - client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_simulation_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSimulationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) - await client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_simulation_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = simulation.Simulation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_simulation( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_simulation_flattened_error(): - client = SecurityCenterClient( - credentials=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_simulation( - securitycenter_service.GetSimulationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_simulation_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = simulation.Simulation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_simulation( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_simulation_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_simulation( - securitycenter_service.GetSimulationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetValuedResourceRequest, - dict, -]) -def test_get_valued_resource(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - ) - response = client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetValuedResourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, valued_resource.ValuedResource) - assert response.name == 'name_value' - assert response.resource == 'resource_value' - assert response.resource_type == 'resource_type_value' - assert response.display_name == 'display_name_value' - assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW - assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) - - -def test_get_valued_resource_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_valued_resource() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetValuedResourceRequest() - - -def test_get_valued_resource_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetValuedResourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_valued_resource(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetValuedResourceRequest( - name='name_value', - ) - -def test_get_valued_resource_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_valued_resource in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc - request = {} - client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_valued_resource(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_valued_resource_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - )) - response = await client.get_valued_resource() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetValuedResourceRequest() - -@pytest.mark.asyncio -async def test_get_valued_resource_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_valued_resource in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_valued_resource] = mock_object - - request = {} - await client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_valued_resource(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_valued_resource_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetValuedResourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - )) - response = await client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetValuedResourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, valued_resource.ValuedResource) - assert response.name == 'name_value' - assert response.resource == 'resource_value' - assert response.resource_type == 'resource_type_value' - assert response.display_name == 'display_name_value' - assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW - assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) - - -@pytest.mark.asyncio -async def test_get_valued_resource_async_from_dict(): - await test_get_valued_resource_async(request_type=dict) - - -def test_get_valued_resource_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetValuedResourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value = valued_resource.ValuedResource() - client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_valued_resource_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetValuedResourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) - await client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_valued_resource_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = valued_resource.ValuedResource() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_valued_resource( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_valued_resource_flattened_error(): - client = SecurityCenterClient( - credentials=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_valued_resource( - securitycenter_service.GetValuedResourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_valued_resource_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = valued_resource.ValuedResource() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_valued_resource( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_valued_resource_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_valued_resource( - securitycenter_service.GetValuedResourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.GetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest( - resource='resource_value', - ) - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object - - request = {} - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_get_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetMuteConfigRequest, - dict, -]) -def test_get_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=mute_config.MuteConfig.MuteConfigType.STATIC, - ) - response = client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC - - -def test_get_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetMuteConfigRequest() - - -def test_get_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetMuteConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetMuteConfigRequest( - name='name_value', - ) - -def test_get_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_mute_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_mute_config] = mock_rpc - request = {} - client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.get_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetMuteConfigRequest() - -@pytest.mark.asyncio -async def test_get_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_mute_config] = mock_object - - request = {} - await client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC - - -@pytest.mark.asyncio -async def test_get_mute_config_async_from_dict(): - await test_get_mute_config_async(request_type=dict) - -def test_get_mute_config_routing_parameters(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetMuteConfigRequest(**{"name": "projects/sample1/locations/sample2/muteConfigs/sample3"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value = mute_config.MuteConfig() - client.get_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetMuteConfigRequest(**{"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value = mute_config.MuteConfig() - client.get_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetMuteConfigRequest(**{"name": "folders/sample1/locations/sample2/muteConfigs/sample3"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value = mute_config.MuteConfig() - client.get_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_get_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mute_config.MuteConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_mute_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_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.GetMuteConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mute_config.MuteConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_mute_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_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_mute_config( - securitycenter_service.GetMuteConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetNotificationConfigRequest, - dict, -]) -def test_get_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_get_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetNotificationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest( - name='name_value', - ) - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_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_notification_config] = mock_rpc - request = {} - client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_get_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_notification_config] = mock_object - - request = {} - await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_get_notification_config_async_from_dict(): - await test_get_notification_config_async(request_type=dict) - - -def test_get_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = notification_config.NotificationConfig() - client.get_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - await client.get_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_notification_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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_notification_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_notification_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetResourceValueConfigRequest, - dict, -]) -def test_get_resource_value_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - response = client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -def test_get_resource_value_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetResourceValueConfigRequest() - - -def test_get_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetResourceValueConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_resource_value_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetResourceValueConfigRequest( - name='name_value', - ) - -def test_get_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc - request = {} - client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_resource_value_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_resource_value_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetResourceValueConfigRequest() - -@pytest.mark.asyncio -async def test_get_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_resource_value_config] = mock_object - - request = {} - await client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_resource_value_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetResourceValueConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -@pytest.mark.asyncio -async def test_get_resource_value_config_async_from_dict(): - await test_get_resource_value_config_async(request_type=dict) - - -def test_get_resource_value_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value = resource_value_config.ResourceValueConfig() - client.get_resource_value_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_resource_value_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) - await client.get_resource_value_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_resource_value_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resource_value_config.ResourceValueConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_resource_value_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_resource_value_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_config( - securitycenter_service.GetResourceValueConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_resource_value_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resource_value_config.ResourceValueConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_resource_value_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_resource_value_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_resource_value_config( - securitycenter_service.GetResourceValueConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_get_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest( - name='name_value', - ) - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - -@pytest.mark.asyncio -async def test_get_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object - - request = {} - await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_get_source_async_from_dict(): - await test_get_source_async(request_type=dict) - - -def test_get_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = source.Source() - client.get_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_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_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_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_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - -@pytest.mark.asyncio -async def test_group_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_findings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object - - request = {} - await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_findings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_findings_async_from_dict(): - await test_group_findings_async(request_type=dict) - - -def test_group_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_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_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - await client.group_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_group_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that the 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - - -def test_group_findings_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - -@pytest.mark.asyncio -async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_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, securitycenter_service.GroupResult) - for i in results) -def test_group_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_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_group_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_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", [ - securitycenter_service.ListAttackPathsRequest, - dict, -]) -def test_list_attack_paths(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAttackPathsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttackPathsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_attack_paths_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_attack_paths() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAttackPathsRequest() - - -def test_list_attack_paths_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListAttackPathsRequest( - 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_attack_paths), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_attack_paths(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAttackPathsRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_value', - ) - -def test_list_attack_paths_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_attack_paths in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc - request = {} - client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_attack_paths(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_attack_paths_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_attack_paths() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAttackPathsRequest() - -@pytest.mark.asyncio -async def test_list_attack_paths_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_attack_paths in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_attack_paths] = mock_object - - request = {} - await client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_attack_paths(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_attack_paths_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAttackPathsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAttackPathsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttackPathsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_attack_paths_async_from_dict(): - await test_list_attack_paths_async(request_type=dict) - - -def test_list_attack_paths_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAttackPathsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - call.return_value = securitycenter_service.ListAttackPathsResponse() - client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_attack_paths_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAttackPathsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) - await client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_attack_paths_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAttackPathsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_attack_paths( - 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_attack_paths_flattened_error(): - client = SecurityCenterClient( - credentials=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_attack_paths( - securitycenter_service.ListAttackPathsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_attack_paths_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAttackPathsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_attack_paths( - 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_attack_paths_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_attack_paths( - securitycenter_service.ListAttackPathsRequest(), - parent='parent_value', - ) - - -def test_list_attack_paths_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_attack_paths(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, attack_path.AttackPath) - for i in results) -def test_list_attack_paths_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - RuntimeError, - ) - pages = list(client.list_attack_paths(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_attack_paths_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_attack_paths(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, attack_path.AttackPath) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_attack_paths_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - 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_attack_paths(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", [ - securitycenter_service.ListBigQueryExportsRequest, - dict, -]) -def test_list_big_query_exports(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListBigQueryExportsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryExportsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_big_query_exports_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_big_query_exports() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListBigQueryExportsRequest() - - -def test_list_big_query_exports_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListBigQueryExportsRequest( - 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_big_query_exports), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_big_query_exports(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListBigQueryExportsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_big_query_exports_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_big_query_exports in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc - request = {} - client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_big_query_exports(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_big_query_exports_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_big_query_exports() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListBigQueryExportsRequest() - -@pytest.mark.asyncio -async def test_list_big_query_exports_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_exports in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_big_query_exports] = mock_object - - request = {} - await client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_big_query_exports(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_big_query_exports_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListBigQueryExportsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListBigQueryExportsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryExportsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_big_query_exports_async_from_dict(): - await test_list_big_query_exports_async(request_type=dict) - - -def test_list_big_query_exports_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListBigQueryExportsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - call.return_value = securitycenter_service.ListBigQueryExportsResponse() - client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_exports_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListBigQueryExportsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) - await client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_exports_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListBigQueryExportsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_big_query_exports( - 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_big_query_exports_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_exports( - securitycenter_service.ListBigQueryExportsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_big_query_exports_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListBigQueryExportsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_big_query_exports( - 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_big_query_exports_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_big_query_exports( - securitycenter_service.ListBigQueryExportsRequest(), - parent='parent_value', - ) - - -def test_list_big_query_exports_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_big_query_exports(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, bigquery_export.BigQueryExport) - for i in results) -def test_list_big_query_exports_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - RuntimeError, - ) - pages = list(client.list_big_query_exports(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_big_query_exports_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_big_query_exports(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, bigquery_export.BigQueryExport) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_big_query_exports_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - 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_big_query_exports(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", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -def test_list_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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] == securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - -@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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object - - request = {} - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -@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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( - 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 = securitycenter_service.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', - ) - - # Establish that the 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_findings_flattened_error(): - client = SecurityCenterClient( - credentials=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( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_findings_flattened_async(): - client = SecurityCenterAsyncClient( - 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 = securitycenter_service.ListFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.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', - ) - - # Establish that 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_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_findings( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - - -def test_list_findings_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in results) -def test_list_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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 = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_findings_async_pages(): - client = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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", [ - securitycenter_service.ListMuteConfigsRequest, - dict, -]) -def test_list_mute_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListMuteConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMuteConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_mute_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_mute_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListMuteConfigsRequest() - - -def test_list_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListMuteConfigsRequest( - 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_mute_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_mute_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListMuteConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_mute_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_mute_configs] = mock_rpc - request = {} - client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_mute_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_mute_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_mute_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListMuteConfigsRequest() - -@pytest.mark.asyncio -async def test_list_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_mute_configs] = mock_object - - request = {} - await client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_mute_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_mute_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListMuteConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListMuteConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMuteConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_mute_configs_async_from_dict(): - await test_list_mute_configs_async(request_type=dict) - -def test_list_mute_configs_routing_parameters(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListMuteConfigsRequest(**{"parent": "projects/sample1/locations/sample2/muteConfigs"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListMuteConfigsResponse() - client.list_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListMuteConfigsRequest(**{"parent": "organizations/sample1/locations/sample2/muteConfigs"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListMuteConfigsResponse() - client.list_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListMuteConfigsRequest(**{"parent": "folders/sample1/locations/sample2/muteConfigs"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListMuteConfigsResponse() - client.list_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_list_mute_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListMuteConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_mute_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_mute_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_configs( - securitycenter_service.ListMuteConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_mute_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListMuteConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_mute_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_mute_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_mute_configs( - securitycenter_service.ListMuteConfigsRequest(), - parent='parent_value', - ) - - -def test_list_mute_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.list_mute_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, mute_config.MuteConfig) - for i in results) -def test_list_mute_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_mute_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_mute_configs_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_mute_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, mute_config.MuteConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_mute_configs_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - 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_mute_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", [ - securitycenter_service.ListNotificationConfigsRequest, - dict, -]) -def test_list_notification_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListNotificationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_notification_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListNotificationConfigsRequest( - 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_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notification_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_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_notification_configs] = mock_rpc - request = {} - client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_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_notification_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - -@pytest.mark.asyncio -async def test_list_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_notification_configs] = mock_object - - request = {} - await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_notification_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListNotificationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_from_dict(): - await test_list_notification_configs_async(request_type=dict) - - -def test_list_notification_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - 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_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - client.list_notification_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_notification_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - 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_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - await client.list_notification_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_notification_configs_flattened(): - client = SecurityCenterClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_notification_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_notification_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_notification_configs_flattened_async(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_notification_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_notification_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_notification_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - 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_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, notification_config.NotificationConfig) - for i in results) -def test_list_notification_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_notification_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_notification_configs_async_pager(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_notification_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, notification_config.NotificationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_pages(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - 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_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", [ - securitycenter_service.ListResourceValueConfigsRequest, - dict, -]) -def test_list_resource_value_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceValueConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_resource_value_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() - - -def test_list_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListResourceValueConfigsRequest( - 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_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_resource_value_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListResourceValueConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc - request = {} - client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_resource_value_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_resource_value_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() - -@pytest.mark.asyncio -async def test_list_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_resource_value_configs] = mock_object - - request = {} - await client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_resource_value_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListResourceValueConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceValueConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_resource_value_configs_async_from_dict(): - await test_list_resource_value_configs_async(request_type=dict) - - -def test_list_resource_value_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListResourceValueConfigsResponse() - client.list_resource_value_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_resource_value_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) - await client.list_resource_value_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_resource_value_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListResourceValueConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_resource_value_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_resource_value_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_configs( - securitycenter_service.ListResourceValueConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_resource_value_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListResourceValueConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_resource_value_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_resource_value_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_resource_value_configs( - securitycenter_service.ListResourceValueConfigsRequest(), - parent='parent_value', - ) - - -def test_list_resource_value_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_resource_value_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, resource_value_config.ResourceValueConfig) - for i in results) -def test_list_resource_value_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_resource_value_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_resource_value_configs_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_resource_value_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, resource_value_config.ResourceValueConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_resource_value_configs_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - 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_resource_value_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", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_sources_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListSourcesRequest( - 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_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - -@pytest.mark.asyncio -async def test_list_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_sources in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object - - request = {} - await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_sources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_sources_async_from_dict(): - await test_list_sources_async(request_type=dict) - - -def test_list_sources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = securitycenter_service.ListSourcesResponse() - client.list_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_sources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - await client.list_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_sources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_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_sources_flattened_error(): - client = SecurityCenterClient( - credentials=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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_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_sources_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_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, source.Source) - for i in results) -def test_list_sources_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = list(client.list_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_sources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_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, source.Source) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - 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_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", [ - securitycenter_service.ListValuedResourcesRequest, - dict, -]) -def test_list_valued_resources(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListValuedResourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListValuedResourcesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_valued_resources_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_valued_resources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListValuedResourcesRequest() - - -def test_list_valued_resources_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListValuedResourcesRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_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_valued_resources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_valued_resources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListValuedResourcesRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_value', - order_by='order_by_value', - ) - -def test_list_valued_resources_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_valued_resources in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc - request = {} - client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_valued_resources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_valued_resources_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_valued_resources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListValuedResourcesRequest() - -@pytest.mark.asyncio -async def test_list_valued_resources_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_valued_resources in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_valued_resources] = mock_object - - request = {} - await client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_valued_resources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_valued_resources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListValuedResourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListValuedResourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListValuedResourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_valued_resources_async_from_dict(): - await test_list_valued_resources_async(request_type=dict) - - -def test_list_valued_resources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListValuedResourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - call.return_value = securitycenter_service.ListValuedResourcesResponse() - client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_valued_resources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListValuedResourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) - await client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_valued_resources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListValuedResourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_valued_resources( - 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_valued_resources_flattened_error(): - client = SecurityCenterClient( - credentials=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_valued_resources( - securitycenter_service.ListValuedResourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_valued_resources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListValuedResourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_valued_resources( - 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_valued_resources_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_valued_resources( - securitycenter_service.ListValuedResourcesRequest(), - parent='parent_value', - ) - - -def test_list_valued_resources_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_valued_resources(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, valued_resource.ValuedResource) - for i in results) -def test_list_valued_resources_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - RuntimeError, - ) - pages = list(client.list_valued_resources(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_valued_resources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_valued_resources(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, valued_resource.ValuedResource) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_valued_resources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - 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_valued_resources(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", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_set_finding_state_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - -@pytest.mark.asyncio -async def test_set_finding_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object - - request = {} - await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_finding_state(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_set_finding_state_async_from_dict(): - await test_set_finding_state_async(request_type=dict) - - -def test_set_finding_state_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = finding.Finding() - client.set_finding_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_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_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_set_finding_state_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - - -def test_set_finding_state_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - ) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.SetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest( - resource='resource_value', - ) - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object - - request = {} - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = SecurityCenterClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetMuteRequest, - dict, -]) -def test_set_mute(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetMuteRequest() - 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.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_set_mute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_mute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetMuteRequest() - - -def test_set_mute_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SetMuteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_mute(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetMuteRequest( - name='name_value', - ) - -def test_set_mute_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_mute in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc - request = {} - client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_mute(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_set_mute_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_mute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetMuteRequest() - -@pytest.mark.asyncio -async def test_set_mute_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_mute in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_mute] = mock_object - - request = {} - await client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_mute(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_mute_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetMuteRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetMuteRequest() - 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.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_set_mute_async_from_dict(): - await test_set_mute_async(request_type=dict) - - -def test_set_mute_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetMuteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value = finding.Finding() - client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_mute_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetMuteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_set_mute_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__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.set_mute( - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].mute - mock_val = finding.Finding.Mute.MUTED - assert arg == mock_val - - -def test_set_mute_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_mute( - securitycenter_service.SetMuteRequest(), - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - -@pytest.mark.asyncio -async def test_set_mute_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__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.set_mute( - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].mute - mock_val = finding.Finding.Mute.MUTED - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_mute_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_mute( - securitycenter_service.SetMuteRequest(), - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.TestIamPermissionsRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( - resource='resource_value', - ) - -def test_test_iam_permissions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object - - request = {} - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateBigQueryExportRequest, - dict, -]) -def test_update_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - response = client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -def test_update_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() - - -def test_update_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateBigQueryExportRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateBigQueryExportRequest( - ) - -def test_update_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc - request = {} - client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_big_query_export(request) - - # Establish that a new wrapper 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_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.update_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_update_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_big_query_export] = mock_object - - request = {} - await client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -@pytest.mark.asyncio -async def test_update_big_query_export_async_from_dict(): - await test_update_big_query_export_async(request_type=dict) - - -def test_update_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateBigQueryExportRequest() - - request.big_query_export.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value = bigquery_export.BigQueryExport() - client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'big_query_export.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateBigQueryExportRequest() - - request.big_query_export.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - await client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'big_query_export.name=name_value', - ) in kw['metadata'] - - -def test_update_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_big_query_export( - big_query_export=bigquery_export.BigQueryExport(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].big_query_export - mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.UpdateBigQueryExportRequest(), - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_big_query_export( - big_query_export=bigquery_export.BigQueryExport(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].big_query_export - mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_big_query_export( - securitycenter_service.UpdateBigQueryExportRequest(), - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateExternalSystemRequest, - dict, -]) -def test_update_external_system(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - ) - response = client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateExternalSystemRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_external_system.ExternalSystem) - assert response.name == 'name_value' - assert response.assignees == ['assignees_value'] - assert response.external_uid == 'external_uid_value' - assert response.status == 'status_value' - assert response.case_uri == 'case_uri_value' - assert response.case_priority == 'case_priority_value' - - -def test_update_external_system_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_external_system() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateExternalSystemRequest() - - -def test_update_external_system_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateExternalSystemRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_external_system(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateExternalSystemRequest( - ) - -def test_update_external_system_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_external_system in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc - request = {} - client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_external_system(request) - - # Establish that a new wrapper 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_external_system_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - )) - response = await client.update_external_system() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateExternalSystemRequest() - -@pytest.mark.asyncio -async def test_update_external_system_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_external_system in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_external_system] = mock_object - - request = {} - await client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_external_system(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_external_system_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateExternalSystemRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - )) - response = await client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateExternalSystemRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_external_system.ExternalSystem) - assert response.name == 'name_value' - assert response.assignees == ['assignees_value'] - assert response.external_uid == 'external_uid_value' - assert response.status == 'status_value' - assert response.case_uri == 'case_uri_value' - assert response.case_priority == 'case_priority_value' - - -@pytest.mark.asyncio -async def test_update_external_system_async_from_dict(): - await test_update_external_system_async(request_type=dict) - - -def test_update_external_system_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateExternalSystemRequest() - - request.external_system.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value = gcs_external_system.ExternalSystem() - client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'external_system.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_external_system_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateExternalSystemRequest() - - request.external_system.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) - await client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'external_system.name=name_value', - ) in kw['metadata'] - - -def test_update_external_system_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_external_system.ExternalSystem() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_external_system( - external_system=gcs_external_system.ExternalSystem(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].external_system - mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error(): - client = SecurityCenterClient( - credentials=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_external_system( - securitycenter_service.UpdateExternalSystemRequest(), - external_system=gcs_external_system.ExternalSystem(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_external_system_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_external_system.ExternalSystem() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_external_system( - external_system=gcs_external_system.ExternalSystem(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].external_system - mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_external_system( - securitycenter_service.UpdateExternalSystemRequest(), - external_system=gcs_external_system.ExternalSystem(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_update_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateFindingRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.update_finding] = mock_rpc - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object - - request = {} - await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_update_finding_async_from_dict(): - await test_update_finding_async(request_type=dict) - - -def test_update_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -def test_update_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_finding( - finding=gcs_finding.Finding(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].finding - mock_val = gcs_finding.Finding(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_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_finding( - finding=gcs_finding.Finding(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].finding - mock_val = gcs_finding.Finding(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_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateMuteConfigRequest, - dict, -]) -def test_update_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - ) - response = client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - - -def test_update_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateMuteConfigRequest() - - -def test_update_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateMuteConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateMuteConfigRequest( - ) - -def test_update_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - request = {} - client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.update_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateMuteConfigRequest() - -@pytest.mark.asyncio -async def test_update_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_mute_config] = mock_object - - request = {} - await client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - - -@pytest.mark.asyncio -async def test_update_mute_config_async_from_dict(): - await test_update_mute_config_async(request_type=dict) - -def test_update_mute_config_routing_parameters(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateMuteConfigRequest(**{"mute_config": {"name": "projects/sample1/locations/sample2/muteConfigs/sample3"}}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.update_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateMuteConfigRequest(**{"mute_config": {"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"}}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.update_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateMuteConfigRequest(**{"mute_config": {"name": "folders/sample1/locations/sample2/muteConfigs/sample3"}}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.update_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_update_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_mute_config( - mute_config=gcs_mute_config.MuteConfig(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].mute_config - mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.UpdateMuteConfigRequest(), - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_mute_config( - mute_config=gcs_mute_config.MuteConfig(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].mute_config - mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_mute_config( - securitycenter_service.UpdateMuteConfigRequest(), - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateNotificationConfigRequest, - dict, -]) -def test_update_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_update_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateNotificationConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest( - ) - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_update_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_notification_config] = mock_object - - request = {} - await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_update_notification_config_async_from_dict(): - await test_update_notification_config_async(request_type=dict) - - -def test_update_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.update_notification_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', - 'notification_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.update_notification_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', - 'notification_config.name=name_value', - ) in kw['metadata'] - - -def test_update_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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].notification_config - mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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].notification_config - mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_notification_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateResourceValueConfigRequest, - dict, -]) -def test_update_resource_value_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - response = client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -def test_update_resource_value_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() - - -def test_update_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateResourceValueConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_resource_value_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest( - ) - -def test_update_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - request = {} - client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_resource_value_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_resource_value_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.update_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() - -@pytest.mark.asyncio -async def test_update_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_resource_value_config] = mock_object - - request = {} - await client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_resource_value_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateResourceValueConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -@pytest.mark.asyncio -async def test_update_resource_value_config_async_from_dict(): - await test_update_resource_value_config_async(request_type=dict) - - -def test_update_resource_value_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateResourceValueConfigRequest() - - request.resource_value_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value = gcs_resource_value_config.ResourceValueConfig() - client.update_resource_value_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', - 'resource_value_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_resource_value_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateResourceValueConfigRequest() - - request.resource_value_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) - await client.update_resource_value_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', - 'resource_value_config.name=name_value', - ) in kw['metadata'] - - -def test_update_resource_value_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_resource_value_config.ResourceValueConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_resource_value_config( - resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config - mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_config( - securitycenter_service.UpdateResourceValueConfigRequest(), - resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_resource_value_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_resource_value_config.ResourceValueConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_resource_value_config( - resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config - mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_resource_value_config( - securitycenter_service.UpdateResourceValueConfigRequest(), - resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - response = client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_security_marks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - -def test_update_security_marks_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSecurityMarksRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( - ) - -def test_update_security_marks_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish that a new wrapper 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_security_marks_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - -@pytest.mark.asyncio -async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_marks in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object - - request = {} - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_security_marks(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_security_marks_async_from_dict(): - await test_update_security_marks_async(request_type=dict) - - -def test_update_security_marks_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -def test_update_security_marks_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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].security_marks - mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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].security_marks - mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSourceRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object - - request = {} - await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_source_async_from_dict(): - await test_update_source_async(request_type=dict) - - -def test_update_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -def test_update_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_source( - source=gcs_source.Source(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].source - mock_val = gcs_source.Source(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_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_source( - source=gcs_source.Source(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].source - mock_val = gcs_source.Source(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_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.BatchCreateResourceValueConfigsRequest, - dict, -]) -def test_batch_create_resource_value_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.BatchCreateResourceValueConfigsResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) - -def test_batch_create_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc - - request = {} - client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_resource_value_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_batch_create_resource_value_configs_rest_required_fields(request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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()).batch_create_resource_value_configs._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_create_resource_value_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_create_resource_value_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_resource_value_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_batch_create_resource_value_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_batch_create_resource_value_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(securitycenter_service.BatchCreateResourceValueConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.BatchCreateResourceValueConfigsResponse.to_json(securitycenter_service.BatchCreateResourceValueConfigsResponse()) - - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - - client.batch_create_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_create_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_create_resource_value_configs(request) - - -def test_batch_create_resource_value_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(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.batch_create_resource_value_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/v2/{parent=organizations/*}/resourceValueConfigs:batchCreate" % client.transport._host, args[1]) - - -def test_batch_create_resource_value_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_create_resource_value_configs( - securitycenter_service.BatchCreateResourceValueConfigsRequest(), - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], - ) - - -def test_batch_create_resource_value_configs_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.BulkMuteFindingsRequest, - dict, -]) -def test_bulk_mute_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') - - # 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 - response = client.bulk_mute_findings(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_bulk_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc - - request = {} - client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_rest_required_fields(request_type=securitycenter_service.BulkMuteFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).bulk_mute_findings._get_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()).bulk_mute_findings._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 = SecurityCenterClient( - 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.bulk_mute_findings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_bulk_mute_findings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.bulk_mute_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_bulk_mute_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_bulk_mute_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_bulk_mute_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.BulkMuteFindingsRequest.pb(securitycenter_service.BulkMuteFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = securitycenter_service.BulkMuteFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.bulk_mute_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_bulk_mute_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BulkMuteFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.bulk_mute_findings(request) - - -def test_bulk_mute_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.bulk_mute_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/v2/{parent=organizations/*}/findings:bulkMute" % client.transport._host, args[1]) - - -def test_bulk_mute_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.bulk_mute_findings( - securitycenter_service.BulkMuteFindingsRequest(), - parent='parent_value', - ) - - -def test_bulk_mute_findings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateBigQueryExportRequest, - dict, -]) -def test_create_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/locations/sample2'} - request_init["big_query_export"] = {'name': 'name_value', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.CreateBigQueryExportRequest.meta.fields["big_query_export"] - - 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["big_query_export"].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["big_query_export"][field])): - del request_init["big_query_export"][field][i][subfield] - else: - del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - -def test_create_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - - request = {} - client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.CreateBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["big_query_export_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 "bigQueryExportId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "bigQueryExportId" in jsonified_request - assert jsonified_request["bigQueryExportId"] == request_init["big_query_export_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["bigQueryExportId"] = 'big_query_export_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("big_query_export_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 "bigQueryExportId" in jsonified_request - assert jsonified_request["bigQueryExportId"] == 'big_query_export_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - expected_params = [ - ( - "bigQueryExportId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(("bigQueryExportId", )) & set(("parent", "bigQueryExport", "bigQueryExportId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_big_query_export") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_big_query_export") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateBigQueryExportRequest.pb(securitycenter_service.CreateBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) - - request = securitycenter_service.CreateBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = bigquery_export.BigQueryExport() - - client.create_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_big_query_export(request) - - -def test_create_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=organizations/*/locations/*}/bigQueryExports" % client.transport._host, args[1]) - - -def test_create_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.CreateBigQueryExportRequest(), - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_id_value', - ) - - -def test_create_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2/locations/sample3'} - request_init["finding"] = {'name': 'name_value', 'canonical_name': 'canonical_name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'mute': 1, 'mute_info': {'static_mute': {'state': 1, 'apply_time': {}}, 'dynamic_mute_records': [{'mute_config': 'mute_config_value', 'match_time': {}}]}, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True, 'exploit_release_date': {}}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.create_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.create_finding] = mock_rpc - - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["finding_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 "findingId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "findingId" in jsonified_request - assert jsonified_request["findingId"] == request_init["finding_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["findingId"] = 'finding_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request - assert jsonified_request["findingId"] == 'finding_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.create_finding(request) - - expected_params = [ - ( - "findingId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.CreateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2/locations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_finding(request) - - -def test_create_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2/locations/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - finding=gcs_finding.Finding(name='name_value'), - finding_id='finding_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 = gcs_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.create_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/v2/{parent=organizations/*/sources/*/locations/*}/findings" % client.transport._host, args[1]) - - -def test_create_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding=gcs_finding.Finding(name='name_value'), - finding_id='finding_id_value', - ) - - -def test_create_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateMuteConfigRequest, - dict, -]) -def test_create_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/locations/sample2'} - request_init["mute_config"] = {'name': 'name_value', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'type_': 1, 'expiry_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 = securitycenter_service.CreateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): - del request_init["mute_config"][field][i][subfield] - else: - del request_init["mute_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 = gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - -def test_create_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - - request = {} - client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.CreateMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["mute_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 "muteConfigId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "muteConfigId" in jsonified_request - assert jsonified_request["muteConfigId"] == request_init["mute_config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["muteConfigId"] = 'mute_config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("mute_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 "muteConfigId" in jsonified_request - assert jsonified_request["muteConfigId"] == 'mute_config_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - expected_params = [ - ( - "muteConfigId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("muteConfigId", )) & set(("parent", "muteConfig", "muteConfigId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_mute_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_mute_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateMuteConfigRequest.pb(securitycenter_service.CreateMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) - - request = securitycenter_service.CreateMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_mute_config.MuteConfig() - - client.create_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_mute_config(request) - - -def test_create_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_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 = gcs_mute_config.MuteConfig.pb(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_mute_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/v2/{parent=organizations/*/locations/*}/muteConfigs" % client.transport._host, args[1]) - - -def test_create_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.CreateMuteConfigRequest(), - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_id_value', - ) - - -def test_create_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateNotificationConfigRequest, - dict, -]) -def test_create_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/locations/sample2'} - request_init["notification_config"] = {'name': 'name_value', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.CreateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): - del request_init["notification_config"][field][i][subfield] - else: - del request_init["notification_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 = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.CreateNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["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 "configId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "configId" in jsonified_request - assert jsonified_request["configId"] == request_init["config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["configId"] = 'config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("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 "configId" in jsonified_request - assert jsonified_request["configId"] == 'config_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ( - "configId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("configId", )) & set(("parent", "configId", "notificationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateNotificationConfigRequest.pb(securitycenter_service.CreateNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) - - request = securitycenter_service.CreateNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_notification_config.NotificationConfig() - - client.create_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_notification_config(request) - - -def test_create_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - config_id='config_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 = gcs_notification_config.NotificationConfig.pb(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_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/v2/{parent=organizations/*/locations/*}/notificationConfigs" % client.transport._host, args[1]) - - -def test_create_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - config_id='config_id_value', - ) - - -def test_create_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.CreateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_source(request) - - -def test_create_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v2/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_create_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -def test_create_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteBigQueryExportRequest, - dict, -]) -def test_delete_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - - request = {} - client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.DeleteBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - 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_big_query_export(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_big_query_export") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteBigQueryExportRequest.pb(securitycenter_service.DeleteBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_big_query_export(request) - - -def test_delete_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/locations/sample2/bigQueryExports/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_big_query_export(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=organizations/*/locations/*/bigQueryExports/*}" % client.transport._host, args[1]) - - -def test_delete_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.DeleteBigQueryExportRequest(), - name='name_value', - ) - - -def test_delete_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteMuteConfigRequest, - dict, -]) -def test_delete_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/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 = 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - - request = {} - client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.DeleteMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( - 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_mute_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_mute_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteMuteConfigRequest.pb(securitycenter_service.DeleteMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_mute_config(request) - - -def test_delete_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/muteConfigs/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_mute_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/v2/{name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.DeleteMuteConfigRequest(), - name='name_value', - ) - - -def test_delete_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteNotificationConfigRequest, - dict, -]) -def test_delete_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = 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_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.DeleteNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_notification_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteNotificationConfigRequest.pb(securitycenter_service.DeleteNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_notification_config(request) - - -def test_delete_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/locations/sample2/notificationConfigs/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_notification_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/v2/{name=organizations/*/locations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -def test_delete_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteResourceValueConfigRequest, - dict, -]) -def test_delete_resource_value_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = 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_resource_value_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - - request = {} - client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.DeleteResourceValueConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( - 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_resource_value_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_resource_value_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_resource_value_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_resource_value_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_resource_value_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteResourceValueConfigRequest.pb(securitycenter_service.DeleteResourceValueConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteResourceValueConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteResourceValueConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_resource_value_config(request) - - -def test_delete_resource_value_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/resourceValueConfigs/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_resource_value_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/v2/{name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_resource_value_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_config( - securitycenter_service.DeleteResourceValueConfigRequest(), - name='name_value', - ) - - -def test_delete_resource_value_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetBigQueryExportRequest, - dict, -]) -def test_get_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - -def test_get_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc - - request = {} - client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.GetBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_big_query_export") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_big_query_export") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetBigQueryExportRequest.pb(securitycenter_service.GetBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) - - request = securitycenter_service.GetBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = bigquery_export.BigQueryExport() - - client.get_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_big_query_export(request) - - -def test_get_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=organizations/*/locations/*/bigQueryExports/*}" % client.transport._host, args[1]) - - -def test_get_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.GetBigQueryExportRequest(), - name='name_value', - ) - - -def test_get_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSimulationRequest, - dict, -]) -def test_get_simulation_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = simulation.Simulation.pb(return_value) - 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_simulation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, simulation.Simulation) - assert response.name == 'name_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - -def test_get_simulation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_simulation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc - - request = {} - client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_simulation(request) - - # Establish 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_simulation_rest_required_fields(request_type=securitycenter_service.GetSimulationRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_simulation._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_simulation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = simulation.Simulation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = simulation.Simulation.pb(return_value) - 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_simulation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_simulation_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_simulation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_simulation_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_simulation") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_simulation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSimulationRequest.pb(securitycenter_service.GetSimulationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = simulation.Simulation.to_json(simulation.Simulation()) - - request = securitycenter_service.GetSimulationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = simulation.Simulation() - - client.get_simulation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_simulation_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSimulationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_simulation(request) - - -def test_get_simulation_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = simulation.Simulation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation.pb(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_simulation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=organizations/*/simulations/*}" % client.transport._host, args[1]) - - -def test_get_simulation_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_simulation( - securitycenter_service.GetSimulationRequest(), - name='name_value', - ) - - -def test_get_simulation_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetValuedResourceRequest, - dict, -]) -def test_get_valued_resource_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = valued_resource.ValuedResource.pb(return_value) - 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_valued_resource(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, valued_resource.ValuedResource) - assert response.name == 'name_value' - assert response.resource == 'resource_value' - assert response.resource_type == 'resource_type_value' - assert response.display_name == 'display_name_value' - assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW - assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) - -def test_get_valued_resource_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_valued_resource in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc - - request = {} - client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_valued_resource(request) - - # Establish 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_valued_resource_rest_required_fields(request_type=securitycenter_service.GetValuedResourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_valued_resource._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_valued_resource._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = valued_resource.ValuedResource() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = valued_resource.ValuedResource.pb(return_value) - 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_valued_resource(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_valued_resource_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_valued_resource._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_valued_resource_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_valued_resource") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_valued_resource") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetValuedResourceRequest.pb(securitycenter_service.GetValuedResourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = valued_resource.ValuedResource.to_json(valued_resource.ValuedResource()) - - request = securitycenter_service.GetValuedResourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = valued_resource.ValuedResource() - - client.get_valued_resource(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_valued_resource_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetValuedResourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_valued_resource(request) - - -def test_get_valued_resource_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = valued_resource.ValuedResource() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource.pb(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_valued_resource(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=organizations/*/simulations/*/valuedResources/*}" % client.transport._host, args[1]) - - -def test_get_valued_resource_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_valued_resource( - securitycenter_service.GetValuedResourceRequest(), - name='name_value', - ) - - -def test_get_valued_resource_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.get_iam_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/v2/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetMuteConfigRequest, - dict, -]) -def test_get_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=mute_config.MuteConfig.MuteConfigType.STATIC, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC - -def test_get_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_mute_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_mute_config] = mock_rpc - - request = {} - client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.GetMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = mute_config.MuteConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_mute_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_mute_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetMuteConfigRequest.pb(securitycenter_service.GetMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = mute_config.MuteConfig.to_json(mute_config.MuteConfig()) - - request = securitycenter_service.GetMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = mute_config.MuteConfig() - - client.get_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_mute_config(request) - - -def test_get_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = mute_config.MuteConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig.pb(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_mute_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/v2/{name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) - - -def test_get_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.GetMuteConfigRequest(), - name='name_value', - ) - - -def test_get_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetNotificationConfigRequest, - dict, -]) -def test_get_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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_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_notification_config] = mock_rpc - - request = {} - client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.GetNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetNotificationConfigRequest.pb(securitycenter_service.GetNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = notification_config.NotificationConfig.to_json(notification_config.NotificationConfig()) - - request = securitycenter_service.GetNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = notification_config.NotificationConfig() - - client.get_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_notification_config(request) - - -def test_get_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = notification_config.NotificationConfig.pb(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_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/v2/{name=organizations/*/locations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_get_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -def test_get_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetResourceValueConfigRequest, - dict, -]) -def test_get_resource_value_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - -def test_get_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc - - request = {} - client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.GetResourceValueConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resource_value_config.ResourceValueConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_resource_value_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_resource_value_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_resource_value_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_resource_value_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_resource_value_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetResourceValueConfigRequest.pb(securitycenter_service.GetResourceValueConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resource_value_config.ResourceValueConfig.to_json(resource_value_config.ResourceValueConfig()) - - request = securitycenter_service.GetResourceValueConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resource_value_config.ResourceValueConfig() - - client.get_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetResourceValueConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_resource_value_config(request) - - -def test_get_resource_value_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resource_value_config.ResourceValueConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig.pb(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_resource_value_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/v2/{name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) - - -def test_get_resource_value_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_config( - securitycenter_service.GetResourceValueConfigRequest(), - name='name_value', - ) - - -def test_get_resource_value_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/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 = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = source.Source.to_json(source.Source()) - - request = securitycenter_service.GetSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = source.Source() - - client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_source(request) - - -def test_get_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v2/{name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_get_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -def test_get_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_findings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_findings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_findings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) - - request = securitycenter_service.GroupFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupFindingsResponse() - - client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_findings(request) - - -def test_group_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - group_by='group_by_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v2/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) - - -def test_group_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} - - pager = client.group_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_findings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListAttackPathsRequest, - dict, -]) -def test_list_attack_paths_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) - 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_attack_paths(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttackPathsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_attack_paths_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_attack_paths in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc - - request = {} - client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_attack_paths(request) - - # Establish 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_attack_paths_rest_required_fields(request_type=securitycenter_service.ListAttackPathsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_attack_paths._get_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_attack_paths._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAttackPathsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) - 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_attack_paths(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_attack_paths_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_attack_paths._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_attack_paths_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_attack_paths") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_attack_paths") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListAttackPathsRequest.pb(securitycenter_service.ListAttackPathsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListAttackPathsResponse.to_json(securitycenter_service.ListAttackPathsResponse()) - - request = securitycenter_service.ListAttackPathsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListAttackPathsResponse() - - client.list_attack_paths(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_attack_paths_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAttackPathsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_attack_paths(request) - - -def test_list_attack_paths_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAttackPathsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse.pb(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_attack_paths(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=organizations/*/simulations/*}/attackPaths" % client.transport._host, args[1]) - - -def test_list_attack_paths_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_attack_paths( - securitycenter_service.ListAttackPathsRequest(), - parent='parent_value', - ) - - -def test_list_attack_paths_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListAttackPathsResponse.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': 'organizations/sample1/simulations/sample2'} - - pager = client.list_attack_paths(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, attack_path.AttackPath) - for i in results) - - pages = list(client.list_attack_paths(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListBigQueryExportsRequest, - dict, -]) -def test_list_big_query_exports_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) - 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_big_query_exports(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryExportsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_big_query_exports_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_big_query_exports in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc - - request = {} - client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_big_query_exports(request) - - # Establish 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_big_query_exports_rest_required_fields(request_type=securitycenter_service.ListBigQueryExportsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_big_query_exports._get_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_big_query_exports._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListBigQueryExportsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) - 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_big_query_exports(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_big_query_exports_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_big_query_exports._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_big_query_exports_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_big_query_exports") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_big_query_exports") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListBigQueryExportsRequest.pb(securitycenter_service.ListBigQueryExportsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListBigQueryExportsResponse.to_json(securitycenter_service.ListBigQueryExportsResponse()) - - request = securitycenter_service.ListBigQueryExportsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListBigQueryExportsResponse() - - client.list_big_query_exports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_big_query_exports_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListBigQueryExportsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_big_query_exports(request) - - -def test_list_big_query_exports_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListBigQueryExportsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse.pb(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_big_query_exports(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=organizations/*/locations/*}/bigQueryExports" % client.transport._host, args[1]) - - -def test_list_big_query_exports_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_exports( - securitycenter_service.ListBigQueryExportsRequest(), - parent='parent_value', - ) - - -def test_list_big_query_exports_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListBigQueryExportsResponse.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': 'organizations/sample1/locations/sample2'} - - pager = client.list_big_query_exports(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, bigquery_export.BigQueryExport) - for i in results) - - pages = list(client.list_big_query_exports(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.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' - assert response.total_size == 1086 - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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=securitycenter_service.ListFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("field_mask", "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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.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 = securitycenter_service.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 = [ - ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("fieldMask", "filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) - - request = securitycenter_service.ListFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListFindingsResponse() - - client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_findings(request) - - -def test_list_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.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/v2/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) - - -def test_list_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - - -def test_list_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} - - pager = client.list_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) - 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 - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListMuteConfigsRequest, - dict, -]) -def test_list_mute_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) - 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_mute_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMuteConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_mute_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_mute_configs] = mock_rpc - - request = {} - client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_mute_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_mute_configs_rest_required_fields(request_type=securitycenter_service.ListMuteConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListMuteConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) - 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_mute_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_mute_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_mute_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_mute_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_mute_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_mute_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListMuteConfigsRequest.pb(securitycenter_service.ListMuteConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListMuteConfigsResponse.to_json(securitycenter_service.ListMuteConfigsResponse()) - - request = securitycenter_service.ListMuteConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListMuteConfigsResponse() - - client.list_mute_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_mute_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListMuteConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_mute_configs(request) - - -def test_list_mute_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListMuteConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse.pb(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_mute_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/v2/{parent=organizations/*}/muteConfigs" % client.transport._host, args[1]) - - -def test_list_mute_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_configs( - securitycenter_service.ListMuteConfigsRequest(), - parent='parent_value', - ) - - -def test_list_mute_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListMuteConfigsResponse.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': 'organizations/sample1'} - - pager = client.list_mute_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, mute_config.MuteConfig) - for i in results) - - pages = list(client.list_mute_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListNotificationConfigsRequest, - dict, -]) -def test_list_notification_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) - 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_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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_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_notification_configs] = mock_rpc - - request = {} - client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_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_notification_configs_rest_required_fields(request_type=securitycenter_service.ListNotificationConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListNotificationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) - 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_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_notification_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_notification_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_notification_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_notification_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_notification_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListNotificationConfigsRequest.pb(securitycenter_service.ListNotificationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListNotificationConfigsResponse.to_json(securitycenter_service.ListNotificationConfigsResponse()) - - request = securitycenter_service.ListNotificationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListNotificationConfigsResponse() - - client.list_notification_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_notification_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_notification_configs(request) - - -def test_list_notification_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListNotificationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse.pb(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_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/v2/{parent=organizations/*/locations/*}/notificationConfigs" % client.transport._host, args[1]) - - -def test_list_notification_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListNotificationConfigsResponse.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': 'organizations/sample1/locations/sample2'} - - pager = client.list_notification_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, notification_config.NotificationConfig) - for i in results) - - pages = list(client.list_notification_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListResourceValueConfigsRequest, - dict, -]) -def test_list_resource_value_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceValueConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc - - request = {} - client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_resource_value_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_resource_value_configs_rest_required_fields(request_type=securitycenter_service.ListResourceValueConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListResourceValueConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_resource_value_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_resource_value_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_resource_value_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_resource_value_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_resource_value_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListResourceValueConfigsRequest.pb(securitycenter_service.ListResourceValueConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListResourceValueConfigsResponse.to_json(securitycenter_service.ListResourceValueConfigsResponse()) - - request = securitycenter_service.ListResourceValueConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListResourceValueConfigsResponse() - - client.list_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListResourceValueConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_resource_value_configs(request) - - -def test_list_resource_value_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListResourceValueConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse.pb(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_resource_value_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/v2/{parent=organizations/*}/resourceValueConfigs" % client.transport._host, args[1]) - - -def test_list_resource_value_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_configs( - securitycenter_service.ListResourceValueConfigsRequest(), - parent='parent_value', - ) - - -def test_list_resource_value_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListResourceValueConfigsResponse.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': 'organizations/sample1'} - - pager = client.list_resource_value_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resource_value_config.ResourceValueConfig) - for i in results) - - pages = list(client.list_resource_value_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_sources_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_sources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_sources_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) - - request = securitycenter_service.ListSourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListSourcesResponse() - - client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_sources(request) - - -def test_list_sources_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v2/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_list_sources_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} - - pager = client.list_sources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, source.Source) - for i in results) - - pages = list(client.list_sources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListValuedResourcesRequest, - dict, -]) -def test_list_valued_resources_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) - 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_valued_resources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListValuedResourcesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_list_valued_resources_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_valued_resources in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc - - request = {} - client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_valued_resources(request) - - # Establish 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_valued_resources_rest_required_fields(request_type=securitycenter_service.ListValuedResourcesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_valued_resources._get_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_valued_resources._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListValuedResourcesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) - 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_valued_resources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_valued_resources_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_valued_resources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_valued_resources_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_valued_resources") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_valued_resources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListValuedResourcesRequest.pb(securitycenter_service.ListValuedResourcesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListValuedResourcesResponse.to_json(securitycenter_service.ListValuedResourcesResponse()) - - request = securitycenter_service.ListValuedResourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListValuedResourcesResponse() - - client.list_valued_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_valued_resources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListValuedResourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_valued_resources(request) - - -def test_list_valued_resources_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListValuedResourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse.pb(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_valued_resources(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=organizations/*/simulations/*}/valuedResources" % client.transport._host, args[1]) - - -def test_list_valued_resources_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_valued_resources( - securitycenter_service.ListValuedResourcesRequest(), - parent='parent_value', - ) - - -def test_list_valued_resources_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListValuedResourcesResponse.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': 'organizations/sample1/simulations/sample2'} - - pager = client.list_valued_resources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, valued_resource.ValuedResource) - for i in results) - - pages = list(client.list_valued_resources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # 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 - response = client.set_finding_state(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( - 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': "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 = 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.set_finding_state(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_finding_state_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_finding_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "state", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_finding_state_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = finding.Finding.to_json(finding.Finding()) - - request = securitycenter_service.SetFindingStateRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_finding_state(request) - - -def test_set_finding_state_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - state=finding.Finding.State.ACTIVE, - ) - mock_args.update(sample_request) - - # 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.set_finding_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/v2/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) - - -def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - ) - - -def test_set_finding_state_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.set_iam_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/v2/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetMuteRequest, - dict, -]) -def test_set_mute_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # 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 - response = client.set_mute(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_set_mute_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_mute in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc - - request = {} - client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_mute(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_set_mute_rest_required_fields(request_type=securitycenter_service.SetMuteRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - 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': "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 = 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.set_mute(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_mute_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_mute._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "mute", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_mute_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_mute") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_mute") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SetMuteRequest.pb(securitycenter_service.SetMuteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = finding.Finding.to_json(finding.Finding()) - - request = securitycenter_service.SetMuteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.set_mute(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_mute_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetMuteRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_mute(request) - - -def test_set_mute_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - mock_args.update(sample_request) - - # 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.set_mute(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=organizations/*/sources/*/findings/*}:setMute" % client.transport._host, args[1]) - - -def test_set_mute_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_mute( - securitycenter_service.SetMuteRequest(), - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - -def test_set_mute_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # 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 - response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_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.test_iam_permissions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateBigQueryExportRequest, - dict, -]) -def test_update_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'big_query_export': {'name': 'organizations/sample1/locations/sample2/bigQueryExports/sample3'}} - request_init["big_query_export"] = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/sample3', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.UpdateBigQueryExportRequest.meta.fields["big_query_export"] - - 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["big_query_export"].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["big_query_export"][field])): - del request_init["big_query_export"][field][i][subfield] - else: - del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - -def test_update_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc - - request = {} - client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.UpdateBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_big_query_export._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_big_query_export._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("bigQueryExport", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_big_query_export") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_big_query_export") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateBigQueryExportRequest.pb(securitycenter_service.UpdateBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) - - request = securitycenter_service.UpdateBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = bigquery_export.BigQueryExport() - - client.update_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'big_query_export': {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_big_query_export(request) - - -def test_update_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - - # get arguments that satisfy an http rule for this method - sample_request = {'big_query_export': {'name': 'organizations/sample1/locations/sample2/bigQueryExports/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - big_query_export=bigquery_export.BigQueryExport(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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{big_query_export.name=organizations/*/locations/*/bigQueryExports/*}" % client.transport._host, args[1]) - - -def test_update_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.UpdateBigQueryExportRequest(), - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateExternalSystemRequest, - dict, -]) -def test_update_external_system_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} - request_init["external_system"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4', 'assignees': ['assignees_value1', 'assignees_value2'], 'external_uid': 'external_uid_value', 'status': 'status_value', 'external_system_update_time': {'seconds': 751, 'nanos': 543}, 'case_uri': 'case_uri_value', 'case_priority': 'case_priority_value', 'case_sla': {}, 'case_create_time': {}, 'case_close_time': {}, 'ticket_info': {'id': 'id_value', 'assignee': 'assignee_value', 'description': 'description_value', 'uri': 'uri_value', 'status': 'status_value', 'update_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 = securitycenter_service.UpdateExternalSystemRequest.meta.fields["external_system"] - - 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["external_system"].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["external_system"][field])): - del request_init["external_system"][field][i][subfield] - else: - del request_init["external_system"][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 = gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_external_system.ExternalSystem.pb(return_value) - 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_external_system(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_external_system.ExternalSystem) - assert response.name == 'name_value' - assert response.assignees == ['assignees_value'] - assert response.external_uid == 'external_uid_value' - assert response.status == 'status_value' - assert response.case_uri == 'case_uri_value' - assert response.case_priority == 'case_priority_value' - -def test_update_external_system_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_external_system in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc - - request = {} - client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_external_system(request) - - # Establish 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_external_system_rest_required_fields(request_type=securitycenter_service.UpdateExternalSystemRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_external_system._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_external_system._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_external_system.ExternalSystem() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_external_system.ExternalSystem.pb(return_value) - 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_external_system(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_external_system_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_external_system._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("externalSystem", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_external_system_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_external_system") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_external_system") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateExternalSystemRequest.pb(securitycenter_service.UpdateExternalSystemRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_external_system.ExternalSystem.to_json(gcs_external_system.ExternalSystem()) - - request = securitycenter_service.UpdateExternalSystemRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_external_system.ExternalSystem() - - client.update_external_system(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_external_system_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateExternalSystemRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_external_system(request) - - -def test_update_external_system_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_external_system.ExternalSystem() - - # get arguments that satisfy an http rule for this method - sample_request = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - external_system=gcs_external_system.ExternalSystem(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 = gcs_external_system.ExternalSystem.pb(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_external_system(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}" % client.transport._host, args[1]) - - -def test_update_external_system_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_external_system( - securitycenter_service.UpdateExternalSystemRequest(), - external_system=gcs_external_system.ExternalSystem(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_external_system_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'canonical_name': 'canonical_name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'mute': 1, 'mute_info': {'static_mute': {'state': 1, 'apply_time': {}}, 'dynamic_mute_records': [{'mute_config': 'mute_config_value', 'match_time': {}}]}, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True, 'exploit_release_date': {}}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.update_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.update_finding] = mock_rpc - - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_finding._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_finding._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.update_finding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.UpdateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_finding(request) - - -def test_update_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - finding=gcs_finding.Finding(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 = gcs_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.update_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/v2/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) - - -def test_update_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateMuteConfigRequest, - dict, -]) -def test_update_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} - request_init["mute_config"] = {'name': 'organizations/sample1/muteConfigs/sample2', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'type_': 1, 'expiry_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 = securitycenter_service.UpdateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): - del request_init["mute_config"][field][i][subfield] - else: - del request_init["mute_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 = gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - -def test_update_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - - request = {} - client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.UpdateMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_mute_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_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("muteConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_mute_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_mute_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateMuteConfigRequest.pb(securitycenter_service.UpdateMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) - - request = securitycenter_service.UpdateMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_mute_config.MuteConfig() - - client.update_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_mute_config(request) - - -def test_update_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - mute_config=gcs_mute_config.MuteConfig(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 = gcs_mute_config.MuteConfig.pb(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_mute_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/v2/{mute_config.name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) - - -def test_update_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.UpdateMuteConfigRequest(), - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateNotificationConfigRequest, - dict, -]) -def test_update_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'notification_config': {'name': 'organizations/sample1/locations/sample2/notificationConfigs/sample3'}} - request_init["notification_config"] = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/sample3', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.UpdateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): - del request_init["notification_config"][field][i][subfield] - else: - del request_init["notification_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 = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.UpdateNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("notificationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateNotificationConfigRequest.pb(securitycenter_service.UpdateNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) - - request = securitycenter_service.UpdateNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_notification_config.NotificationConfig() - - client.update_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'notification_config': {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_notification_config(request) - - -def test_update_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'notification_config': {'name': 'organizations/sample1/locations/sample2/notificationConfigs/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/v2/{notification_config.name=organizations/*/locations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_update_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateResourceValueConfigRequest, - dict, -]) -def test_update_resource_value_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} - request_init["resource_value_config"] = {'name': 'organizations/sample1/resourceValueConfigs/sample2', 'resource_value': 1, 'tag_values': ['tag_values_value1', 'tag_values_value2'], 'resource_type': 'resource_type_value', 'scope': 'scope_value', 'resource_labels_selector': {}, 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'cloud_provider': 1, 'sensitive_data_protection_mapping': {'high_sensitivity_mapping': 1, 'medium_sensitivity_mapping': 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 = securitycenter_service.UpdateResourceValueConfigRequest.meta.fields["resource_value_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["resource_value_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["resource_value_config"][field])): - del request_init["resource_value_config"][field][i][subfield] - else: - del request_init["resource_value_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 = gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - -def test_update_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - - request = {} - client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.UpdateResourceValueConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_resource_value_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_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_resource_value_config.ResourceValueConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_resource_value_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_resource_value_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("resourceValueConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_resource_value_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_resource_value_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_resource_value_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateResourceValueConfigRequest.pb(securitycenter_service.UpdateResourceValueConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_resource_value_config.ResourceValueConfig.to_json(gcs_resource_value_config.ResourceValueConfig()) - - request = securitycenter_service.UpdateResourceValueConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_resource_value_config.ResourceValueConfig() - - client.update_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateResourceValueConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_resource_value_config(request) - - -def test_update_resource_value_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_resource_value_config.ResourceValueConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - resource_value_config=gcs_resource_value_config.ResourceValueConfig(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 = gcs_resource_value_config.ResourceValueConfig.pb(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_resource_value_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/v2/{resource_value_config.name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) - - -def test_update_resource_value_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_config( - securitycenter_service.UpdateResourceValueConfigRequest(), - resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_resource_value_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks'}} - request_init["security_marks"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks', 'marks': {}, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] - - 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["security_marks"].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["security_marks"][field])): - del request_init["security_marks"][field][i][subfield] - else: - del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - -def test_update_security_marks_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_security_marks._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_security_marks._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_security_marks_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_security_marks._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("securityMarks", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_security_marks_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) - - request = securitycenter_service.UpdateSecurityMarksRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_security_marks.SecurityMarks() - - client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_security_marks(request) - - -def test_update_security_marks_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - - # get arguments that satisfy an http rule for this method - sample_request = {'security_marks': {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks'}} - - # get truthy value for each flattened field - mock_args = dict( - security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}" % client.transport._host, args[1]) - - -def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_security_marks_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.UpdateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_source(request) - - -def test_update_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v2/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_update_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SecurityCenterClient( - 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 = SecurityCenterClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SecurityCenterClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SecurityCenterClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SecurityCenterGrpcTransport, - ) - -def test_security_center_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_security_center_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.securitycenter_v2.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'batch_create_resource_value_configs', - 'bulk_mute_findings', - 'create_big_query_export', - 'create_finding', - 'create_mute_config', - 'create_notification_config', - 'create_source', - 'delete_big_query_export', - 'delete_mute_config', - 'delete_notification_config', - 'delete_resource_value_config', - 'get_big_query_export', - 'get_simulation', - 'get_valued_resource', - 'get_iam_policy', - 'get_mute_config', - 'get_notification_config', - 'get_resource_value_config', - 'get_source', - 'group_findings', - 'list_attack_paths', - 'list_big_query_exports', - 'list_findings', - 'list_mute_configs', - 'list_notification_configs', - 'list_resource_value_configs', - 'list_sources', - 'list_valued_resources', - 'set_finding_state', - 'set_iam_policy', - 'set_mute', - 'test_iam_permissions', - 'update_big_query_export', - 'update_external_system', - 'update_finding', - 'update_mute_config', - 'update_notification_config', - 'update_resource_value_config', - 'update_security_marks', - 'update_source', - '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_security_center_base_transport_with_credentials_file(): - # Instantiate the 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.securitycenter_v2.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - 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_security_center_base_transport_with_adc(): - # Test the default 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.securitycenter_v2.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport() - adc.assert_called_once() - - -def test_security_center_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) - SecurityCenterClient() - 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -def test_security_center_transport_auth_adc(transport_class): - # If 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, - ], -) -def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), - (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_security_center_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host 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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_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.SecurityCenterRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_security_center_rest_lro_client(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a 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 - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_no_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_with_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_security_center_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SecurityCenterClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SecurityCenterClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.batch_create_resource_value_configs._session - session2 = client2.transport.batch_create_resource_value_configs._session - assert session1 != session2 - session1 = client1.transport.bulk_mute_findings._session - session2 = client2.transport.bulk_mute_findings._session - assert session1 != session2 - session1 = client1.transport.create_big_query_export._session - session2 = client2.transport.create_big_query_export._session - assert session1 != session2 - session1 = client1.transport.create_finding._session - session2 = client2.transport.create_finding._session - assert session1 != session2 - session1 = client1.transport.create_mute_config._session - session2 = client2.transport.create_mute_config._session - assert session1 != session2 - session1 = client1.transport.create_notification_config._session - session2 = client2.transport.create_notification_config._session - assert session1 != session2 - session1 = client1.transport.create_source._session - session2 = client2.transport.create_source._session - assert session1 != session2 - session1 = client1.transport.delete_big_query_export._session - session2 = client2.transport.delete_big_query_export._session - assert session1 != session2 - session1 = client1.transport.delete_mute_config._session - session2 = client2.transport.delete_mute_config._session - assert session1 != session2 - session1 = client1.transport.delete_notification_config._session - session2 = client2.transport.delete_notification_config._session - assert session1 != session2 - session1 = client1.transport.delete_resource_value_config._session - session2 = client2.transport.delete_resource_value_config._session - assert session1 != session2 - session1 = client1.transport.get_big_query_export._session - session2 = client2.transport.get_big_query_export._session - assert session1 != session2 - session1 = client1.transport.get_simulation._session - session2 = client2.transport.get_simulation._session - assert session1 != session2 - session1 = client1.transport.get_valued_resource._session - session2 = client2.transport.get_valued_resource._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.get_mute_config._session - session2 = client2.transport.get_mute_config._session - assert session1 != session2 - session1 = client1.transport.get_notification_config._session - session2 = client2.transport.get_notification_config._session - assert session1 != session2 - session1 = client1.transport.get_resource_value_config._session - session2 = client2.transport.get_resource_value_config._session - assert session1 != session2 - session1 = client1.transport.get_source._session - session2 = client2.transport.get_source._session - assert session1 != session2 - session1 = client1.transport.group_findings._session - session2 = client2.transport.group_findings._session - assert session1 != session2 - session1 = client1.transport.list_attack_paths._session - session2 = client2.transport.list_attack_paths._session - assert session1 != session2 - session1 = client1.transport.list_big_query_exports._session - session2 = client2.transport.list_big_query_exports._session - assert session1 != session2 - session1 = client1.transport.list_findings._session - session2 = client2.transport.list_findings._session - assert session1 != session2 - session1 = client1.transport.list_mute_configs._session - session2 = client2.transport.list_mute_configs._session - assert session1 != session2 - session1 = client1.transport.list_notification_configs._session - session2 = client2.transport.list_notification_configs._session - assert session1 != session2 - session1 = client1.transport.list_resource_value_configs._session - session2 = client2.transport.list_resource_value_configs._session - assert session1 != session2 - session1 = client1.transport.list_sources._session - session2 = client2.transport.list_sources._session - assert session1 != session2 - session1 = client1.transport.list_valued_resources._session - session2 = client2.transport.list_valued_resources._session - assert session1 != session2 - session1 = client1.transport.set_finding_state._session - session2 = client2.transport.set_finding_state._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.set_mute._session - session2 = client2.transport.set_mute._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 - session1 = client1.transport.update_big_query_export._session - session2 = client2.transport.update_big_query_export._session - assert session1 != session2 - session1 = client1.transport.update_external_system._session - session2 = client2.transport.update_external_system._session - assert session1 != session2 - session1 = client1.transport.update_finding._session - session2 = client2.transport.update_finding._session - assert session1 != session2 - session1 = client1.transport.update_mute_config._session - session2 = client2.transport.update_mute_config._session - assert session1 != session2 - session1 = client1.transport.update_notification_config._session - session2 = client2.transport.update_notification_config._session - assert session1 != session2 - session1 = client1.transport.update_resource_value_config._session - session2 = client2.transport.update_resource_value_config._session - assert session1 != session2 - session1 = client1.transport.update_security_marks._session - session2 = client2.transport.update_security_marks._session - assert session1 != session2 - session1 = client1.transport.update_source._session - session2 = client2.transport.update_source._session - assert session1 != session2 -def test_security_center_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcTransport( - 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_security_center_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcAsyncIOTransport( - 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(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_security_center_grpc_lro_client(): - client = SecurityCenterClient( - 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_security_center_grpc_lro_async_client(): - client = SecurityCenterAsyncClient( - 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_attack_path_path(): - organization = "squid" - simulation = "clam" - valued_resource = "whelk" - attack_path = "octopus" - expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) - actual = SecurityCenterClient.attack_path_path(organization, simulation, valued_resource, attack_path) - assert expected == actual - - -def test_parse_attack_path_path(): - expected = { - "organization": "oyster", - "simulation": "nudibranch", - "valued_resource": "cuttlefish", - "attack_path": "mussel", - } - path = SecurityCenterClient.attack_path_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_attack_path_path(path) - assert expected == actual - -def test_big_query_export_path(): - organization = "winkle" - location = "nautilus" - export = "scallop" - expected = "organizations/{organization}/locations/{location}/bigQueryExports/{export}".format(organization=organization, location=location, export=export, ) - actual = SecurityCenterClient.big_query_export_path(organization, location, export) - assert expected == actual - - -def test_parse_big_query_export_path(): - expected = { - "organization": "abalone", - "location": "squid", - "export": "clam", - } - path = SecurityCenterClient.big_query_export_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_big_query_export_path(path) - assert expected == actual - -def test_dlp_job_path(): - project = "whelk" - dlp_job = "octopus" - expected = "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) - actual = SecurityCenterClient.dlp_job_path(project, dlp_job) - assert expected == actual - - -def test_parse_dlp_job_path(): - expected = { - "project": "oyster", - "dlp_job": "nudibranch", - } - path = SecurityCenterClient.dlp_job_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_dlp_job_path(path) - assert expected == actual - -def test_external_system_path(): - organization = "cuttlefish" - source = "mussel" - finding = "winkle" - externalsystem = "nautilus" - expected = "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) - actual = SecurityCenterClient.external_system_path(organization, source, finding, externalsystem) - assert expected == actual - - -def test_parse_external_system_path(): - expected = { - "organization": "scallop", - "source": "abalone", - "finding": "squid", - "externalsystem": "clam", - } - path = SecurityCenterClient.external_system_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_external_system_path(path) - assert expected == actual - -def test_finding_path(): - organization = "whelk" - source = "octopus" - finding = "oyster" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - actual = SecurityCenterClient.finding_path(organization, source, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "organization": "nudibranch", - "source": "cuttlefish", - "finding": "mussel", - } - path = SecurityCenterClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_finding_path(path) - assert expected == actual - -def test_mute_config_path(): - organization = "winkle" - mute_config = "nautilus" - expected = "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) - actual = SecurityCenterClient.mute_config_path(organization, mute_config) - assert expected == actual - - -def test_parse_mute_config_path(): - expected = { - "organization": "scallop", - "mute_config": "abalone", - } - path = SecurityCenterClient.mute_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_mute_config_path(path) - assert expected == actual - -def test_notification_config_path(): - organization = "squid" - location = "clam" - notification_config = "whelk" - expected = "organizations/{organization}/locations/{location}/notificationConfigs/{notification_config}".format(organization=organization, location=location, notification_config=notification_config, ) - actual = SecurityCenterClient.notification_config_path(organization, location, notification_config) - assert expected == actual - - -def test_parse_notification_config_path(): - expected = { - "organization": "octopus", - "location": "oyster", - "notification_config": "nudibranch", - } - path = SecurityCenterClient.notification_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_notification_config_path(path) - assert expected == actual - -def test_policy_path(): - organization = "cuttlefish" - constraint_name = "mussel" - expected = "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) - actual = SecurityCenterClient.policy_path(organization, constraint_name) - assert expected == actual - - -def test_parse_policy_path(): - expected = { - "organization": "winkle", - "constraint_name": "nautilus", - } - path = SecurityCenterClient.policy_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_policy_path(path) - assert expected == actual - -def test_resource_value_config_path(): - organization = "scallop" - resource_value_config = "abalone" - expected = "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) - actual = SecurityCenterClient.resource_value_config_path(organization, resource_value_config) - assert expected == actual - - -def test_parse_resource_value_config_path(): - expected = { - "organization": "squid", - "resource_value_config": "clam", - } - path = SecurityCenterClient.resource_value_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_resource_value_config_path(path) - assert expected == actual - -def test_security_marks_path(): - organization = "whelk" - asset = "octopus" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.security_marks_path(organization, asset) - assert expected == actual - - -def test_parse_security_marks_path(): - expected = { - "organization": "oyster", - "asset": "nudibranch", - } - path = SecurityCenterClient.security_marks_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_security_marks_path(path) - assert expected == actual - -def test_simulation_path(): - organization = "cuttlefish" - simulation = "mussel" - expected = "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) - actual = SecurityCenterClient.simulation_path(organization, simulation) - assert expected == actual - - -def test_parse_simulation_path(): - expected = { - "organization": "winkle", - "simulation": "nautilus", - } - path = SecurityCenterClient.simulation_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_simulation_path(path) - assert expected == actual - -def test_source_path(): - organization = "scallop" - source = "abalone" - expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - actual = SecurityCenterClient.source_path(organization, source) - assert expected == actual - - -def test_parse_source_path(): - expected = { - "organization": "squid", - "source": "clam", - } - path = SecurityCenterClient.source_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_source_path(path) - assert expected == actual - -def test_table_data_profile_path(): - project = "whelk" - table_profile = "octopus" - expected = "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) - actual = SecurityCenterClient.table_data_profile_path(project, table_profile) - assert expected == actual - - -def test_parse_table_data_profile_path(): - expected = { - "project": "oyster", - "table_profile": "nudibranch", - } - path = SecurityCenterClient.table_data_profile_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_table_data_profile_path(path) - assert expected == actual - -def test_topic_path(): - project = "cuttlefish" - topic = "mussel" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = SecurityCenterClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "winkle", - "topic": "nautilus", - } - path = SecurityCenterClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_topic_path(path) - assert expected == actual - -def test_valued_resource_path(): - organization = "scallop" - simulation = "abalone" - valued_resource = "squid" - expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) - actual = SecurityCenterClient.valued_resource_path(organization, simulation, valued_resource) - assert expected == actual - - -def test_parse_valued_resource_path(): - expected = { - "organization": "clam", - "simulation": "whelk", - "valued_resource": "octopus", - } - path = SecurityCenterClient.valued_resource_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_valued_resource_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SecurityCenterClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = SecurityCenterClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = SecurityCenterClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = SecurityCenterClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SecurityCenterClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = SecurityCenterClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = SecurityCenterClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = SecurityCenterClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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 = SecurityCenterClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = SecurityCenterClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - transport_class = SecurityCenterClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations/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 = 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.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations/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 = 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_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations/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() - - # 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 - - 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(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations'}, 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() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations'} - request = request_type(**request_init) - # Mock the http request call within the method and 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.ListOperationsResponse() - - # 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 - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), -]) -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-securitycenter/google/cloud/securitycenter/gapic_version.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter/gapic_version.py index fb9de72fa8c4..558c8aab67c5 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter/gapic_version.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.33.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/gapic_version.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/gapic_version.py index fb9de72fa8c4..558c8aab67c5 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/gapic_version.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.33.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1beta1/gapic_version.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1beta1/gapic_version.py index fb9de72fa8c4..558c8aab67c5 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1beta1/gapic_version.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.33.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1p1beta1/gapic_version.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1p1beta1/gapic_version.py index fb9de72fa8c4..558c8aab67c5 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1p1beta1/gapic_version.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1p1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.33.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/gapic_version.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/gapic_version.py index fb9de72fa8c4..558c8aab67c5 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/gapic_version.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.33.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/async_client.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/async_client.py index 7521b961852b..e992367c8155 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/async_client.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/async_client.py @@ -403,7 +403,6 @@ async def sample_batch_create_resource_value_configs(): # Initialize request argument(s) requests = securitycenter_v2.CreateResourceValueConfigRequest() requests.parent = "parent_value" - requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( parent="parent_value", @@ -696,9 +695,9 @@ async def sample_create_big_query_export(): parent (:class:`str`): Required. The name of the parent resource of the new BigQuery export. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -962,7 +961,7 @@ async def sample_create_mute_config(): # Initialize request argument(s) mute_config = securitycenter_v2.MuteConfig() mute_config.filter = "filter_value" - mute_config.type_ = "STATIC" + mute_config.type_ = "DYNAMIC" request = securitycenter_v2.CreateMuteConfigRequest( parent="parent_value", @@ -983,9 +982,9 @@ async def sample_create_mute_config(): parent (:class:`str`): Required. Resource name of the new mute configs's parent. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1123,9 +1122,9 @@ async def sample_create_notification_config(): parent (:class:`str`): Required. Resource name of the new notification config's parent. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1264,7 +1263,7 @@ async def sample_create_source(): source. parent (:class:`str`): Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". + format should be ``organizations/[organization_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1919,12 +1918,12 @@ async def sample_get_simulation(): simulation For example, "organizations/123/simulations/latest". name (:class:`str`): - Required. The organization name or - simulation name of this simulation - Valid format: + Required. The organization name or simulation name of + this simulation - "organizations/{organization}/simulations/latest" - "organizations/{organization}/simulations/{simulation}" + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2032,7 +2031,7 @@ async def sample_get_valued_resource(): Required. The name of this valued resource Valid format: - "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}" + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2626,7 +2625,7 @@ async def sample_get_source(): name (:class:`str`): Required. Relative resource name of the source. Its format is - "organizations/[organization_id]/source/[source_id]". + ``organizations/[organization_id]/source/[source_id]``. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2914,10 +2913,10 @@ async def sample_list_attack_paths(): parent (:class:`str`): Required. Name of parent to list attack paths. - Valid formats: "organizations/{organization}", - "organizations/{organization}/simulations/{simulation}" - "organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}" - "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}" + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -3049,9 +3048,9 @@ async def sample_list_big_query_exports(): parent (:class:`str`): Required. The parent, which owns the collection of BigQuery exports. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -3331,11 +3330,11 @@ async def sample_list_mute_configs(): parent (:class:`str`): Required. The parent, which owns the collection of mute configs. Its format is - "organizations/[organization_id]", - "folders/[folder_id]", "projects/[project_id]", - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]", "folders/[folder_id]``, + ``projects/[project_id]``, + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, + ``projects/[project_id]/locations/[location_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -3587,7 +3586,7 @@ async def sample_list_resource_value_configs(): parent (:class:`str`): Required. The parent, which owns the collection of resource value configs. Its format is - "organizations/[organization_id]" + ``organizations/[organization_id]`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -3712,8 +3711,8 @@ async def sample_list_sources(): parent (:class:`str`): Required. Resource name of the parent of sources to list. Its format should be - "organizations/[organization_id]", - "folders/[folder_id]", or "projects/[project_id]". + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -3838,9 +3837,9 @@ async def sample_list_valued_resources(): parent (:class:`str`): Required. Name of parent to list exposed resources. - Valid formats: "organizations/{organization}", - "organizations/{organization}/simulations/{simulation}" - "organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}" + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -4876,7 +4875,7 @@ async def sample_update_mute_config(): # Initialize request argument(s) mute_config = securitycenter_v2.MuteConfig() mute_config.filter = "filter_value" - mute_config.type_ = "STATIC" + mute_config.type_ = "DYNAMIC" request = securitycenter_v2.UpdateMuteConfigRequest( mute_config=mute_config, @@ -5133,11 +5132,7 @@ async def sample_update_resource_value_config(): client = securitycenter_v2.SecurityCenterAsyncClient() # Initialize request argument(s) - resource_value_config = securitycenter_v2.ResourceValueConfig() - resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - request = securitycenter_v2.UpdateResourceValueConfigRequest( - resource_value_config=resource_value_config, ) # Make the request diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/client.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/client.py index 83c038810570..56ccc9e58154 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/client.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/client.py @@ -1065,7 +1065,6 @@ def sample_batch_create_resource_value_configs(): # Initialize request argument(s) requests = securitycenter_v2.CreateResourceValueConfigRequest() requests.parent = "parent_value" - requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( parent="parent_value", @@ -1354,9 +1353,9 @@ def sample_create_big_query_export(): parent (str): Required. The name of the parent resource of the new BigQuery export. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1614,7 +1613,7 @@ def sample_create_mute_config(): # Initialize request argument(s) mute_config = securitycenter_v2.MuteConfig() mute_config.filter = "filter_value" - mute_config.type_ = "STATIC" + mute_config.type_ = "DYNAMIC" request = securitycenter_v2.CreateMuteConfigRequest( parent="parent_value", @@ -1635,9 +1634,9 @@ def sample_create_mute_config(): parent (str): Required. Resource name of the new mute configs's parent. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1794,9 +1793,9 @@ def sample_create_notification_config(): parent (str): Required. Resource name of the new notification config's parent. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1934,7 +1933,7 @@ def sample_create_source(): source. parent (str): Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". + format should be ``organizations/[organization_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -2597,12 +2596,12 @@ def sample_get_simulation(): simulation For example, "organizations/123/simulations/latest". name (str): - Required. The organization name or - simulation name of this simulation - Valid format: + Required. The organization name or simulation name of + this simulation - "organizations/{organization}/simulations/latest" - "organizations/{organization}/simulations/{simulation}" + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2707,7 +2706,7 @@ def sample_get_valued_resource(): Required. The name of this valued resource Valid format: - "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}" + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -3314,7 +3313,7 @@ def sample_get_source(): name (str): Required. Relative resource name of the source. Its format is - "organizations/[organization_id]/source/[source_id]". + ``organizations/[organization_id]/source/[source_id]``. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -3596,10 +3595,10 @@ def sample_list_attack_paths(): parent (str): Required. Name of parent to list attack paths. - Valid formats: "organizations/{organization}", - "organizations/{organization}/simulations/{simulation}" - "organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}" - "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}" + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -3728,9 +3727,9 @@ def sample_list_big_query_exports(): parent (str): Required. The parent, which owns the collection of BigQuery exports. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -4004,11 +4003,11 @@ def sample_list_mute_configs(): parent (str): Required. The parent, which owns the collection of mute configs. Its format is - "organizations/[organization_id]", - "folders/[folder_id]", "projects/[project_id]", - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]", "folders/[folder_id]``, + ``projects/[project_id]``, + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, + ``projects/[project_id]/locations/[location_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -4278,7 +4277,7 @@ def sample_list_resource_value_configs(): parent (str): Required. The parent, which owns the collection of resource value configs. Its format is - "organizations/[organization_id]" + ``organizations/[organization_id]`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -4402,8 +4401,8 @@ def sample_list_sources(): parent (str): Required. Resource name of the parent of sources to list. Its format should be - "organizations/[organization_id]", - "folders/[folder_id]", or "projects/[project_id]". + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -4525,9 +4524,9 @@ def sample_list_valued_resources(): parent (str): Required. Name of parent to list exposed resources. - Valid formats: "organizations/{organization}", - "organizations/{organization}/simulations/{simulation}" - "organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}" + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -5549,7 +5548,7 @@ def sample_update_mute_config(): # Initialize request argument(s) mute_config = securitycenter_v2.MuteConfig() mute_config.filter = "filter_value" - mute_config.type_ = "STATIC" + mute_config.type_ = "DYNAMIC" request = securitycenter_v2.UpdateMuteConfigRequest( mute_config=mute_config, @@ -5822,11 +5821,7 @@ def sample_update_resource_value_config(): client = securitycenter_v2.SecurityCenterClient() # Initialize request argument(s) - resource_value_config = securitycenter_v2.ResourceValueConfig() - resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - request = securitycenter_v2.UpdateResourceValueConfigRequest( - resource_value_config=resource_value_config, ) # Make the request diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_exposure.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_exposure.py index f019a48275ca..3f09e58913df 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_exposure.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_exposure.py @@ -42,10 +42,10 @@ class AttackExposure(proto.Message): The most recent time the attack exposure was updated on this finding. attack_exposure_result (str): - The resource name of the attack path - simulation result that contains the details - regarding this attack exposure score. Example: - organizations/123/simulations/456/attackExposureResults/789 + The resource name of the attack path simulation result that + contains the details regarding this attack exposure score. + Example: + ``organizations/123/simulations/456/attackExposureResults/789`` state (google.cloud.securitycenter_v2.types.AttackExposure.State): Output only. What state this AttackExposure is in. This captures whether or not an attack diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_path.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_path.py index a1c3d4b3c32c..9bd83c1491bf 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_path.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_path.py @@ -52,10 +52,10 @@ class AttackPathNode(proto.Message): The name of the resource at this point in the attack path. The format of the name follows the Cloud Asset Inventory `resource name - format <"https://cloud.google.com/asset-inventory/docs/resource-name-format">`__ + format `__ resource_type (str): The `supported resource - type `__ + type `__ display_name (str): Human-readable name of this resource. associated_findings (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.PathNodeAssociatedFinding]): @@ -95,9 +95,8 @@ class PathNodeAssociatedFinding(proto.Message): Attributes: canonical_finding (str): - Canonical name of the associated findings. - Example: - organizations/123/sources/456/findings/789 + Canonical name of the associated findings. Example: + ``organizations/123/sources/456/findings/789`` finding_category (str): The additional taxonomy group within findings from a given source. diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/bigquery_export.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/bigquery_export.py index 68554295fdfd..89012e9e94c3 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/bigquery_export.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/bigquery_export.py @@ -33,7 +33,7 @@ class BigQueryExport(proto.Message): Attributes: name (str): - The relative resource name of this export. See: + Identifier. The relative resource name of this export. See: https://cloud.google.com/apis/design/resource_names#relative_resource_name. The following list shows some examples: @@ -77,7 +77,7 @@ class BigQueryExport(proto.Message): dataset (str): The dataset to write findings' updates to. Its format is "projects/[project_id]/datasets/[bigquery_dataset_id]". - BigQuery Dataset unique ID must contain only letters (a-z, + BigQuery dataset unique ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time at which the BigQuery diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/finding.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/finding.py index e355720e1846..1c6b7d9f07a0 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/finding.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/finding.py @@ -191,6 +191,9 @@ class Finding(proto.Message): muted, unmuted or undefined). Unlike other attributes of a finding, a finding provider shouldn't set the value of mute. + mute_info (google.cloud.securitycenter_v2.types.Finding.MuteInfo): + Output only. The mute information regarding + this finding. finding_class (google.cloud.securitycenter_v2.types.Finding.FindingClass): The class of the finding. indicator (google.cloud.securitycenter_v2.types.Indicator): @@ -495,6 +498,83 @@ class FindingClass(proto.Enum): POSTURE_VIOLATION = 6 TOXIC_COMBINATION = 7 + class MuteInfo(proto.Message): + r"""Mute information about the finding, including whether the + finding has a static mute or any matching dynamic mute rules. + + Attributes: + static_mute (google.cloud.securitycenter_v2.types.Finding.MuteInfo.StaticMute): + If set, the static mute applied to this + finding. Static mutes override dynamic mutes. If + unset, there is no static mute. + dynamic_mute_records (MutableSequence[google.cloud.securitycenter_v2.types.Finding.MuteInfo.DynamicMuteRecord]): + The list of dynamic mute rules that currently + match the finding. + """ + + class StaticMute(proto.Message): + r"""Information about the static mute state. A static mute state + overrides any dynamic mute rules that apply to this finding. The + static mute state can be set by a static mute rule or by muting + the finding directly. + + Attributes: + state (google.cloud.securitycenter_v2.types.Finding.Mute): + The static mute state. If the value is ``MUTED`` or + ``UNMUTED``, then the finding's overall mute state will have + the same value. + apply_time (google.protobuf.timestamp_pb2.Timestamp): + When the static mute was applied. + """ + + state: "Finding.Mute" = proto.Field( + proto.ENUM, + number=1, + enum="Finding.Mute", + ) + apply_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + class DynamicMuteRecord(proto.Message): + r"""The record of a dynamic mute rule that matches the finding. + + Attributes: + mute_config (str): + The relative resource name of the mute rule, represented by + a mute config, that created this record, for example + ``organizations/123/muteConfigs/mymuteconfig`` or + ``organizations/123/locations/global/muteConfigs/mymuteconfig``. + match_time (google.protobuf.timestamp_pb2.Timestamp): + When the dynamic mute rule first matched the + finding. + """ + + mute_config: str = proto.Field( + proto.STRING, + number=1, + ) + match_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + static_mute: "Finding.MuteInfo.StaticMute" = proto.Field( + proto.MESSAGE, + number=1, + message="Finding.MuteInfo.StaticMute", + ) + dynamic_mute_records: MutableSequence[ + "Finding.MuteInfo.DynamicMuteRecord" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Finding.MuteInfo.DynamicMuteRecord", + ) + name: str = proto.Field( proto.STRING, number=1, @@ -555,6 +635,11 @@ class FindingClass(proto.Enum): number=15, enum=Mute, ) + mute_info: MuteInfo = proto.Field( + proto.MESSAGE, + number=53, + message=MuteInfo, + ) finding_class: FindingClass = proto.Field( proto.ENUM, number=16, diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mitre_attack.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mitre_attack.py index 6fcfb196ace4..64e19b3268df 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mitre_attack.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mitre_attack.py @@ -111,7 +111,7 @@ class Tactic(proto.Enum): class Technique(proto.Enum): r"""MITRE ATT&CK techniques that can be referenced by SCC findings. See: https://attack.mitre.org/techniques/enterprise/ - Next ID: 63 + Next ID: 65 Values: TECHNIQUE_UNSPECIFIED (0): @@ -134,10 +134,14 @@ class Technique(proto.Enum): T1059.004 PYTHON (59): T1059.006 + EXPLOITATION_FOR_PRIVILEGE_ESCALATION (63): + T1068 PERMISSION_GROUPS_DISCOVERY (18): T1069 CLOUD_GROUPS (19): T1069.003 + INDICATOR_REMOVAL_FILE_DELETION (64): + T1070.004 APPLICATION_LAYER_PROTOCOL (45): T1071 DNS (46): @@ -233,7 +237,7 @@ class Technique(proto.Enum): SCANNING_IP_BLOCKS (2): T1595.001 CONTAINER_ADMINISTRATION_COMMAND (60): - T1613 + T1609 ESCAPE_TO_HOST (61): T1611 CONTAINER_AND_RESOURCE_DISCOVERY (57): @@ -251,8 +255,10 @@ class Technique(proto.Enum): COMMAND_AND_SCRIPTING_INTERPRETER = 6 UNIX_SHELL = 7 PYTHON = 59 + EXPLOITATION_FOR_PRIVILEGE_ESCALATION = 63 PERMISSION_GROUPS_DISCOVERY = 18 CLOUD_GROUPS = 19 + INDICATOR_REMOVAL_FILE_DELETION = 64 APPLICATION_LAYER_PROTOCOL = 45 DNS = 46 SOFTWARE_DEPLOYMENT_TOOLS = 47 diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mute_config.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mute_config.py index c7b4bd0f194d..79a5abf08dad 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mute_config.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mute_config.py @@ -34,8 +34,9 @@ class MuteConfig(proto.Message): Attributes: name (str): - This field will be ignored if provided on config creation. - The following list shows some examples of the format: + Identifier. This field will be ignored if provided on config + creation. The following list shows some examples of the + format: - ``organizations/{organization}/muteConfigs/{mute_config}`` - @@ -89,6 +90,11 @@ class MuteConfig(proto.Message): Required. The type of the mute config, which determines what type of mute state the config affects. Immutable after creation. + expiry_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The expiry of the mute config. Only + applicable for dynamic configs. If the expiry is + set, when the config expires, it is removed from + all findings. """ class MuteConfigType(proto.Enum): @@ -103,9 +109,20 @@ class MuteConfigType(proto.Enum): Once the static mute state has been set, finding or config modifications will not affect the state. + DYNAMIC (2): + A dynamic mute config, which is applied to + existing and future matching findings, setting + their dynamic mute state to "muted". If the + config is updated or deleted, or a matching + finding is updated, such that the finding + doesn't match the config, the config will be + removed from the finding, and the finding's + dynamic mute state may become "unmuted" (unless + other configs still match). """ MUTE_CONFIG_TYPE_UNSPECIFIED = 0 STATIC = 1 + DYNAMIC = 2 name: str = proto.Field( proto.STRING, @@ -138,6 +155,11 @@ class MuteConfigType(proto.Enum): number=8, enum=MuteConfigType, ) + expiry_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/notification_config.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/notification_config.py index b968de83efed..4d30100ea9b4 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/notification_config.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/notification_config.py @@ -39,7 +39,8 @@ class NotificationConfig(proto.Message): Attributes: name (str): - The relative resource name of this notification config. See: + Identifier. The relative resource name of this notification + config. See: https://cloud.google.com/apis/design/resource_names#relative_resource_name The following list shows some examples: + ``organizations/{organization_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource.py index 06bb401f4d6f..d4a3ea140b7a 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource.py @@ -99,13 +99,13 @@ class Resource(proto.Message): resource_path_string (str): A string representation of the resource path. For Google Cloud, it has the format of - organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id} + ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` where there can be any number of folders. For AWS, it has the format of - org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id} + ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` where there can be any number of organizational units. For Azure, it has the format of - mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name} + ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` where there can be any number of management groups. """ @@ -338,8 +338,8 @@ class AzureManagementGroup(proto.Message): Attributes: id (str): - The UUID of the Azure management group, for - example, "20000000-0001-0000-0000-000000000000". + The UUID of the Azure management group, for example, + ``20000000-0001-0000-0000-000000000000``. display_name (str): The display name of the Azure management group. @@ -359,8 +359,8 @@ class AzureSubscription(proto.Message): Attributes: id (str): - The UUID of the Azure subscription, for - example, "291bba3f-e0a5-47bc-a099-3bdcb2a50a05". + The UUID of the Azure subscription, for example, + ``291bba3f-e0a5-47bc-a099-3bdcb2a50a05``. display_name (str): The display name of the Azure subscription. """ diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource_value_config.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource_value_config.py index 01e4060766ff..5c8a7048f653 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource_value_config.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource_value_config.py @@ -61,34 +61,34 @@ class ResourceValueConfig(proto.Message): Attributes: name (str): - Name for the resource value configuration + Identifier. Name for the resource value + configuration resource_value (google.cloud.securitycenter_v2.types.ResourceValue): Resource value level this expression - represents Only required when there is no SDP - mapping in the request + represents Only required when there is no + Sensitive Data Protection mapping in the request tag_values (MutableSequence[str]): - Required. Tag values combined with AND to check against. - Values in the form "tagValues/123" Example: [ - "tagValues/123", "tagValues/456", "tagValues/789" ] + Tag values combined with ``AND`` to check against. Values in + the form "tagValues/123" Example: + ``[ "tagValues/123", "tagValues/456", "tagValues/789" ]`` https://cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing resource_type (str): Apply resource_value only to resources that match - resource_type. resource_type will be checked with AND of + resource_type. resource_type will be checked with ``AND`` of other resources. For example, "storage.googleapis.com/Bucket" with resource_value "HIGH" will apply "HIGH" value only to "storage.googleapis.com/Bucket" resources. scope (str): - Project or folder to scope this configuration - to. For example, "project/456" would apply this - configuration only to resources in "project/456" - scope will be checked with AND of - other resources. + Project or folder to scope this configuration to. For + example, "project/456" would apply this configuration only + to resources in "project/456" scope and will be checked with + ``AND`` of other resources. resource_labels_selector (MutableMapping[str, str]): - List of resource labels to search for, evaluated with AND. - For example, "resource_labels_selector": {"key": "value", - "env": "prod"} will match resources with labels "key": - "value" AND "env": "prod" + List of resource labels to search for, evaluated with + ``AND``. For example, "resource_labels_selector": {"key": + "value", "env": "prod"} will match resources with labels + "key": "value" ``AND`` "env": "prod" https://cloud.google.com/resource-manager/docs/creating-managing-labels description (str): Description of the resource value diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/securitycenter_service.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/securitycenter_service.py index ffb631a1e35e..c70cdbf00092 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/securitycenter_service.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/securitycenter_service.py @@ -179,8 +179,29 @@ class BulkMuteFindingsRequest(proto.Message): - string literals in quotes. - integer literals without quotes. - boolean literals ``true`` and ``false`` without quotes. + mute_state (google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest.MuteState): + Optional. All findings matching the given filter will have + their mute state set to this value. The default value is + ``MUTED``. Setting this to ``UNDEFINED`` will clear the mute + state on all matching findings. """ + class MuteState(proto.Enum): + r"""The mute state. + + Values: + MUTE_STATE_UNSPECIFIED (0): + Unused. + MUTED (1): + Matching findings will be muted (default). + UNDEFINED (2): + Matching findings will have their mute state + cleared. + """ + MUTE_STATE_UNSPECIFIED = 0 + MUTED = 1 + UNDEFINED = 2 + parent: str = proto.Field( proto.STRING, number=1, @@ -189,6 +210,11 @@ class BulkMuteFindingsRequest(proto.Message): proto.STRING, number=2, ) + mute_state: MuteState = proto.Field( + proto.ENUM, + number=3, + enum=MuteState, + ) class BulkMuteFindingsResponse(proto.Message): @@ -205,9 +231,9 @@ class CreateBigQueryExportRequest(proto.Message): parent (str): Required. The name of the parent resource of the new BigQuery export. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): Required. The BigQuery export being created. big_query_export_id (str): @@ -277,9 +303,9 @@ class CreateMuteConfigRequest(proto.Message): parent (str): Required. Resource name of the new mute configs's parent. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. mute_config (google.cloud.securitycenter_v2.types.MuteConfig): Required. The mute config being created. mute_config_id (str): @@ -313,9 +339,9 @@ class CreateNotificationConfigRequest(proto.Message): parent (str): Required. Resource name of the new notification config's parent. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. config_id (str): Required. Unique identifier provided by the client within @@ -373,7 +399,7 @@ class CreateSourceRequest(proto.Message): Attributes: parent (str): Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". + format should be ``organizations/[organization_id]``. source (google.cloud.securitycenter_v2.types.Source): Required. The Source being created, only the display_name and description will be used. All other fields will be @@ -570,7 +596,7 @@ class GetSourceRequest(proto.Message): Attributes: name (str): Required. Relative resource name of the source. Its format - is "organizations/[organization_id]/source/[source_id]". + is ``organizations/[organization_id]/source/[source_id]``. """ name: str = proto.Field( @@ -774,10 +800,10 @@ class ListAttackPathsRequest(proto.Message): parent (str): Required. Name of parent to list attack paths. - Valid formats: "organizations/{organization}", - "organizations/{organization}/simulations/{simulation}" - "organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}" - "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}". + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` filter (str): The filter expression that filters the attack path in the response. Supported fields: @@ -847,12 +873,12 @@ class GetSimulationRequest(proto.Message): Attributes: name (str): - Required. The organization name or simulation - name of this simulation - Valid format: + Required. The organization name or simulation name of this + simulation - "organizations/{organization}/simulations/latest" - "organizations/{organization}/simulations/{simulation}". + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` """ name: str = proto.Field( @@ -869,7 +895,7 @@ class GetValuedResourceRequest(proto.Message): Required. The name of this valued resource Valid format: - "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}". + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` """ name: str = proto.Field( @@ -886,9 +912,9 @@ class ListBigQueryExportsRequest(proto.Message): parent (str): Required. The parent, which owns the collection of BigQuery exports. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. page_size (int): The maximum number of configs to return. The service may return fewer than this value. @@ -1162,13 +1188,13 @@ class Resource(proto.Message): resource_path_string (str): A string representation of the resource path. For Google Cloud, it has the format of - organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id} + ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` where there can be any number of folders. For AWS, it has the format of - org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id} + ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` where there can be any number of organizational units. For Azure, it has the format of - mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name} + ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` where there can be any number of management groups. """ @@ -1263,11 +1289,12 @@ class ListMuteConfigsRequest(proto.Message): Attributes: parent (str): Required. The parent, which owns the collection of mute - configs. Its format is "organizations/[organization_id]", - "folders/[folder_id]", "projects/[project_id]", - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", - "projects/[project_id]/locations/[location_id]". + configs. Its format is + ``organizations/[organization_id]", "folders/[folder_id]``, + ``projects/[project_id]``, + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, + ``projects/[project_id]/locations/[location_id]``. page_size (int): The maximum number of configs to return. The service may return fewer than this value. @@ -1395,7 +1422,7 @@ class ListResourceValueConfigsRequest(proto.Message): parent (str): Required. The parent, which owns the collection of resource value configs. Its format is - "organizations/[organization_id]". + ``organizations/[organization_id]`` page_size (int): The maximum number of configs to return. The service may return fewer than this value. @@ -1465,8 +1492,8 @@ class ListSourcesRequest(proto.Message): Attributes: parent (str): Required. Resource name of the parent of sources to list. - Its format should be "organizations/[organization_id]", - "folders/[folder_id]", or "projects/[project_id]". + Its format should be ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. page_token (str): The value returned by the last ``ListSourcesResponse``; indicates that this is a continuation of a prior @@ -1526,9 +1553,9 @@ class ListValuedResourcesRequest(proto.Message): parent (str): Required. Name of parent to list exposed resources. - Valid formats: "organizations/{organization}", - "organizations/{organization}/simulations/{simulation}" - "organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}". + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` filter (str): The filter expression that filters the valued resources in the response. Supported fields: diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/simulation.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/simulation.py index 922002db1ae2..6286b1425290 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/simulation.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/simulation.py @@ -36,8 +36,7 @@ class Simulation(proto.Message): Attributes: name (str): Full resource name of the Simulation: - - organizations/123/simulations/456 + ``organizations/123/simulations/456`` create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. Time simulation was created resource_value_configs_metadata (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfigMetadata]): diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/vulnerability.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/vulnerability.py index 7e34b9a21f92..6fc4b6ed3216 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/vulnerability.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/vulnerability.py @@ -106,6 +106,9 @@ class Cve(proto.Message): zero_day (bool): Whether or not the vulnerability was zero day when the finding was published. + exploit_release_date (google.protobuf.timestamp_pb2.Timestamp): + Date the first publicly available exploit or + PoC was released. """ class RiskRating(proto.Enum): @@ -204,6 +207,11 @@ class ExploitationActivity(proto.Enum): proto.BOOL, number=8, ) + exploit_release_date: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) class Reference(proto.Message): diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py index 66c343ecf2b8..e74e57a22631 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py @@ -41,7 +41,6 @@ async def sample_batch_create_resource_value_configs(): # Initialize request argument(s) requests = securitycenter_v2.CreateResourceValueConfigRequest() requests.parent = "parent_value" - requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( parent="parent_value", diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py index bc2c6ec7cc85..d6c2ad8428ff 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py @@ -41,7 +41,6 @@ def sample_batch_create_resource_value_configs(): # Initialize request argument(s) requests = securitycenter_v2.CreateResourceValueConfigRequest() requests.parent = "parent_value" - requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( parent="parent_value", diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py index e178a9dbcfcc..c858b59a6586 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py @@ -41,7 +41,7 @@ async def sample_create_mute_config(): # Initialize request argument(s) mute_config = securitycenter_v2.MuteConfig() mute_config.filter = "filter_value" - mute_config.type_ = "STATIC" + mute_config.type_ = "DYNAMIC" request = securitycenter_v2.CreateMuteConfigRequest( parent="parent_value", diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py index 3d2028e3e2e2..a0de28b38bbd 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py @@ -41,7 +41,7 @@ def sample_create_mute_config(): # Initialize request argument(s) mute_config = securitycenter_v2.MuteConfig() mute_config.filter = "filter_value" - mute_config.type_ = "STATIC" + mute_config.type_ = "DYNAMIC" request = securitycenter_v2.CreateMuteConfigRequest( parent="parent_value", diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py index 467232733072..7796c39566e2 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py @@ -41,7 +41,7 @@ async def sample_update_mute_config(): # Initialize request argument(s) mute_config = securitycenter_v2.MuteConfig() mute_config.filter = "filter_value" - mute_config.type_ = "STATIC" + mute_config.type_ = "DYNAMIC" request = securitycenter_v2.UpdateMuteConfigRequest( mute_config=mute_config, diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py index bf9e519c9aff..920f6986fb3b 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py @@ -41,7 +41,7 @@ def sample_update_mute_config(): # Initialize request argument(s) mute_config = securitycenter_v2.MuteConfig() mute_config.filter = "filter_value" - mute_config.type_ = "STATIC" + mute_config.type_ = "DYNAMIC" request = securitycenter_v2.UpdateMuteConfigRequest( mute_config=mute_config, diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py index fa3d632023ab..0ecd6b7d2fd5 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py @@ -39,11 +39,7 @@ async def sample_update_resource_value_config(): client = securitycenter_v2.SecurityCenterAsyncClient() # Initialize request argument(s) - resource_value_config = securitycenter_v2.ResourceValueConfig() - resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - request = securitycenter_v2.UpdateResourceValueConfigRequest( - resource_value_config=resource_value_config, ) # Make the request diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py index fa6e10020fff..2508104c843d 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py @@ -39,11 +39,7 @@ def sample_update_resource_value_config(): client = securitycenter_v2.SecurityCenterClient() # Initialize request argument(s) - resource_value_config = securitycenter_v2.ResourceValueConfig() - resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - request = securitycenter_v2.UpdateResourceValueConfigRequest( - resource_value_config=resource_value_config, ) # Make the request diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json index 2afe1dce6f83..176395462f39 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json +++ b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-securitycenter", - "version": "1.33.1" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json index 538244890e88..a4c1295eaf99 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json +++ b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-securitycenter", - "version": "1.33.1" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json index bab39e47d4d0..774592ce11f7 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json +++ b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-securitycenter", - "version": "1.33.1" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json index e500f1cf3a45..3ebbbfe28b50 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json +++ b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-securitycenter", - "version": "1.33.1" + "version": "0.1.0" }, "snippets": [ { @@ -64,12 +64,12 @@ "regionTag": "securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_async", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -79,18 +79,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], @@ -148,12 +148,12 @@ "regionTag": "securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -163,18 +163,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], @@ -6149,12 +6149,12 @@ "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_async", "segments": [ { - "end": 54, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 50, "start": 27, "type": "SHORT" }, @@ -6164,18 +6164,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], @@ -6233,12 +6233,12 @@ "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_sync", "segments": [ { - "end": 54, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 50, "start": 27, "type": "SHORT" }, @@ -6248,18 +6248,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], diff --git a/packages/google-cloud-securitycenter/scripts/fixup_securitycenter_v2_keywords.py b/packages/google-cloud-securitycenter/scripts/fixup_securitycenter_v2_keywords.py index ea2090d422e1..f95da838422b 100644 --- a/packages/google-cloud-securitycenter/scripts/fixup_securitycenter_v2_keywords.py +++ b/packages/google-cloud-securitycenter/scripts/fixup_securitycenter_v2_keywords.py @@ -40,7 +40,7 @@ class securitycenterCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'batch_create_resource_value_configs': ('parent', 'requests', ), - 'bulk_mute_findings': ('parent', 'filter', ), + 'bulk_mute_findings': ('parent', 'filter', 'mute_state', ), 'create_big_query_export': ('parent', 'big_query_export', 'big_query_export_id', ), 'create_finding': ('parent', 'finding_id', 'finding', ), 'create_mute_config': ('parent', 'mute_config', 'mute_config_id', ), diff --git a/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/test_security_center.py b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/test_security_center.py index badcffb4fb46..d4ed25fa3cef 100644 --- a/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/test_security_center.py +++ b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/test_security_center.py @@ -20250,6 +20250,12 @@ def test_create_finding_rest(request_type): "create_time": {}, "severity": 1, "mute": 1, + "mute_info": { + "static_mute": {"state": 1, "apply_time": {}}, + "dynamic_mute_records": [ + {"mute_config": "mute_config_value", "match_time": {}} + ], + }, "finding_class": 1, "indicator": { "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], @@ -20288,6 +20294,7 @@ def test_create_finding_rest(request_type): "exploitation_activity": 1, "observed_in_the_wild": True, "zero_day": True, + "exploit_release_date": {}, }, "offending_package": { "package_name": "package_name_value", @@ -20980,6 +20987,7 @@ def test_create_mute_config_rest(request_type): "update_time": {}, "most_recent_editor": "most_recent_editor_value", "type_": 1, + "expiry_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 @@ -31515,6 +31523,12 @@ def test_update_finding_rest(request_type): "create_time": {}, "severity": 1, "mute": 1, + "mute_info": { + "static_mute": {"state": 1, "apply_time": {}}, + "dynamic_mute_records": [ + {"mute_config": "mute_config_value", "match_time": {}} + ], + }, "finding_class": 1, "indicator": { "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], @@ -31553,6 +31567,7 @@ def test_update_finding_rest(request_type): "exploitation_activity": 1, "observed_in_the_wild": True, "zero_day": True, + "exploit_release_date": {}, }, "offending_package": { "package_name": "package_name_value", @@ -32222,6 +32237,7 @@ def test_update_mute_config_rest(request_type): "update_time": {}, "most_recent_editor": "most_recent_editor_value", "type_": 1, + "expiry_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 From ae6e8e0fdb4d8b2e62fa496cca93923099ffac43 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 6 Aug 2024 00:56:52 +0000 Subject: [PATCH 3/4] feat: enable Dynamic Mute feat: New values `EXPLOITATION_FOR_PRIVILEGE_ESCALATION` corresponding to T1068 and `INDICATOR_REMOVAL_FILE_DELETION` corresponding to T1070.004 are added to enum `Technique` docs: T1068 is added for value `EXPLOITATION_FOR_PRIVILEGE_ESCALATION` and T1070.004 is added for value `INDICATOR_REMOVAL_FILE_DELETION` for enum `Technique PiperOrigin-RevId: 659656285 Source-Link: https://github.com/googleapis/googleapis/commit/ae593946b7cd10df5535b910b7a2ce2b64ff4098 Source-Link: https://github.com/googleapis/googleapis-gen/commit/1a6022a51bc210272b4a0a2ba76e5a44e8cf8cc6 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLXNlY3VyaXR5Y2VudGVyLy5Pd2xCb3QueWFtbCIsImgiOiIxYTYwMjJhNTFiYzIxMDI3MmI0YTBhMmJhNzZlNWE0NGU4Y2Y4Y2M2In0= --- .../v1/.coveragerc | 13 + .../google-cloud-securitycenter/v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../google-cloud-securitycenter/v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../v1/docs/conf.py | 376 + .../v1/docs/index.rst | 7 + .../securitycenter_v1/security_center.rst | 10 + .../v1/docs/securitycenter_v1/services_.rst | 6 + .../v1/docs/securitycenter_v1/types_.rst | 6 + .../google/cloud/securitycenter/__init__.py | 343 + .../cloud/securitycenter/gapic_version.py | 16 + .../v1/google/cloud/securitycenter/py.typed | 2 + .../cloud/securitycenter_v1/__init__.py | 344 + .../securitycenter_v1/gapic_metadata.json | 973 + .../cloud/securitycenter_v1/gapic_version.py | 16 + .../google/cloud/securitycenter_v1/py.typed | 2 + .../securitycenter_v1/services/__init__.py | 15 + .../services/security_center/__init__.py | 22 + .../services/security_center/async_client.py | 7965 +++ .../services/security_center/client.py | 8455 +++ .../services/security_center/pagers.py | 2333 + .../security_center/transports/__init__.py | 38 + .../security_center/transports/base.py | 1251 + .../security_center/transports/grpc.py | 2103 + .../transports/grpc_asyncio.py | 2583 + .../security_center/transports/rest.py | 8529 +++ .../cloud/securitycenter_v1/types/__init__.py | 440 + .../cloud/securitycenter_v1/types/access.py | 193 + .../securitycenter_v1/types/application.py | 55 + .../cloud/securitycenter_v1/types/asset.py | 227 + .../types/attack_exposure.py | 113 + .../securitycenter_v1/types/attack_path.py | 223 + .../types/backup_disaster_recovery.py | 137 + .../types/bigquery_export.py | 135 + .../securitycenter_v1/types/cloud_armor.py | 217 + .../types/cloud_dlp_data_profile.py | 71 + .../types/cloud_dlp_inspection.py | 70 + .../securitycenter_v1/types/compliance.py | 61 + .../securitycenter_v1/types/connection.py | 97 + .../types/contact_details.py | 61 + .../securitycenter_v1/types/container.py | 80 + .../cloud/securitycenter_v1/types/database.py | 98 + ...ve_event_threat_detection_custom_module.py | 113 + ...security_health_analytics_custom_module.py | 104 + .../event_threat_detection_custom_module.py | 138 + ...tection_custom_module_validation_errors.py | 123 + .../securitycenter_v1/types/exfiltration.py | 96 + .../types/external_system.py | 180 + .../cloud/securitycenter_v1/types/file.py | 113 + .../cloud/securitycenter_v1/types/finding.py | 774 + .../cloud/securitycenter_v1/types/folder.py | 54 + .../types/group_membership.py | 65 + .../securitycenter_v1/types/iam_binding.py | 77 + .../securitycenter_v1/types/indicator.py | 186 + .../securitycenter_v1/types/kernel_rootkit.py | 107 + .../securitycenter_v1/types/kubernetes.py | 398 + .../cloud/securitycenter_v1/types/label.py | 54 + .../securitycenter_v1/types/load_balancer.py | 47 + .../securitycenter_v1/types/log_entry.py | 96 + .../securitycenter_v1/types/mitre_attack.py | 340 + .../securitycenter_v1/types/mute_config.py | 171 + .../cloud/securitycenter_v1/types/notebook.py | 72 + .../types/notification_config.py | 127 + .../types/notification_message.py | 70 + .../securitycenter_v1/types/org_policy.py | 47 + .../types/organization_settings.py | 123 + .../cloud/securitycenter_v1/types/process.py | 136 + .../cloud/securitycenter_v1/types/resource.py | 474 + .../types/resource_value_config.py | 189 + .../types/run_asset_discovery_response.py | 76 + ...security_health_analytics_custom_config.py | 173 + ...security_health_analytics_custom_module.py | 138 + .../securitycenter_v1/types/security_marks.py | 80 + .../types/security_posture.py | 128 + .../types/securitycenter_service.py | 3519 ++ .../securitycenter_v1/types/simulation.py | 73 + .../cloud/securitycenter_v1/types/source.py | 88 + .../types/toxic_combination.py | 60 + .../types/valued_resource.py | 126 + .../securitycenter_v1/types/vulnerability.py | 546 + .../google-cloud-securitycenter/v1/mypy.ini | 3 + .../google-cloud-securitycenter/v1/noxfile.py | 280 + ...tch_create_resource_value_configs_async.py | 58 + ...atch_create_resource_value_configs_sync.py | 58 + ...ecurity_center_bulk_mute_findings_async.py | 56 + ...security_center_bulk_mute_findings_sync.py | 56 + ...ty_center_create_big_query_export_async.py | 53 + ...ity_center_create_big_query_export_sync.py | 53 + ...nt_threat_detection_custom_module_async.py | 52 + ...ent_threat_detection_custom_module_sync.py | 52 + ...ed_security_center_create_finding_async.py | 53 + ...ted_security_center_create_finding_sync.py | 53 + ...ecurity_center_create_mute_config_async.py | 57 + ...security_center_create_mute_config_sync.py | 57 + ...center_create_notification_config_async.py | 53 + ..._center_create_notification_config_sync.py | 53 + ...ty_health_analytics_custom_module_async.py | 52 + ...ity_health_analytics_custom_module_sync.py | 52 + ...ted_security_center_create_source_async.py | 52 + ...ated_security_center_create_source_sync.py | 52 + ...ty_center_delete_big_query_export_async.py | 50 + ...ity_center_delete_big_query_export_sync.py | 50 + ...nt_threat_detection_custom_module_async.py | 50 + ...ent_threat_detection_custom_module_sync.py | 50 + ...ecurity_center_delete_mute_config_async.py | 50 + ...security_center_delete_mute_config_sync.py | 50 + ...center_delete_notification_config_async.py | 50 + ..._center_delete_notification_config_sync.py | 50 + ...nter_delete_resource_value_config_async.py | 50 + ...enter_delete_resource_value_config_sync.py | 50 + ...ty_health_analytics_custom_module_async.py | 50 + ...ity_health_analytics_custom_module_sync.py | 50 + ...urity_center_get_big_query_export_async.py | 52 + ...curity_center_get_big_query_export_sync.py | 52 + ...nt_threat_detection_custom_module_async.py | 52 + ...ent_threat_detection_custom_module_sync.py | 52 + ...ty_health_analytics_custom_module_async.py | 52 + ...ity_health_analytics_custom_module_sync.py | 52 + ...nt_threat_detection_custom_module_async.py | 52 + ...ent_threat_detection_custom_module_sync.py | 52 + ...ed_security_center_get_iam_policy_async.py | 53 + ...ted_security_center_get_iam_policy_sync.py | 53 + ...d_security_center_get_mute_config_async.py | 52 + ...ed_security_center_get_mute_config_sync.py | 52 + ...ty_center_get_notification_config_async.py | 52 + ...ity_center_get_notification_config_sync.py | 52 + ..._center_get_organization_settings_async.py | 52 + ...y_center_get_organization_settings_sync.py | 52 + ..._center_get_resource_value_config_async.py | 52 + ...y_center_get_resource_value_config_sync.py | 52 + ...ty_health_analytics_custom_module_async.py | 52 + ...ity_health_analytics_custom_module_sync.py | 52 + ...ed_security_center_get_simulation_async.py | 52 + ...ted_security_center_get_simulation_sync.py | 52 + ...erated_security_center_get_source_async.py | 52 + ...nerated_security_center_get_source_sync.py | 52 + ...curity_center_get_valued_resource_async.py | 52 + ...ecurity_center_get_valued_resource_sync.py | 52 + ...ated_security_center_group_assets_async.py | 54 + ...rated_security_center_group_assets_sync.py | 54 + ...ed_security_center_group_findings_async.py | 54 + ...ted_security_center_group_findings_sync.py | 54 + ...rated_security_center_list_assets_async.py | 53 + ...erated_security_center_list_assets_sync.py | 53 + ...security_center_list_attack_paths_async.py | 53 + ..._security_center_list_attack_paths_sync.py | 53 + ...ity_center_list_big_query_exports_async.py | 53 + ...rity_center_list_big_query_exports_sync.py | 53 + ...t_threat_detection_custom_modules_async.py | 53 + ...nt_threat_detection_custom_modules_sync.py | 53 + ...y_health_analytics_custom_modules_async.py | 53 + ...ty_health_analytics_custom_modules_sync.py | 53 + ...t_threat_detection_custom_modules_async.py | 53 + ...nt_threat_detection_custom_modules_sync.py | 53 + ...y_health_analytics_custom_modules_async.py | 53 + ...ty_health_analytics_custom_modules_sync.py | 53 + ...t_threat_detection_custom_modules_async.py | 53 + ...nt_threat_detection_custom_modules_sync.py | 53 + ...ted_security_center_list_findings_async.py | 53 + ...ated_security_center_list_findings_sync.py | 53 + ...security_center_list_mute_configs_async.py | 53 + ..._security_center_list_mute_configs_sync.py | 53 + ..._center_list_notification_configs_async.py | 53 + ...y_center_list_notification_configs_sync.py | 53 + ...enter_list_resource_value_configs_async.py | 53 + ...center_list_resource_value_configs_sync.py | 53 + ...y_health_analytics_custom_modules_async.py | 53 + ...ty_health_analytics_custom_modules_sync.py | 53 + ...ated_security_center_list_sources_async.py | 53 + ...rated_security_center_list_sources_sync.py | 53 + ...rity_center_list_valued_resources_async.py | 53 + ...urity_center_list_valued_resources_sync.py | 53 + ...curity_center_run_asset_discovery_async.py | 56 + ...ecurity_center_run_asset_discovery_sync.py | 56 + ...security_center_set_finding_state_async.py | 53 + ..._security_center_set_finding_state_sync.py | 53 + ...ed_security_center_set_iam_policy_async.py | 53 + ...ted_security_center_set_iam_policy_sync.py | 53 + ...enerated_security_center_set_mute_async.py | 53 + ...generated_security_center_set_mute_sync.py | 53 + ...ty_health_analytics_custom_module_async.py | 56 + ...ity_health_analytics_custom_module_sync.py | 56 + ...urity_center_test_iam_permissions_async.py | 54 + ...curity_center_test_iam_permissions_sync.py | 54 + ...ty_center_update_big_query_export_async.py | 51 + ...ity_center_update_big_query_export_sync.py | 51 + ...nt_threat_detection_custom_module_async.py | 51 + ...ent_threat_detection_custom_module_sync.py | 51 + ...ity_center_update_external_system_async.py | 51 + ...rity_center_update_external_system_sync.py | 51 + ...ed_security_center_update_finding_async.py | 51 + ...ted_security_center_update_finding_sync.py | 51 + ...ecurity_center_update_mute_config_async.py | 55 + ...security_center_update_mute_config_sync.py | 55 + ...center_update_notification_config_async.py | 51 + ..._center_update_notification_config_sync.py | 51 + ...nter_update_organization_settings_async.py | 51 + ...enter_update_organization_settings_sync.py | 51 + ...nter_update_resource_value_config_async.py | 56 + ...enter_update_resource_value_config_sync.py | 56 + ...ty_health_analytics_custom_module_async.py | 51 + ...ity_health_analytics_custom_module_sync.py | 51 + ...rity_center_update_security_marks_async.py | 51 + ...urity_center_update_security_marks_sync.py | 51 + ...ted_security_center_update_source_async.py | 51 + ...ated_security_center_update_source_sync.py | 51 + ...nt_threat_detection_custom_module_async.py | 54 + ...ent_threat_detection_custom_module_sync.py | 54 + ...tadata_google.cloud.securitycenter.v1.json | 10298 ++++ .../fixup_securitycenter_v1_keywords.py | 238 + .../google-cloud-securitycenter/v1/setup.py | 94 + .../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/securitycenter_v1/__init__.py | 16 + .../securitycenter_v1/test_security_center.py | 48271 ++++++++++++++++ .../v1beta1/.coveragerc | 13 + .../v1beta1/.flake8 | 33 + .../v1beta1/MANIFEST.in | 2 + .../v1beta1/README.rst | 49 + .../v1beta1/docs/_static/custom.css | 3 + .../v1beta1/docs/conf.py | 376 + .../v1beta1/docs/index.rst | 7 + .../security_center.rst | 10 + .../docs/securitycenter_v1beta1/services_.rst | 6 + .../docs/securitycenter_v1beta1/types_.rst | 6 + .../google/cloud/securitycenter/__init__.py | 81 + .../cloud/securitycenter/gapic_version.py | 16 + .../google/cloud/securitycenter/py.typed | 2 + .../cloud/securitycenter_v1beta1/__init__.py | 82 + .../gapic_metadata.json | 298 + .../securitycenter_v1beta1/gapic_version.py | 16 + .../cloud/securitycenter_v1beta1/py.typed | 2 + .../services/__init__.py | 15 + .../services/security_center/__init__.py | 22 + .../services/security_center/async_client.py | 2364 + .../services/security_center/client.py | 2755 + .../services/security_center/pagers.py | 704 + .../security_center/transports/__init__.py | 38 + .../security_center/transports/base.py | 498 + .../security_center/transports/grpc.py | 760 + .../transports/grpc_asyncio.py | 945 + .../security_center/transports/rest.py | 2542 + .../securitycenter_v1beta1/types/__init__.py | 86 + .../securitycenter_v1beta1/types/asset.py | 155 + .../securitycenter_v1beta1/types/finding.py | 165 + .../types/organization_settings.py | 115 + .../types/run_asset_discovery_response.py | 76 + .../types/security_marks.py | 68 + .../types/securitycenter_service.py | 1053 + .../securitycenter_v1beta1/types/source.py | 77 + .../v1beta1/mypy.ini | 3 + .../v1beta1/noxfile.py | 280 + ...ed_security_center_create_finding_async.py | 53 + ...ted_security_center_create_finding_sync.py | 53 + ...ted_security_center_create_source_async.py | 52 + ...ated_security_center_create_source_sync.py | 52 + ...ed_security_center_get_iam_policy_async.py | 53 + ...ted_security_center_get_iam_policy_sync.py | 53 + ..._center_get_organization_settings_async.py | 52 + ...y_center_get_organization_settings_sync.py | 52 + ...erated_security_center_get_source_async.py | 52 + ...nerated_security_center_get_source_sync.py | 52 + ...ated_security_center_group_assets_async.py | 54 + ...rated_security_center_group_assets_sync.py | 54 + ...ed_security_center_group_findings_async.py | 54 + ...ted_security_center_group_findings_sync.py | 54 + ...rated_security_center_list_assets_async.py | 53 + ...erated_security_center_list_assets_sync.py | 53 + ...ted_security_center_list_findings_async.py | 53 + ...ated_security_center_list_findings_sync.py | 53 + ...ated_security_center_list_sources_async.py | 53 + ...rated_security_center_list_sources_sync.py | 53 + ...curity_center_run_asset_discovery_async.py | 56 + ...ecurity_center_run_asset_discovery_sync.py | 56 + ...security_center_set_finding_state_async.py | 53 + ..._security_center_set_finding_state_sync.py | 53 + ...ed_security_center_set_iam_policy_async.py | 53 + ...ted_security_center_set_iam_policy_sync.py | 53 + ...urity_center_test_iam_permissions_async.py | 54 + ...curity_center_test_iam_permissions_sync.py | 54 + ...ed_security_center_update_finding_async.py | 51 + ...ted_security_center_update_finding_sync.py | 51 + ...nter_update_organization_settings_async.py | 51 + ...enter_update_organization_settings_sync.py | 51 + ...rity_center_update_security_marks_async.py | 51 + ...urity_center_update_security_marks_sync.py | 51 + ...ted_security_center_update_source_async.py | 51 + ...ated_security_center_update_source_sync.py | 51 + ...a_google.cloud.securitycenter.v1beta1.json | 2945 + .../fixup_securitycenter_v1beta1_keywords.py | 193 + .../v1beta1/setup.py | 94 + .../v1beta1/testing/constraints-3.10.txt | 7 + .../v1beta1/testing/constraints-3.11.txt | 7 + .../v1beta1/testing/constraints-3.12.txt | 7 + .../v1beta1/testing/constraints-3.7.txt | 11 + .../v1beta1/testing/constraints-3.8.txt | 7 + .../v1beta1/testing/constraints-3.9.txt | 7 + .../v1beta1/tests/__init__.py | 16 + .../v1beta1/tests/unit/__init__.py | 16 + .../v1beta1/tests/unit/gapic/__init__.py | 16 + .../gapic/securitycenter_v1beta1/__init__.py | 16 + .../test_security_center.py | 14372 +++++ .../v1p1beta1/.coveragerc | 13 + .../v1p1beta1/.flake8 | 33 + .../v1p1beta1/MANIFEST.in | 2 + .../v1p1beta1/README.rst | 49 + .../v1p1beta1/docs/_static/custom.css | 3 + .../v1p1beta1/docs/conf.py | 376 + .../v1p1beta1/docs/index.rst | 7 + .../security_center.rst | 10 + .../securitycenter_v1p1beta1/services_.rst | 6 + .../docs/securitycenter_v1p1beta1/types_.rst | 6 + .../google/cloud/securitycenter/__init__.py | 101 + .../cloud/securitycenter/gapic_version.py | 16 + .../google/cloud/securitycenter/py.typed | 2 + .../securitycenter_v1p1beta1/__init__.py | 102 + .../gapic_metadata.json | 373 + .../securitycenter_v1p1beta1/gapic_version.py | 16 + .../cloud/securitycenter_v1p1beta1/py.typed | 2 + .../services/__init__.py | 15 + .../services/security_center/__init__.py | 22 + .../services/security_center/async_client.py | 3039 + .../services/security_center/client.py | 3441 ++ .../services/security_center/pagers.py | 839 + .../security_center/transports/__init__.py | 38 + .../security_center/transports/base.py | 591 + .../security_center/transports/grpc.py | 895 + .../transports/grpc_asyncio.py | 1125 + .../security_center/transports/rest.py | 3197 + .../types/__init__.py | 114 + .../securitycenter_v1p1beta1/types/asset.py | 227 + .../securitycenter_v1p1beta1/types/finding.py | 209 + .../securitycenter_v1p1beta1/types/folder.py | 54 + .../types/notification_config.py | 143 + .../types/notification_message.py | 69 + .../types/organization_settings.py | 123 + .../types/resource.py | 85 + .../types/run_asset_discovery_response.py | 76 + .../types/security_marks.py | 80 + .../types/securitycenter_service.py | 1641 + .../securitycenter_v1p1beta1/types/source.py | 88 + .../v1p1beta1/mypy.ini | 3 + .../v1p1beta1/noxfile.py | 280 + ...ed_security_center_create_finding_async.py | 53 + ...ted_security_center_create_finding_sync.py | 53 + ...center_create_notification_config_async.py | 53 + ..._center_create_notification_config_sync.py | 53 + ...ted_security_center_create_source_async.py | 52 + ...ated_security_center_create_source_sync.py | 52 + ...center_delete_notification_config_async.py | 50 + ..._center_delete_notification_config_sync.py | 50 + ...ed_security_center_get_iam_policy_async.py | 53 + ...ted_security_center_get_iam_policy_sync.py | 53 + ...ty_center_get_notification_config_async.py | 52 + ...ity_center_get_notification_config_sync.py | 52 + ..._center_get_organization_settings_async.py | 52 + ...y_center_get_organization_settings_sync.py | 52 + ...erated_security_center_get_source_async.py | 52 + ...nerated_security_center_get_source_sync.py | 52 + ...ated_security_center_group_assets_async.py | 54 + ...rated_security_center_group_assets_sync.py | 54 + ...ed_security_center_group_findings_async.py | 54 + ...ted_security_center_group_findings_sync.py | 54 + ...rated_security_center_list_assets_async.py | 53 + ...erated_security_center_list_assets_sync.py | 53 + ...ted_security_center_list_findings_async.py | 53 + ...ated_security_center_list_findings_sync.py | 53 + ..._center_list_notification_configs_async.py | 53 + ...y_center_list_notification_configs_sync.py | 53 + ...ated_security_center_list_sources_async.py | 53 + ...rated_security_center_list_sources_sync.py | 53 + ...curity_center_run_asset_discovery_async.py | 56 + ...ecurity_center_run_asset_discovery_sync.py | 56 + ...security_center_set_finding_state_async.py | 53 + ..._security_center_set_finding_state_sync.py | 53 + ...ed_security_center_set_iam_policy_async.py | 53 + ...ted_security_center_set_iam_policy_sync.py | 53 + ...urity_center_test_iam_permissions_async.py | 54 + ...curity_center_test_iam_permissions_sync.py | 54 + ...ed_security_center_update_finding_async.py | 51 + ...ted_security_center_update_finding_sync.py | 51 + ...center_update_notification_config_async.py | 51 + ..._center_update_notification_config_sync.py | 51 + ...nter_update_organization_settings_async.py | 51 + ...enter_update_organization_settings_sync.py | 51 + ...rity_center_update_security_marks_async.py | 51 + ...urity_center_update_security_marks_sync.py | 51 + ...ted_security_center_update_source_async.py | 51 + ...ated_security_center_update_source_sync.py | 51 + ...google.cloud.securitycenter.v1p1beta1.json | 3808 ++ ...fixup_securitycenter_v1p1beta1_keywords.py | 198 + .../v1p1beta1/setup.py | 94 + .../v1p1beta1/testing/constraints-3.10.txt | 7 + .../v1p1beta1/testing/constraints-3.11.txt | 7 + .../v1p1beta1/testing/constraints-3.12.txt | 7 + .../v1p1beta1/testing/constraints-3.7.txt | 11 + .../v1p1beta1/testing/constraints-3.8.txt | 7 + .../v1p1beta1/testing/constraints-3.9.txt | 7 + .../v1p1beta1/tests/__init__.py | 16 + .../v1p1beta1/tests/unit/__init__.py | 16 + .../v1p1beta1/tests/unit/gapic/__init__.py | 16 + .../securitycenter_v1p1beta1/__init__.py | 16 + .../test_security_center.py | 18405 ++++++ .../v2/.coveragerc | 13 + .../google-cloud-securitycenter/v2/.flake8 | 33 + .../v2/MANIFEST.in | 2 + .../google-cloud-securitycenter/v2/README.rst | 49 + .../v2/docs/_static/custom.css | 3 + .../v2/docs/conf.py | 376 + .../v2/docs/index.rst | 7 + .../securitycenter_v2/security_center.rst | 10 + .../v2/docs/securitycenter_v2/services_.rst | 6 + .../v2/docs/securitycenter_v2/types_.rst | 6 + .../google/cloud/securitycenter/__init__.py | 257 + .../cloud/securitycenter/gapic_version.py | 16 + .../v2/google/cloud/securitycenter/py.typed | 2 + .../cloud/securitycenter_v2/__init__.py | 258 + .../securitycenter_v2/gapic_metadata.json | 628 + .../cloud/securitycenter_v2/gapic_version.py | 16 + .../google/cloud/securitycenter_v2/py.typed | 2 + .../securitycenter_v2/services/__init__.py | 15 + .../services/security_center/__init__.py | 22 + .../services/security_center/async_client.py | 5422 ++ .../services/security_center/client.py | 5948 ++ .../services/security_center/pagers.py | 1249 + .../security_center/transports/__init__.py | 38 + .../security_center/transports/base.py | 761 + .../security_center/transports/grpc.py | 1452 + .../transports/grpc_asyncio.py | 1657 + .../security_center/transports/rest.py | 5820 ++ .../cloud/securitycenter_v2/types/__init__.py | 336 + .../cloud/securitycenter_v2/types/access.py | 193 + .../securitycenter_v2/types/application.py | 55 + .../types/attack_exposure.py | 113 + .../securitycenter_v2/types/attack_path.py | 223 + .../types/backup_disaster_recovery.py | 137 + .../types/bigquery_export.py | 141 + .../securitycenter_v2/types/cloud_armor.py | 217 + .../types/cloud_dlp_data_profile.py | 71 + .../types/cloud_dlp_inspection.py | 70 + .../securitycenter_v2/types/compliance.py | 61 + .../securitycenter_v2/types/connection.py | 97 + .../types/contact_details.py | 61 + .../securitycenter_v2/types/container.py | 80 + .../cloud/securitycenter_v2/types/database.py | 98 + .../securitycenter_v2/types/exfiltration.py | 96 + .../types/external_system.py | 192 + .../cloud/securitycenter_v2/types/file.py | 113 + .../cloud/securitycenter_v2/types/finding.py | 808 + .../cloud/securitycenter_v2/types/folder.py | 54 + .../types/group_membership.py | 65 + .../securitycenter_v2/types/iam_binding.py | 77 + .../securitycenter_v2/types/indicator.py | 186 + .../securitycenter_v2/types/kernel_rootkit.py | 107 + .../securitycenter_v2/types/kubernetes.py | 398 + .../cloud/securitycenter_v2/types/label.py | 54 + .../securitycenter_v2/types/load_balancer.py | 47 + .../securitycenter_v2/types/log_entry.py | 95 + .../securitycenter_v2/types/mitre_attack.py | 340 + .../securitycenter_v2/types/mute_config.py | 166 + .../cloud/securitycenter_v2/types/notebook.py | 72 + .../types/notification_config.py | 129 + .../types/notification_message.py | 70 + .../securitycenter_v2/types/org_policy.py | 47 + .../cloud/securitycenter_v2/types/process.py | 136 + .../cloud/securitycenter_v2/types/resource.py | 493 + .../types/resource_value_config.py | 190 + .../securitycenter_v2/types/security_marks.py | 101 + .../types/security_posture.py | 128 + .../types/securitycenter_service.py | 1932 + .../securitycenter_v2/types/simulation.py | 73 + .../cloud/securitycenter_v2/types/source.py | 88 + .../types/toxic_combination.py | 60 + .../types/valued_resource.py | 126 + .../securitycenter_v2/types/vulnerability.py | 546 + .../google-cloud-securitycenter/v2/mypy.ini | 3 + .../google-cloud-securitycenter/v2/noxfile.py | 280 + ...tch_create_resource_value_configs_async.py | 56 + ...atch_create_resource_value_configs_sync.py | 56 + ...ecurity_center_bulk_mute_findings_async.py | 56 + ...security_center_bulk_mute_findings_sync.py | 56 + ...ty_center_create_big_query_export_async.py | 53 + ...ity_center_create_big_query_export_sync.py | 53 + ...ed_security_center_create_finding_async.py | 53 + ...ted_security_center_create_finding_sync.py | 53 + ...ecurity_center_create_mute_config_async.py | 58 + ...security_center_create_mute_config_sync.py | 58 + ...center_create_notification_config_async.py | 53 + ..._center_create_notification_config_sync.py | 53 + ...ted_security_center_create_source_async.py | 52 + ...ated_security_center_create_source_sync.py | 52 + ...ty_center_delete_big_query_export_async.py | 50 + ...ity_center_delete_big_query_export_sync.py | 50 + ...ecurity_center_delete_mute_config_async.py | 50 + ...security_center_delete_mute_config_sync.py | 50 + ...center_delete_notification_config_async.py | 50 + ..._center_delete_notification_config_sync.py | 50 + ...nter_delete_resource_value_config_async.py | 50 + ...enter_delete_resource_value_config_sync.py | 50 + ...urity_center_get_big_query_export_async.py | 52 + ...curity_center_get_big_query_export_sync.py | 52 + ...ed_security_center_get_iam_policy_async.py | 53 + ...ted_security_center_get_iam_policy_sync.py | 53 + ...d_security_center_get_mute_config_async.py | 52 + ...ed_security_center_get_mute_config_sync.py | 52 + ...ty_center_get_notification_config_async.py | 52 + ...ity_center_get_notification_config_sync.py | 52 + ..._center_get_resource_value_config_async.py | 52 + ...y_center_get_resource_value_config_sync.py | 52 + ...ed_security_center_get_simulation_async.py | 52 + ...ted_security_center_get_simulation_sync.py | 52 + ...erated_security_center_get_source_async.py | 52 + ...nerated_security_center_get_source_sync.py | 52 + ...curity_center_get_valued_resource_async.py | 52 + ...ecurity_center_get_valued_resource_sync.py | 52 + ...ed_security_center_group_findings_async.py | 54 + ...ted_security_center_group_findings_sync.py | 54 + ...security_center_list_attack_paths_async.py | 53 + ..._security_center_list_attack_paths_sync.py | 53 + ...ity_center_list_big_query_exports_async.py | 53 + ...rity_center_list_big_query_exports_sync.py | 53 + ...ted_security_center_list_findings_async.py | 53 + ...ated_security_center_list_findings_sync.py | 53 + ...security_center_list_mute_configs_async.py | 53 + ..._security_center_list_mute_configs_sync.py | 53 + ..._center_list_notification_configs_async.py | 53 + ...y_center_list_notification_configs_sync.py | 53 + ...enter_list_resource_value_configs_async.py | 53 + ...center_list_resource_value_configs_sync.py | 53 + ...ated_security_center_list_sources_async.py | 53 + ...rated_security_center_list_sources_sync.py | 53 + ...rity_center_list_valued_resources_async.py | 53 + ...urity_center_list_valued_resources_sync.py | 53 + ...security_center_set_finding_state_async.py | 53 + ..._security_center_set_finding_state_sync.py | 53 + ...ed_security_center_set_iam_policy_async.py | 53 + ...ted_security_center_set_iam_policy_sync.py | 53 + ...enerated_security_center_set_mute_async.py | 53 + ...generated_security_center_set_mute_sync.py | 53 + ...urity_center_test_iam_permissions_async.py | 54 + ...curity_center_test_iam_permissions_sync.py | 54 + ...ty_center_update_big_query_export_async.py | 51 + ...ity_center_update_big_query_export_sync.py | 51 + ...ity_center_update_external_system_async.py | 51 + ...rity_center_update_external_system_sync.py | 51 + ...ed_security_center_update_finding_async.py | 51 + ...ted_security_center_update_finding_sync.py | 51 + ...ecurity_center_update_mute_config_async.py | 56 + ...security_center_update_mute_config_sync.py | 56 + ...center_update_notification_config_async.py | 51 + ..._center_update_notification_config_sync.py | 51 + ...nter_update_resource_value_config_async.py | 51 + ...enter_update_resource_value_config_sync.py | 51 + ...rity_center_update_security_marks_async.py | 51 + ...urity_center_update_security_marks_sync.py | 51 + ...ted_security_center_update_source_async.py | 51 + ...ated_security_center_update_source_sync.py | 51 + ...tadata_google.cloud.securitycenter.v2.json | 6607 +++ .../fixup_securitycenter_v2_keywords.py | 215 + .../google-cloud-securitycenter/v2/setup.py | 94 + .../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 + .../v2/tests/__init__.py | 16 + .../v2/tests/unit/__init__.py | 16 + .../v2/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/securitycenter_v2/__init__.py | 16 + .../securitycenter_v2/test_security_center.py | 31716 ++++++++++ 579 files changed, 265294 insertions(+) create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/.flake8 create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/setup.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.flake8 create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/setup.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/.coveragerc create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/.flake8 create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/README.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/noxfile.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/setup.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/__init__.py create mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc new file mode 100644 index 000000000000..45cb273f8f7c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/securitycenter/__init__.py + google/cloud/securitycenter/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-securitycenter/v1/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v1/MANIFEST.in new file mode 100644 index 000000000000..a18e3d0b6821 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/securitycenter *.py +recursive-include google/cloud/securitycenter_v1 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/README.rst b/owl-bot-staging/google-cloud-securitycenter/v1/README.rst new file mode 100644 index 000000000000..f8c63f4cb48a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v1/docs/conf.py new file mode 100644 index 000000000000..8e92d2319721 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter 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-securitycenter" +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-securitycenter-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-securitycenter.tex", + u"google-cloud-securitycenter 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-securitycenter", + u"Google Cloud Securitycenter 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-securitycenter", + u"google-cloud-securitycenter Documentation", + author, + "google-cloud-securitycenter", + "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v1/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/index.rst new file mode 100644 index 000000000000..47fc2db7cc98 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + securitycenter_v1/services + securitycenter_v1/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst new file mode 100644 index 000000000000..bc6175c8b5cc --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst @@ -0,0 +1,10 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v1.services.security_center + :members: + :inherited-members: + +.. automodule:: google.cloud.securitycenter_v1.services.security_center.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst new file mode 100644 index 000000000000..295acede4385 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v1 API +=============================================== +.. toctree:: + :maxdepth: 2 + + security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst new file mode 100644 index 000000000000..f7497757d041 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Securitycenter v1 API +============================================ + +.. automodule:: google.cloud.securitycenter_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.py new file mode 100644 index 000000000000..7c15b78219eb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.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. +# +from google.cloud.securitycenter import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.securitycenter_v1.services.security_center.client import SecurityCenterClient +from google.cloud.securitycenter_v1.services.security_center.async_client import SecurityCenterAsyncClient + +from google.cloud.securitycenter_v1.types.access import Access +from google.cloud.securitycenter_v1.types.access import Geolocation +from google.cloud.securitycenter_v1.types.access import ServiceAccountDelegationInfo +from google.cloud.securitycenter_v1.types.application import Application +from google.cloud.securitycenter_v1.types.asset import Asset +from google.cloud.securitycenter_v1.types.attack_exposure import AttackExposure +from google.cloud.securitycenter_v1.types.attack_path import AttackPath +from google.cloud.securitycenter_v1.types.backup_disaster_recovery import BackupDisasterRecovery +from google.cloud.securitycenter_v1.types.bigquery_export import BigQueryExport +from google.cloud.securitycenter_v1.types.cloud_armor import AdaptiveProtection +from google.cloud.securitycenter_v1.types.cloud_armor import Attack +from google.cloud.securitycenter_v1.types.cloud_armor import CloudArmor +from google.cloud.securitycenter_v1.types.cloud_armor import Requests +from google.cloud.securitycenter_v1.types.cloud_armor import SecurityPolicy +from google.cloud.securitycenter_v1.types.cloud_dlp_data_profile import CloudDlpDataProfile +from google.cloud.securitycenter_v1.types.cloud_dlp_inspection import CloudDlpInspection +from google.cloud.securitycenter_v1.types.compliance import Compliance +from google.cloud.securitycenter_v1.types.connection import Connection +from google.cloud.securitycenter_v1.types.contact_details import Contact +from google.cloud.securitycenter_v1.types.contact_details import ContactDetails +from google.cloud.securitycenter_v1.types.container import Container +from google.cloud.securitycenter_v1.types.database import Database +from google.cloud.securitycenter_v1.types.effective_event_threat_detection_custom_module import EffectiveEventThreatDetectionCustomModule +from google.cloud.securitycenter_v1.types.effective_security_health_analytics_custom_module import EffectiveSecurityHealthAnalyticsCustomModule +from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module import EventThreatDetectionCustomModule +from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationError +from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationErrors +from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module_validation_errors import Position +from google.cloud.securitycenter_v1.types.exfiltration import ExfilResource +from google.cloud.securitycenter_v1.types.exfiltration import Exfiltration +from google.cloud.securitycenter_v1.types.external_system import ExternalSystem +from google.cloud.securitycenter_v1.types.file import File +from google.cloud.securitycenter_v1.types.finding import Finding +from google.cloud.securitycenter_v1.types.folder import Folder +from google.cloud.securitycenter_v1.types.group_membership import GroupMembership +from google.cloud.securitycenter_v1.types.iam_binding import IamBinding +from google.cloud.securitycenter_v1.types.indicator import Indicator +from google.cloud.securitycenter_v1.types.kernel_rootkit import KernelRootkit +from google.cloud.securitycenter_v1.types.kubernetes import Kubernetes +from google.cloud.securitycenter_v1.types.label import Label +from google.cloud.securitycenter_v1.types.load_balancer import LoadBalancer +from google.cloud.securitycenter_v1.types.log_entry import CloudLoggingEntry +from google.cloud.securitycenter_v1.types.log_entry import LogEntry +from google.cloud.securitycenter_v1.types.mitre_attack import MitreAttack +from google.cloud.securitycenter_v1.types.mute_config import MuteConfig +from google.cloud.securitycenter_v1.types.notebook import Notebook +from google.cloud.securitycenter_v1.types.notification_config import NotificationConfig +from google.cloud.securitycenter_v1.types.notification_message import NotificationMessage +from google.cloud.securitycenter_v1.types.org_policy import OrgPolicy +from google.cloud.securitycenter_v1.types.organization_settings import OrganizationSettings +from google.cloud.securitycenter_v1.types.process import EnvironmentVariable +from google.cloud.securitycenter_v1.types.process import Process +from google.cloud.securitycenter_v1.types.resource import AwsMetadata +from google.cloud.securitycenter_v1.types.resource import AzureMetadata +from google.cloud.securitycenter_v1.types.resource import Resource +from google.cloud.securitycenter_v1.types.resource import ResourcePath +from google.cloud.securitycenter_v1.types.resource import CloudProvider +from google.cloud.securitycenter_v1.types.resource_value_config import ResourceValueConfig +from google.cloud.securitycenter_v1.types.resource_value_config import ResourceValue +from google.cloud.securitycenter_v1.types.run_asset_discovery_response import RunAssetDiscoveryResponse +from google.cloud.securitycenter_v1.types.security_health_analytics_custom_config import CustomConfig +from google.cloud.securitycenter_v1.types.security_health_analytics_custom_module import SecurityHealthAnalyticsCustomModule +from google.cloud.securitycenter_v1.types.security_marks import SecurityMarks +from google.cloud.securitycenter_v1.types.security_posture import SecurityPosture +from google.cloud.securitycenter_v1.types.securitycenter_service import BatchCreateResourceValueConfigsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import BatchCreateResourceValueConfigsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import BulkMuteFindingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import BulkMuteFindingsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateBigQueryExportRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateEventThreatDetectionCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateFindingRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateMuteConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateNotificationConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateResourceValueConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateSecurityHealthAnalyticsCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateSourceRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteBigQueryExportRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteEventThreatDetectionCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteMuteConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteNotificationConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteResourceValueConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteSecurityHealthAnalyticsCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetBigQueryExportRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetEffectiveEventThreatDetectionCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetEffectiveSecurityHealthAnalyticsCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetEventThreatDetectionCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetMuteConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetNotificationConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetOrganizationSettingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetResourceValueConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetSecurityHealthAnalyticsCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetSimulationRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetSourceRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetValuedResourceRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupAssetsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupAssetsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupFindingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupFindingsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupResult +from google.cloud.securitycenter_v1.types.securitycenter_service import ListAssetsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListAssetsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListAttackPathsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListAttackPathsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListBigQueryExportsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListBigQueryExportsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListEventThreatDetectionCustomModulesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListEventThreatDetectionCustomModulesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListFindingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListFindingsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListMuteConfigsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListMuteConfigsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListNotificationConfigsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListNotificationConfigsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListResourceValueConfigsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListResourceValueConfigsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListSourcesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListSourcesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListValuedResourcesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListValuedResourcesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import RunAssetDiscoveryRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import SetFindingStateRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import SetMuteRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateBigQueryExportRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateEventThreatDetectionCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateExternalSystemRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateFindingRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateMuteConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateNotificationConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateOrganizationSettingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateResourceValueConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSecurityHealthAnalyticsCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSecurityMarksRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSourceRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ValidateEventThreatDetectionCustomModuleRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ValidateEventThreatDetectionCustomModuleResponse +from google.cloud.securitycenter_v1.types.simulation import Simulation +from google.cloud.securitycenter_v1.types.source import Source +from google.cloud.securitycenter_v1.types.toxic_combination import ToxicCombination +from google.cloud.securitycenter_v1.types.valued_resource import ResourceValueConfigMetadata +from google.cloud.securitycenter_v1.types.valued_resource import ValuedResource +from google.cloud.securitycenter_v1.types.vulnerability import Cve +from google.cloud.securitycenter_v1.types.vulnerability import Cvssv3 +from google.cloud.securitycenter_v1.types.vulnerability import Package +from google.cloud.securitycenter_v1.types.vulnerability import Reference +from google.cloud.securitycenter_v1.types.vulnerability import SecurityBulletin +from google.cloud.securitycenter_v1.types.vulnerability import Vulnerability + +__all__ = ('SecurityCenterClient', + 'SecurityCenterAsyncClient', + 'Access', + 'Geolocation', + 'ServiceAccountDelegationInfo', + 'Application', + 'Asset', + 'AttackExposure', + 'AttackPath', + 'BackupDisasterRecovery', + 'BigQueryExport', + 'AdaptiveProtection', + 'Attack', + 'CloudArmor', + 'Requests', + 'SecurityPolicy', + 'CloudDlpDataProfile', + 'CloudDlpInspection', + 'Compliance', + 'Connection', + 'Contact', + 'ContactDetails', + 'Container', + 'Database', + 'EffectiveEventThreatDetectionCustomModule', + 'EffectiveSecurityHealthAnalyticsCustomModule', + 'EventThreatDetectionCustomModule', + 'CustomModuleValidationError', + 'CustomModuleValidationErrors', + 'Position', + 'ExfilResource', + 'Exfiltration', + 'ExternalSystem', + 'File', + 'Finding', + 'Folder', + 'GroupMembership', + 'IamBinding', + 'Indicator', + 'KernelRootkit', + 'Kubernetes', + 'Label', + 'LoadBalancer', + 'CloudLoggingEntry', + 'LogEntry', + 'MitreAttack', + 'MuteConfig', + 'Notebook', + 'NotificationConfig', + 'NotificationMessage', + 'OrgPolicy', + 'OrganizationSettings', + 'EnvironmentVariable', + 'Process', + 'AwsMetadata', + 'AzureMetadata', + 'Resource', + 'ResourcePath', + 'CloudProvider', + 'ResourceValueConfig', + 'ResourceValue', + 'RunAssetDiscoveryResponse', + 'CustomConfig', + 'SecurityHealthAnalyticsCustomModule', + 'SecurityMarks', + 'SecurityPosture', + 'BatchCreateResourceValueConfigsRequest', + 'BatchCreateResourceValueConfigsResponse', + 'BulkMuteFindingsRequest', + 'BulkMuteFindingsResponse', + 'CreateBigQueryExportRequest', + 'CreateEventThreatDetectionCustomModuleRequest', + 'CreateFindingRequest', + 'CreateMuteConfigRequest', + 'CreateNotificationConfigRequest', + 'CreateResourceValueConfigRequest', + 'CreateSecurityHealthAnalyticsCustomModuleRequest', + 'CreateSourceRequest', + 'DeleteBigQueryExportRequest', + 'DeleteEventThreatDetectionCustomModuleRequest', + 'DeleteMuteConfigRequest', + 'DeleteNotificationConfigRequest', + 'DeleteResourceValueConfigRequest', + 'DeleteSecurityHealthAnalyticsCustomModuleRequest', + 'GetBigQueryExportRequest', + 'GetEffectiveEventThreatDetectionCustomModuleRequest', + 'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', + 'GetEventThreatDetectionCustomModuleRequest', + 'GetMuteConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetResourceValueConfigRequest', + 'GetSecurityHealthAnalyticsCustomModuleRequest', + 'GetSimulationRequest', + 'GetSourceRequest', + 'GetValuedResourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListAttackPathsRequest', + 'ListAttackPathsResponse', + 'ListBigQueryExportsRequest', + 'ListBigQueryExportsResponse', + 'ListDescendantEventThreatDetectionCustomModulesRequest', + 'ListDescendantEventThreatDetectionCustomModulesResponse', + 'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', + 'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', + 'ListEffectiveEventThreatDetectionCustomModulesRequest', + 'ListEffectiveEventThreatDetectionCustomModulesResponse', + 'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', + 'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', + 'ListEventThreatDetectionCustomModulesRequest', + 'ListEventThreatDetectionCustomModulesResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListMuteConfigsRequest', + 'ListMuteConfigsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListResourceValueConfigsRequest', + 'ListResourceValueConfigsResponse', + 'ListSecurityHealthAnalyticsCustomModulesRequest', + 'ListSecurityHealthAnalyticsCustomModulesResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListValuedResourcesRequest', + 'ListValuedResourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'SetMuteRequest', + 'SimulateSecurityHealthAnalyticsCustomModuleRequest', + 'SimulateSecurityHealthAnalyticsCustomModuleResponse', + 'UpdateBigQueryExportRequest', + 'UpdateEventThreatDetectionCustomModuleRequest', + 'UpdateExternalSystemRequest', + 'UpdateFindingRequest', + 'UpdateMuteConfigRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateResourceValueConfigRequest', + 'UpdateSecurityHealthAnalyticsCustomModuleRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'ValidateEventThreatDetectionCustomModuleRequest', + 'ValidateEventThreatDetectionCustomModuleResponse', + 'Simulation', + 'Source', + 'ToxicCombination', + 'ResourceValueConfigMetadata', + 'ValuedResource', + 'Cve', + 'Cvssv3', + 'Package', + 'Reference', + 'SecurityBulletin', + 'Vulnerability', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/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-securitycenter/v1/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.py new file mode 100644 index 000000000000..ac4fb60e1479 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.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. +# +from google.cloud.securitycenter_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + +from .types.access import Access +from .types.access import Geolocation +from .types.access import ServiceAccountDelegationInfo +from .types.application import Application +from .types.asset import Asset +from .types.attack_exposure import AttackExposure +from .types.attack_path import AttackPath +from .types.backup_disaster_recovery import BackupDisasterRecovery +from .types.bigquery_export import BigQueryExport +from .types.cloud_armor import AdaptiveProtection +from .types.cloud_armor import Attack +from .types.cloud_armor import CloudArmor +from .types.cloud_armor import Requests +from .types.cloud_armor import SecurityPolicy +from .types.cloud_dlp_data_profile import CloudDlpDataProfile +from .types.cloud_dlp_inspection import CloudDlpInspection +from .types.compliance import Compliance +from .types.connection import Connection +from .types.contact_details import Contact +from .types.contact_details import ContactDetails +from .types.container import Container +from .types.database import Database +from .types.effective_event_threat_detection_custom_module import EffectiveEventThreatDetectionCustomModule +from .types.effective_security_health_analytics_custom_module import EffectiveSecurityHealthAnalyticsCustomModule +from .types.event_threat_detection_custom_module import EventThreatDetectionCustomModule +from .types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationError +from .types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationErrors +from .types.event_threat_detection_custom_module_validation_errors import Position +from .types.exfiltration import ExfilResource +from .types.exfiltration import Exfiltration +from .types.external_system import ExternalSystem +from .types.file import File +from .types.finding import Finding +from .types.folder import Folder +from .types.group_membership import GroupMembership +from .types.iam_binding import IamBinding +from .types.indicator import Indicator +from .types.kernel_rootkit import KernelRootkit +from .types.kubernetes import Kubernetes +from .types.label import Label +from .types.load_balancer import LoadBalancer +from .types.log_entry import CloudLoggingEntry +from .types.log_entry import LogEntry +from .types.mitre_attack import MitreAttack +from .types.mute_config import MuteConfig +from .types.notebook import Notebook +from .types.notification_config import NotificationConfig +from .types.notification_message import NotificationMessage +from .types.org_policy import OrgPolicy +from .types.organization_settings import OrganizationSettings +from .types.process import EnvironmentVariable +from .types.process import Process +from .types.resource import AwsMetadata +from .types.resource import AzureMetadata +from .types.resource import Resource +from .types.resource import ResourcePath +from .types.resource import CloudProvider +from .types.resource_value_config import ResourceValueConfig +from .types.resource_value_config import ResourceValue +from .types.run_asset_discovery_response import RunAssetDiscoveryResponse +from .types.security_health_analytics_custom_config import CustomConfig +from .types.security_health_analytics_custom_module import SecurityHealthAnalyticsCustomModule +from .types.security_marks import SecurityMarks +from .types.security_posture import SecurityPosture +from .types.securitycenter_service import BatchCreateResourceValueConfigsRequest +from .types.securitycenter_service import BatchCreateResourceValueConfigsResponse +from .types.securitycenter_service import BulkMuteFindingsRequest +from .types.securitycenter_service import BulkMuteFindingsResponse +from .types.securitycenter_service import CreateBigQueryExportRequest +from .types.securitycenter_service import CreateEventThreatDetectionCustomModuleRequest +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateMuteConfigRequest +from .types.securitycenter_service import CreateNotificationConfigRequest +from .types.securitycenter_service import CreateResourceValueConfigRequest +from .types.securitycenter_service import CreateSecurityHealthAnalyticsCustomModuleRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import DeleteBigQueryExportRequest +from .types.securitycenter_service import DeleteEventThreatDetectionCustomModuleRequest +from .types.securitycenter_service import DeleteMuteConfigRequest +from .types.securitycenter_service import DeleteNotificationConfigRequest +from .types.securitycenter_service import DeleteResourceValueConfigRequest +from .types.securitycenter_service import DeleteSecurityHealthAnalyticsCustomModuleRequest +from .types.securitycenter_service import GetBigQueryExportRequest +from .types.securitycenter_service import GetEffectiveEventThreatDetectionCustomModuleRequest +from .types.securitycenter_service import GetEffectiveSecurityHealthAnalyticsCustomModuleRequest +from .types.securitycenter_service import GetEventThreatDetectionCustomModuleRequest +from .types.securitycenter_service import GetMuteConfigRequest +from .types.securitycenter_service import GetNotificationConfigRequest +from .types.securitycenter_service import GetOrganizationSettingsRequest +from .types.securitycenter_service import GetResourceValueConfigRequest +from .types.securitycenter_service import GetSecurityHealthAnalyticsCustomModuleRequest +from .types.securitycenter_service import GetSimulationRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GetValuedResourceRequest +from .types.securitycenter_service import GroupAssetsRequest +from .types.securitycenter_service import GroupAssetsResponse +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAssetsRequest +from .types.securitycenter_service import ListAssetsResponse +from .types.securitycenter_service import ListAttackPathsRequest +from .types.securitycenter_service import ListAttackPathsResponse +from .types.securitycenter_service import ListBigQueryExportsRequest +from .types.securitycenter_service import ListBigQueryExportsResponse +from .types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesRequest +from .types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesResponse +from .types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesRequest +from .types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesResponse +from .types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesRequest +from .types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesResponse +from .types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesRequest +from .types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesResponse +from .types.securitycenter_service import ListEventThreatDetectionCustomModulesRequest +from .types.securitycenter_service import ListEventThreatDetectionCustomModulesResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListMuteConfigsRequest +from .types.securitycenter_service import ListMuteConfigsResponse +from .types.securitycenter_service import ListNotificationConfigsRequest +from .types.securitycenter_service import ListNotificationConfigsResponse +from .types.securitycenter_service import ListResourceValueConfigsRequest +from .types.securitycenter_service import ListResourceValueConfigsResponse +from .types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesRequest +from .types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import ListValuedResourcesRequest +from .types.securitycenter_service import ListValuedResourcesResponse +from .types.securitycenter_service import RunAssetDiscoveryRequest +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import SetMuteRequest +from .types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleRequest +from .types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleResponse +from .types.securitycenter_service import UpdateBigQueryExportRequest +from .types.securitycenter_service import UpdateEventThreatDetectionCustomModuleRequest +from .types.securitycenter_service import UpdateExternalSystemRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateMuteConfigRequest +from .types.securitycenter_service import UpdateNotificationConfigRequest +from .types.securitycenter_service import UpdateOrganizationSettingsRequest +from .types.securitycenter_service import UpdateResourceValueConfigRequest +from .types.securitycenter_service import UpdateSecurityHealthAnalyticsCustomModuleRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.securitycenter_service import ValidateEventThreatDetectionCustomModuleRequest +from .types.securitycenter_service import ValidateEventThreatDetectionCustomModuleResponse +from .types.simulation import Simulation +from .types.source import Source +from .types.toxic_combination import ToxicCombination +from .types.valued_resource import ResourceValueConfigMetadata +from .types.valued_resource import ValuedResource +from .types.vulnerability import Cve +from .types.vulnerability import Cvssv3 +from .types.vulnerability import Package +from .types.vulnerability import Reference +from .types.vulnerability import SecurityBulletin +from .types.vulnerability import Vulnerability + +__all__ = ( + 'SecurityCenterAsyncClient', +'Access', +'AdaptiveProtection', +'Application', +'Asset', +'Attack', +'AttackExposure', +'AttackPath', +'AwsMetadata', +'AzureMetadata', +'BackupDisasterRecovery', +'BatchCreateResourceValueConfigsRequest', +'BatchCreateResourceValueConfigsResponse', +'BigQueryExport', +'BulkMuteFindingsRequest', +'BulkMuteFindingsResponse', +'CloudArmor', +'CloudDlpDataProfile', +'CloudDlpInspection', +'CloudLoggingEntry', +'CloudProvider', +'Compliance', +'Connection', +'Contact', +'ContactDetails', +'Container', +'CreateBigQueryExportRequest', +'CreateEventThreatDetectionCustomModuleRequest', +'CreateFindingRequest', +'CreateMuteConfigRequest', +'CreateNotificationConfigRequest', +'CreateResourceValueConfigRequest', +'CreateSecurityHealthAnalyticsCustomModuleRequest', +'CreateSourceRequest', +'CustomConfig', +'CustomModuleValidationError', +'CustomModuleValidationErrors', +'Cve', +'Cvssv3', +'Database', +'DeleteBigQueryExportRequest', +'DeleteEventThreatDetectionCustomModuleRequest', +'DeleteMuteConfigRequest', +'DeleteNotificationConfigRequest', +'DeleteResourceValueConfigRequest', +'DeleteSecurityHealthAnalyticsCustomModuleRequest', +'EffectiveEventThreatDetectionCustomModule', +'EffectiveSecurityHealthAnalyticsCustomModule', +'EnvironmentVariable', +'EventThreatDetectionCustomModule', +'ExfilResource', +'Exfiltration', +'ExternalSystem', +'File', +'Finding', +'Folder', +'Geolocation', +'GetBigQueryExportRequest', +'GetEffectiveEventThreatDetectionCustomModuleRequest', +'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', +'GetEventThreatDetectionCustomModuleRequest', +'GetMuteConfigRequest', +'GetNotificationConfigRequest', +'GetOrganizationSettingsRequest', +'GetResourceValueConfigRequest', +'GetSecurityHealthAnalyticsCustomModuleRequest', +'GetSimulationRequest', +'GetSourceRequest', +'GetValuedResourceRequest', +'GroupAssetsRequest', +'GroupAssetsResponse', +'GroupFindingsRequest', +'GroupFindingsResponse', +'GroupMembership', +'GroupResult', +'IamBinding', +'Indicator', +'KernelRootkit', +'Kubernetes', +'Label', +'ListAssetsRequest', +'ListAssetsResponse', +'ListAttackPathsRequest', +'ListAttackPathsResponse', +'ListBigQueryExportsRequest', +'ListBigQueryExportsResponse', +'ListDescendantEventThreatDetectionCustomModulesRequest', +'ListDescendantEventThreatDetectionCustomModulesResponse', +'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', +'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', +'ListEffectiveEventThreatDetectionCustomModulesRequest', +'ListEffectiveEventThreatDetectionCustomModulesResponse', +'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', +'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', +'ListEventThreatDetectionCustomModulesRequest', +'ListEventThreatDetectionCustomModulesResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListMuteConfigsRequest', +'ListMuteConfigsResponse', +'ListNotificationConfigsRequest', +'ListNotificationConfigsResponse', +'ListResourceValueConfigsRequest', +'ListResourceValueConfigsResponse', +'ListSecurityHealthAnalyticsCustomModulesRequest', +'ListSecurityHealthAnalyticsCustomModulesResponse', +'ListSourcesRequest', +'ListSourcesResponse', +'ListValuedResourcesRequest', +'ListValuedResourcesResponse', +'LoadBalancer', +'LogEntry', +'MitreAttack', +'MuteConfig', +'Notebook', +'NotificationConfig', +'NotificationMessage', +'OrgPolicy', +'OrganizationSettings', +'Package', +'Position', +'Process', +'Reference', +'Requests', +'Resource', +'ResourcePath', +'ResourceValue', +'ResourceValueConfig', +'ResourceValueConfigMetadata', +'RunAssetDiscoveryRequest', +'RunAssetDiscoveryResponse', +'SecurityBulletin', +'SecurityCenterClient', +'SecurityHealthAnalyticsCustomModule', +'SecurityMarks', +'SecurityPolicy', +'SecurityPosture', +'ServiceAccountDelegationInfo', +'SetFindingStateRequest', +'SetMuteRequest', +'SimulateSecurityHealthAnalyticsCustomModuleRequest', +'SimulateSecurityHealthAnalyticsCustomModuleResponse', +'Simulation', +'Source', +'ToxicCombination', +'UpdateBigQueryExportRequest', +'UpdateEventThreatDetectionCustomModuleRequest', +'UpdateExternalSystemRequest', +'UpdateFindingRequest', +'UpdateMuteConfigRequest', +'UpdateNotificationConfigRequest', +'UpdateOrganizationSettingsRequest', +'UpdateResourceValueConfigRequest', +'UpdateSecurityHealthAnalyticsCustomModuleRequest', +'UpdateSecurityMarksRequest', +'UpdateSourceRequest', +'ValidateEventThreatDetectionCustomModuleRequest', +'ValidateEventThreatDetectionCustomModuleResponse', +'ValuedResource', +'Vulnerability', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json new file mode 100644 index 000000000000..3bca8f8a0f67 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json @@ -0,0 +1,973 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v1", + "protoPackage": "google.cloud.securitycenter.v1", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateEventThreatDetectionCustomModule": { + "methods": [ + "create_event_threat_detection_custom_module" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "create_security_health_analytics_custom_module" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteEventThreatDetectionCustomModule": { + "methods": [ + "delete_event_threat_detection_custom_module" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "DeleteSecurityHealthAnalyticsCustomModule": { + "methods": [ + "delete_security_health_analytics_custom_module" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetEffectiveEventThreatDetectionCustomModule": { + "methods": [ + "get_effective_event_threat_detection_custom_module" + ] + }, + "GetEffectiveSecurityHealthAnalyticsCustomModule": { + "methods": [ + "get_effective_security_health_analytics_custom_module" + ] + }, + "GetEventThreatDetectionCustomModule": { + "methods": [ + "get_event_threat_detection_custom_module" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSecurityHealthAnalyticsCustomModule": { + "methods": [ + "get_security_health_analytics_custom_module" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListDescendantEventThreatDetectionCustomModules": { + "methods": [ + "list_descendant_event_threat_detection_custom_modules" + ] + }, + "ListDescendantSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_descendant_security_health_analytics_custom_modules" + ] + }, + "ListEffectiveEventThreatDetectionCustomModules": { + "methods": [ + "list_effective_event_threat_detection_custom_modules" + ] + }, + "ListEffectiveSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_effective_security_health_analytics_custom_modules" + ] + }, + "ListEventThreatDetectionCustomModules": { + "methods": [ + "list_event_threat_detection_custom_modules" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_security_health_analytics_custom_modules" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "SimulateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "simulate_security_health_analytics_custom_module" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateEventThreatDetectionCustomModule": { + "methods": [ + "update_event_threat_detection_custom_module" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "update_security_health_analytics_custom_module" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + }, + "ValidateEventThreatDetectionCustomModule": { + "methods": [ + "validate_event_threat_detection_custom_module" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateEventThreatDetectionCustomModule": { + "methods": [ + "create_event_threat_detection_custom_module" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "create_security_health_analytics_custom_module" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteEventThreatDetectionCustomModule": { + "methods": [ + "delete_event_threat_detection_custom_module" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "DeleteSecurityHealthAnalyticsCustomModule": { + "methods": [ + "delete_security_health_analytics_custom_module" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetEffectiveEventThreatDetectionCustomModule": { + "methods": [ + "get_effective_event_threat_detection_custom_module" + ] + }, + "GetEffectiveSecurityHealthAnalyticsCustomModule": { + "methods": [ + "get_effective_security_health_analytics_custom_module" + ] + }, + "GetEventThreatDetectionCustomModule": { + "methods": [ + "get_event_threat_detection_custom_module" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSecurityHealthAnalyticsCustomModule": { + "methods": [ + "get_security_health_analytics_custom_module" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListDescendantEventThreatDetectionCustomModules": { + "methods": [ + "list_descendant_event_threat_detection_custom_modules" + ] + }, + "ListDescendantSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_descendant_security_health_analytics_custom_modules" + ] + }, + "ListEffectiveEventThreatDetectionCustomModules": { + "methods": [ + "list_effective_event_threat_detection_custom_modules" + ] + }, + "ListEffectiveSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_effective_security_health_analytics_custom_modules" + ] + }, + "ListEventThreatDetectionCustomModules": { + "methods": [ + "list_event_threat_detection_custom_modules" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_security_health_analytics_custom_modules" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "SimulateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "simulate_security_health_analytics_custom_module" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateEventThreatDetectionCustomModule": { + "methods": [ + "update_event_threat_detection_custom_module" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "update_security_health_analytics_custom_module" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + }, + "ValidateEventThreatDetectionCustomModule": { + "methods": [ + "validate_event_threat_detection_custom_module" + ] + } + } + }, + "rest": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateEventThreatDetectionCustomModule": { + "methods": [ + "create_event_threat_detection_custom_module" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "create_security_health_analytics_custom_module" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteEventThreatDetectionCustomModule": { + "methods": [ + "delete_event_threat_detection_custom_module" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "DeleteSecurityHealthAnalyticsCustomModule": { + "methods": [ + "delete_security_health_analytics_custom_module" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetEffectiveEventThreatDetectionCustomModule": { + "methods": [ + "get_effective_event_threat_detection_custom_module" + ] + }, + "GetEffectiveSecurityHealthAnalyticsCustomModule": { + "methods": [ + "get_effective_security_health_analytics_custom_module" + ] + }, + "GetEventThreatDetectionCustomModule": { + "methods": [ + "get_event_threat_detection_custom_module" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSecurityHealthAnalyticsCustomModule": { + "methods": [ + "get_security_health_analytics_custom_module" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListDescendantEventThreatDetectionCustomModules": { + "methods": [ + "list_descendant_event_threat_detection_custom_modules" + ] + }, + "ListDescendantSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_descendant_security_health_analytics_custom_modules" + ] + }, + "ListEffectiveEventThreatDetectionCustomModules": { + "methods": [ + "list_effective_event_threat_detection_custom_modules" + ] + }, + "ListEffectiveSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_effective_security_health_analytics_custom_modules" + ] + }, + "ListEventThreatDetectionCustomModules": { + "methods": [ + "list_event_threat_detection_custom_modules" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSecurityHealthAnalyticsCustomModules": { + "methods": [ + "list_security_health_analytics_custom_modules" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "SimulateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "simulate_security_health_analytics_custom_module" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateEventThreatDetectionCustomModule": { + "methods": [ + "update_event_threat_detection_custom_module" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityHealthAnalyticsCustomModule": { + "methods": [ + "update_security_health_analytics_custom_module" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + }, + "ValidateEventThreatDetectionCustomModule": { + "methods": [ + "validate_event_threat_detection_custom_module" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_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-securitycenter/v1/google/cloud/securitycenter_v1/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_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-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py new file mode 100644 index 000000000000..bffcff5da306 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + 'SecurityCenterClient', + 'SecurityCenterAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py new file mode 100644 index 000000000000..913bf9fee02a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -0,0 +1,7965 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +import warnings + +from google.cloud.securitycenter_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.securitycenter_v1.services.security_center import pagers +from google.cloud.securitycenter_v1.types import access +from google.cloud.securitycenter_v1.types import application +from google.cloud.securitycenter_v1.types import attack_exposure +from google.cloud.securitycenter_v1.types import attack_path +from google.cloud.securitycenter_v1.types import backup_disaster_recovery +from google.cloud.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import cloud_armor +from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile +from google.cloud.securitycenter_v1.types import cloud_dlp_inspection +from google.cloud.securitycenter_v1.types import compliance +from google.cloud.securitycenter_v1.types import connection +from google.cloud.securitycenter_v1.types import container +from google.cloud.securitycenter_v1.types import database +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors +from google.cloud.securitycenter_v1.types import exfiltration +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import file +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import group_membership +from google.cloud.securitycenter_v1.types import iam_binding +from google.cloud.securitycenter_v1.types import indicator +from google.cloud.securitycenter_v1.types import kernel_rootkit +from google.cloud.securitycenter_v1.types import kubernetes +from google.cloud.securitycenter_v1.types import load_balancer +from google.cloud.securitycenter_v1.types import log_entry +from google.cloud.securitycenter_v1.types import mitre_attack +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notebook +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import org_policy +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import process +from google.cloud.securitycenter_v1.types import resource +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import security_posture +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import toxic_combination +from google.cloud.securitycenter_v1.types import valued_resource +from google.cloud.securitycenter_v1.types import vulnerability +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 empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V1 APIs for Security Center service.""" + + _client: SecurityCenterClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE + + asset_path = staticmethod(SecurityCenterClient.asset_path) + parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) + attack_path_path = staticmethod(SecurityCenterClient.attack_path_path) + parse_attack_path_path = staticmethod(SecurityCenterClient.parse_attack_path_path) + big_query_export_path = staticmethod(SecurityCenterClient.big_query_export_path) + parse_big_query_export_path = staticmethod(SecurityCenterClient.parse_big_query_export_path) + dlp_job_path = staticmethod(SecurityCenterClient.dlp_job_path) + parse_dlp_job_path = staticmethod(SecurityCenterClient.parse_dlp_job_path) + effective_event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.effective_event_threat_detection_custom_module_path) + parse_effective_event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.parse_effective_event_threat_detection_custom_module_path) + effective_security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.effective_security_health_analytics_custom_module_path) + parse_effective_security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.parse_effective_security_health_analytics_custom_module_path) + event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.event_threat_detection_custom_module_path) + parse_event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.parse_event_threat_detection_custom_module_path) + external_system_path = staticmethod(SecurityCenterClient.external_system_path) + parse_external_system_path = staticmethod(SecurityCenterClient.parse_external_system_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) + parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) + mute_config_path = staticmethod(SecurityCenterClient.mute_config_path) + parse_mute_config_path = staticmethod(SecurityCenterClient.parse_mute_config_path) + notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) + parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) + organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) + parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) + policy_path = staticmethod(SecurityCenterClient.policy_path) + parse_policy_path = staticmethod(SecurityCenterClient.parse_policy_path) + resource_value_config_path = staticmethod(SecurityCenterClient.resource_value_config_path) + parse_resource_value_config_path = staticmethod(SecurityCenterClient.parse_resource_value_config_path) + security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.security_health_analytics_custom_module_path) + parse_security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.parse_security_health_analytics_custom_module_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) + simulation_path = staticmethod(SecurityCenterClient.simulation_path) + parse_simulation_path = staticmethod(SecurityCenterClient.parse_simulation_path) + source_path = staticmethod(SecurityCenterClient.source_path) + parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) + table_data_profile_path = staticmethod(SecurityCenterClient.table_data_profile_path) + parse_table_data_profile_path = staticmethod(SecurityCenterClient.parse_table_data_profile_path) + topic_path = staticmethod(SecurityCenterClient.topic_path) + parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) + valued_resource_path = staticmethod(SecurityCenterClient.valued_resource_path) + parse_valued_resource_path = staticmethod(SecurityCenterClient.parse_valued_resource_path) + common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) + parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) + common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) + parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) + common_project_path = staticmethod(SecurityCenterClient.common_project_path) + parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) + common_location_path = staticmethod(SecurityCenterClient.common_location_path) + parse_common_location_path = staticmethod(SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def bulk_mute_findings(self, + request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off an LRO to bulk mute findings for a parent + based on a filter. The parent can be either an + organization, folder or project. The findings matched by + the filter will be muted after the LRO is done. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest, dict]]): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + parent (:class:`str`): + Required. The parent, at which bulk action needs to be + applied. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1.types.BulkMuteFindingsResponse` + The response to a BulkMute request. Contains the LRO + 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]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): + request = securitycenter_service.BulkMuteFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.bulk_mute_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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + securitycenter_service.BulkMuteFindingsResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def create_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Creates a resident + SecurityHealthAnalyticsCustomModule at the scope of the + given CRM parent, and also creates inherited + SecurityHealthAnalyticsCustomModules for all CRM + descendants of the given parent. These modules are + enabled by default. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_create_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]]): + The request object. Request message for creating Security + Health Analytics custom modules. + parent (:class:`str`): + Required. Resource name of the new custom module's + parent. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_health_analytics_custom_module (:class:`google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule`): + Required. SecurityHealthAnalytics + custom module to create. The provided + name is ignored and reset with provided + parent information and server-generated + ID. + + This corresponds to the ``security_health_analytics_custom_module`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, security_health_analytics_custom_module]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_health_analytics_custom_module is not None: + request.security_health_analytics_custom_module = security_health_analytics_custom_module + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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 create_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v1 + + async def sample_create_source(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateSourceRequest, dict]]): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be ``organizations/[organization_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`google.cloud.securitycenter_v1.types.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = 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_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding_id: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_create_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateFindingRequest, dict]]): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + ``organizations/[organization_id]/sources/[source_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`google.cloud.securitycenter_v1.types.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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 create_mute_config(self, + request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + mute_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Creates a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_create_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = await client.create_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateMuteConfigRequest, dict]]): + The request object. Request message for creating a mute + config. + parent (:class:`str`): + Required. Resource name of the new mute configs's + parent. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config (:class:`google.cloud.securitycenter_v1.types.MuteConfig`): + Required. The mute config being + created. + + This corresponds to the ``mute_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``mute_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.cloud.securitycenter_v1.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): + request = securitycenter_service.CreateMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mute_config is not None: + request.mute_config = mute_config + if mute_config_id is not None: + request.mute_config_id = mute_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_mute_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 create_notification_config(self, + request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + config_id: Optional[str] = None, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_create_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest, dict]]): + The request object. Request message for creating a + notification config. + parent (:class:`str`): + Required. Resource name of the new notification config's + parent. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (:class:`str`): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters and contain + alphanumeric characters, underscores, or + hyphens only. + + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_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.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_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_notification_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_mute_config(self, + request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_delete_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_mute_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest, dict]]): + The request object. Request message for deleting a mute + config. + name (:class:`str`): + Required. Name of the mute config to delete. Its format + is + ``organizations/{organization}/muteConfigs/{config_id}``, + ``folders/{folder}/muteConfigs/{config_id}``, + ``projects/{project}/muteConfigs/{config_id}``, + ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, + ``folders/{folder}/locations/global/muteConfigs/{config_id}``, + or + ``projects/{project}/locations/global/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): + request = securitycenter_service.DeleteMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_mute_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 delete_notification_config(self, + request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest, dict]]): + The request object. Request message for deleting a + notification config. + name (:class:`str`): + Required. Name of the notification config to delete. Its + format is + ``organizations/[organization_id]/notificationConfigs/[config_id]``, + ``folders/[folder_id]/notificationConfigs/[config_id]``, + or + ``projects/[project_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 delete_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]] = 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 + SecurityHealthAnalyticsCustomModule and all of its + descendants in the CRM hierarchy. This method is only + supported for resident custom modules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_delete_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + await client.delete_security_health_analytics_custom_module(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]]): + The request object. Request message for deleting Security + Health Analytics custom modules. + name (:class:`str`): + Required. Name of the custom module to delete. Its + format is + ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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, securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_simulation(self, + request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> simulation.Simulation: + r"""Get the simulation by name or the latest simulation + for the given organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_simulation(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_simulation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetSimulationRequest, dict]]): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + name (:class:`str`): + Required. The organization name or simulation name of + this simulation + + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Simulation: + Attack path simulation + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSimulationRequest): + request = securitycenter_service.GetSimulationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_simulation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_valued_resource(self, + request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> valued_resource.ValuedResource: + r"""Get the valued resource by 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 import securitycenter_v1 + + async def sample_get_valued_resource(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_valued_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetValuedResourceRequest, dict]]): + The request object. Request message for getting a valued + resource. + name (:class:`str`): + Required. The name of this valued resource + + Valid format: + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v1.types.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetValuedResourceRequest): + request = securitycenter_service.GetValuedResourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_valued_resource] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_big_query_export(self, + request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Gets a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetBigQueryExportRequest, dict]]): + The request object. Request message for retrieving a + BigQuery export. + name (:class:`str`): + Required. Name of the BigQuery export to retrieve. Its + format is + ``organizations/{organization}/bigQueryExports/{export_id}``, + ``folders/{folder}/bigQueryExports/{export_id}``, or + ``projects/{project}/bigQueryExports/{export_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.cloud.securitycenter_v1.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): + request = securitycenter_service.GetBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 get_mute_config(self, + request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> mute_config.MuteConfig: + r"""Gets a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetMuteConfigRequest, dict]]): + The request object. Request message for retrieving a mute + config. + name (:class:`str`): + Required. Name of the mute config to retrieve. Its + format is + ``organizations/{organization}/muteConfigs/{config_id}``, + ``folders/{folder}/muteConfigs/{config_id}``, + ``projects/{project}/muteConfigs/{config_id}``, + ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, + ``folders/{folder}/locations/global/muteConfigs/{config_id}``, + or + ``projects/{project}/locations/global/muteConfigs/{config_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.cloud.securitycenter_v1.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetMuteConfigRequest): + request = securitycenter_service.GetMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_mute_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 get_notification_config(self, + request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetNotificationConfigRequest, dict]]): + The request object. Request message for getting a + notification config. + name (:class:`str`): + Required. Name of the notification config to get. Its + format is + ``organizations/[organization_id]/notificationConfigs/[config_id]``, + ``folders/[folder_id]/notificationConfigs/[config_id]``, + or + ``projects/[project_id]/notificationConfigs/[config_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.cloud.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 get_organization_settings(self, + request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest, dict]]): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + ``organizations/[organization_id]/organizationSettings``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_organization_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 get_effective_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: + r"""Retrieves an + EffectiveSecurityHealthAnalyticsCustomModule. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_effective_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_effective_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]]): + The request object. Request message for getting effective + Security Health Analytics custom + modules. + name (:class:`str`): + Required. Name of the effective custom module to get. + Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule: + An EffectiveSecurityHealthAnalyticsCustomModule is the representation of + a Security Health Analytics custom module at a + specified level of the resource hierarchy: + organization, folder, or project. If a custom module + is inherited from a parent organization or folder, + the value of the enablementState property in + EffectiveSecurityHealthAnalyticsCustomModule is set + to the value that is effective in the parent, instead + of INHERITED. For example, if the module is enabled + in a parent organization or folder, the effective + enablement_state for the module in all child folders + or projects is also enabled. + EffectiveSecurityHealthAnalyticsCustomModule is + read-only. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_effective_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Retrieves a SecurityHealthAnalyticsCustomModule. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest, dict]]): + The request object. Request message for getting Security + Health Analytics custom modules. + name (:class:`str`): + Required. Name of the custom module to get. Its format + is + ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v1 + + async def sample_get_source(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetSourceRequest, dict]]): + The request object. Request message for getting a source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 group_assets(self, + request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsAsyncPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_group_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GroupAssetsRequest, dict]]): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsAsyncPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + warnings.warn("SecurityCenterAsyncClient.group_assets is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.GroupAssetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_group_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GroupFindingsRequest, dict]]): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + ``organizations/[organization_id]/sources/[source_id]``, + ``folders/[folder_id]/sources/[source_id]``, or + ``projects/[project_id]/sources/[source_id]``. To + groupBy across all sources provide a source_id of ``-``. + For example: + ``organizations/{organization_id}/sources/-, folders/{folder_id}/sources/-``, + or ``projects/{project_id}/sources/-`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported when compare_duration + is set: + + - state_change + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets(self, + request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists an organization's assets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListAssetsRequest, dict]]): + The request object. Request message for listing assets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsAsyncPager: + Response message for listing assets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + warnings.warn("SecurityCenterAsyncClient.list_assets is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(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_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListAssetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_descendant_security_health_analytics_custom_modules(self, + request: Optional[Union[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, 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.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: + r"""Returns a list of all resident + SecurityHealthAnalyticsCustomModules under the given CRM + parent and all of the parent’s CRM descendants. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_descendant_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, dict]]): + The request object. Request message for listing + descendant Security Health Analytics + custom modules. + parent (:class:`str`): + Required. Name of parent to list descendant custom + modules. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + 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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: + Response message for listing + descendant Security Health Analytics + custom modules. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_descendant_security_health_analytics_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings(self, + request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListFindingsRequest( + parent="parent_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.securitycenter_v1.types.ListFindingsRequest, dict]]): + The request object. Request message for listing findings. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.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_mute_configs(self, + request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsAsyncPager: + r"""Lists mute configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_mute_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListMuteConfigsRequest, dict]]): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or project. + parent (:class:`str`): + Required. The parent, which owns the collection of mute + configs. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + + 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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsAsyncPager: + Response message for listing mute + configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): + request = securitycenter_service.ListMuteConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_mute_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.ListMuteConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_notification_configs(self, + request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsAsyncPager: + r"""Lists notification configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest, dict]]): + The request object. Request message for listing + notification configs. + parent (:class:`str`): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]", + "folders/[folder_id]", or "projects/[project_id]". + + 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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsAsyncPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListNotificationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_effective_security_health_analytics_custom_modules(self, + request: Optional[Union[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, 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.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: + r"""Returns a list of all + EffectiveSecurityHealthAnalyticsCustomModules for the + given parent. This includes resident modules defined at + the scope of the parent, and inherited modules, + inherited from CRM ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_effective_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_security_health_analytics_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, dict]]): + The request object. Request message for listing effective + Security Health Analytics custom + modules. + parent (:class:`str`): + Required. Name of parent to list effective custom + modules. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + 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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: + Response message for listing + effective Security Health Analytics + custom modules. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_effective_security_health_analytics_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_security_health_analytics_custom_modules(self, + request: Optional[Union[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, 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.ListSecurityHealthAnalyticsCustomModulesAsyncPager: + r"""Returns a list of all + SecurityHealthAnalyticsCustomModules for the given + parent. This includes resident modules defined at the + scope of the parent, and inherited modules, inherited + from CRM ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_health_analytics_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest, dict]]): + The request object. Request message for listing Security + Health Analytics custom modules. + parent (:class:`str`): + Required. Name of parent to list custom modules. Its + format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + 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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager: + Response message for listing Security + Health Analytics custom modules. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_security_health_analytics_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListSecurityHealthAnalyticsCustomModulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_sources(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListSourcesRequest, dict]]): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + 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.securitycenter_v1.services.security_center.pagers.ListSourcesAsyncPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_asset_discovery(self, + request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS 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 securitycenter_v1 + + async def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest, dict]]): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + ``organizations/[organization_id]``. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` + Response of asset discovery run + + """ + warnings.warn("SecurityCenterAsyncClient.run_asset_discovery is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.run_asset_discovery] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + start_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of 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 securitycenter_v1 + + async def sample_set_finding_state(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.SetFindingStateRequest, dict]]): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The `relative resource + name `__ + of the finding. Example: + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, + ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`google.cloud.securitycenter_v1.types.Finding.State`): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_mute(self, + request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, + *, + name: Optional[str] = None, + mute: Optional[finding.Finding.Mute] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the mute state of 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 securitycenter_v1 + + async def sample_set_mute(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = await client.set_mute(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.SetMuteRequest, dict]]): + The request object. Request message for updating a + finding's mute status. + name (:class:`str`): + Required. The `relative resource + name `__ + of the finding. Example: + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, + ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute (:class:`google.cloud.securitycenter_v1.types.Finding.Mute`): + Required. The desired state of the + Mute. + + This corresponds to the ``mute`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, mute]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetMuteRequest): + request = securitycenter_service.SetMuteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if mute is not None: + request.mute = mute + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.set_mute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 simulate_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_config: Optional[security_health_analytics_custom_config.CustomConfig] = None, + resource: Optional[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: + r"""Simulates a given SecurityHealthAnalyticsCustomModule + and Resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_simulate_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + resource = securitycenter_v1.SimulatedResource() + resource.resource_type = "resource_type_value" + + request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + resource=resource, + ) + + # Make the request + response = await client.simulate_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]]): + The request object. Request message to simulate a + CustomConfig against a given test + resource. Maximum size of the request is + 4 MB by default. + parent (:class:`str`): + Required. The relative resource name of the + organization, project, or folder. For more information + about relative resource names, see `Relative Resource + Name `__ + Example: ``organizations/{organization_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_config (:class:`google.cloud.securitycenter_v1.types.CustomConfig`): + Required. The custom configuration + that you need to test. + + This corresponds to the ``custom_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (:class:`google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource`): + Required. Resource data to simulate + custom module against. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse: + Response message for simulating a SecurityHealthAnalyticsCustomModule + against a given 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, custom_config, resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_config is not None: + request.custom_config = custom_config + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.simulate_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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_external_system(self, + request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, + *, + external_system: Optional[gcs_external_system.ExternalSystem] = None, + update_mask: 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]] = (), + ) -> gcs_external_system.ExternalSystem: + r"""Updates external system. This is for a given 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 securitycenter_v1 + + async def sample_update_external_system(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateExternalSystemRequest( + ) + + # Make the request + response = await client.update_external_system(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest, dict]]): + The request object. Request message for updating a + ExternalSystem resource. + external_system (:class:`google.cloud.securitycenter_v1.types.ExternalSystem`): + Required. The external system + resource to update. + + This corresponds to the ``external_system`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the external system resource. + If empty all mutable fields 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.cloud.securitycenter_v1.types.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): + request = securitycenter_service.UpdateExternalSystemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if external_system is not None: + request.external_system = external_system + 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_external_system] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("external_system.name", request.external_system.name), + )), + ) + + # Validate the universe domain. + self._client._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_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateFindingRequest, dict]]): + The request object. Request message for updating or + creating a finding. + finding (:class:`google.cloud.securitycenter_v1.types.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe domain. + self._client._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_mute_config(self, + request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, + *, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + update_mask: 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]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Updates a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = await client.update_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest, dict]]): + The request object. Request message for updating a mute + config. + mute_config (:class:`google.cloud.securitycenter_v1.types.MuteConfig`): + Required. The mute config being + updated. + + This corresponds to the ``mute_config`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): + request = securitycenter_service.UpdateMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mute_config is not None: + request.mute_config = mute_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_mute_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("mute_config.name", request.mute_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 update_notification_config(self, + request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, + *, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + update_mask: 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest, dict]]): + The request object. Request message for updating a + notification config. + notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the notification config. + If empty all mutable fields 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.cloud.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_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 update_organization_settings(self, + request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, + *, + organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = await client.update_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest, dict]]): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`google.cloud.securitycenter_v1.types.OrganizationSettings`): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_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 update_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, + update_mask: 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]] = (), + ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Updates the SecurityHealthAnalyticsCustomModule under + the given name based on the given update mask. Updating + the enablement state is supported on both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name and custom config of a module is supported + on resident modules only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( + ) + + # Make the request + response = await client.update_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]]): + The request object. Request message for updating Security + Health Analytics custom modules. + security_health_analytics_custom_module (:class:`google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule`): + Required. The SecurityHealthAnalytics + custom module to update. + + This corresponds to the ``security_health_analytics_custom_module`` 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 only fields that + can be updated are ``enablement_state`` and + ``custom_config``. If empty or set to the wildcard value + ``*``, both ``enablement_state`` and ``custom_config`` + are 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.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_health_analytics_custom_module, 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, securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_health_analytics_custom_module is not None: + request.security_health_analytics_custom_module = security_health_analytics_custom_module + 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_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_health_analytics_custom_module.name", request.security_health_analytics_custom_module.name), + )), + ) + + # Validate the universe domain. + self._client._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_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v1 + + async def sample_update_source(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateSourceRequest, dict]]): + The request object. Request message for updating a + source. + source (:class:`google.cloud.securitycenter_v1.types.Source`): + Required. The source resource to + update. + + This corresponds to the ``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.cloud.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_security_marks(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest, dict]]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`google.cloud.securitycenter_v1.types.SecurityMarks`): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe domain. + self._client._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_big_query_export(self, + request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, + *, + parent: Optional[str] = None, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + big_query_export_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Creates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_create_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = await client.create_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest, dict]]): + The request object. Request message for creating a + BigQuery export. + parent (:class:`str`): + Required. The name of the parent resource of the new + BigQuery export. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export (:class:`google.cloud.securitycenter_v1.types.BigQueryExport`): + Required. The BigQuery export being + created. + + This corresponds to the ``big_query_export`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``big_query_export_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.cloud.securitycenter_v1.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): + request = securitycenter_service.CreateBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if big_query_export is not None: + request.big_query_export = big_query_export + if big_query_export_id is not None: + request.big_query_export_id = big_query_export_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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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_big_query_export(self, + request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + await client.delete_big_query_export(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest, dict]]): + The request object. Request message for deleting a + BigQuery export. + name (:class:`str`): + Required. The name of the BigQuery export to delete. Its + format is + ``organizations/{organization}/bigQueryExports/{export_id}``, + ``folders/{folder}/bigQueryExports/{export_id}``, or + ``projects/{project}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): + request = securitycenter_service.DeleteBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_big_query_export(self, + request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, + *, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + update_mask: 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]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Updates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateBigQueryExportRequest( + ) + + # Make the request + response = await client.update_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest, dict]]): + The request object. Request message for updating a + BigQuery export. + big_query_export (:class:`google.cloud.securitycenter_v1.types.BigQueryExport`): + Required. The BigQuery export being + updated. + + This corresponds to the ``big_query_export`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): + request = securitycenter_service.UpdateBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if big_query_export is not None: + request.big_query_export = big_query_export + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("big_query_export.name", request.big_query_export.name), + )), + ) + + # Validate the universe domain. + self._client._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_big_query_exports(self, + request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsAsyncPager: + r"""Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are 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 securitycenter_v1 + + async def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest, dict]]): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or project. + parent (:class:`str`): + Required. The parent, which owns the collection of + BigQuery exports. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + + 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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsAsyncPager: + Response message for listing BigQuery + exports. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): + request = securitycenter_service.ListBigQueryExportsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_big_query_exports] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListBigQueryExportsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Creates a resident Event Threat Detection custom + module at the scope of the given Resource Manager + parent, and also creates inherited custom modules for + all descendants of the given parent. These modules are + enabled by default. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_create_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest, dict]]): + The request object. Request to create an Event Threat + Detection custom module. + parent (:class:`str`): + Required. The new custom module's parent. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_threat_detection_custom_module (:class:`google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule`): + Required. The module to create. The + event_threat_detection_custom_module.name will be + ignored and server generated. + + This corresponds to the ``event_threat_detection_custom_module`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, event_threat_detection_custom_module]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if event_threat_detection_custom_module is not None: + request.event_threat_detection_custom_module = event_threat_detection_custom_module + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, dict]] = 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 Event Threat Detection custom + module and all of its descendants in the Resource + Manager hierarchy. This method is only supported for + resident custom modules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_delete_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + await client.delete_event_threat_detection_custom_module(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest, dict]]): + The request object. Request to delete an Event Threat + Detection custom module. + name (:class:`str`): + Required. Name of the custom module to delete. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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, securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.GetEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Gets an Event Threat Detection custom module. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest, dict]]): + The request object. Request to get an Event Threat + Detection custom module. + name (:class:`str`): + Required. Name of the custom module to get. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_descendant_event_threat_detection_custom_modules(self, + request: Optional[Union[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, 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.ListDescendantEventThreatDetectionCustomModulesAsyncPager: + r"""Lists all resident Event Threat Detection custom + modules under the given Resource Manager parent and its + descendants. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_descendant_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest, dict]]): + The request object. Request to list current and + descendant resident Event Threat + Detection custom modules. + parent (:class:`str`): + Required. Name of the parent to list custom modules + under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + 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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager: + Response for listing current and + descendant resident Event Threat + Detection custom modules. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_descendant_event_threat_detection_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListDescendantEventThreatDetectionCustomModulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_event_threat_detection_custom_modules(self, + request: Optional[Union[securitycenter_service.ListEventThreatDetectionCustomModulesRequest, 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.ListEventThreatDetectionCustomModulesAsyncPager: + r"""Lists all Event Threat Detection custom modules for + the given Resource Manager parent. This includes + resident modules defined at the scope of the parent + along with modules inherited from ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_event_threat_detection_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest, dict]]): + The request object. Request to list Event Threat + Detection custom modules. + parent (:class:`str`): + Required. Name of the parent to list custom modules + under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + 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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesAsyncPager: + Response for listing Event Threat + Detection custom modules. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListEventThreatDetectionCustomModulesRequest): + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_event_threat_detection_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListEventThreatDetectionCustomModulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, + update_mask: 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]] = (), + ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Updates the Event Threat Detection custom module with + the given name based on the given update mask. Updating + the enablement state is supported for both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name or configuration of a module is supported + for resident modules only. The type of a module cannot + be changed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( + ) + + # Make the request + response = await client.update_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest, dict]]): + The request object. Request to update an Event Threat + Detection custom module. + event_threat_detection_custom_module (:class:`google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule`): + Required. The module being updated. + This corresponds to the ``event_threat_detection_custom_module`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([event_threat_detection_custom_module, 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, securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if event_threat_detection_custom_module is not None: + request.event_threat_detection_custom_module = event_threat_detection_custom_module + 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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("event_threat_detection_custom_module.name", request.event_threat_detection_custom_module.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def validate_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: + r"""Validates the given Event Threat Detection custom + module. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_validate_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + raw_text="raw_text_value", + type_="type__value", + ) + + # Make the request + response = await client.validate_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest, dict]]): + The request object. Request to validate an Event Threat + Detection custom module. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse: + Response to validating an Event + Threat Detection custom module. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest(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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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_effective_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: + r"""Gets an effective Event Threat Detection custom + module at the given level. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_effective_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_effective_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]]): + The request object. Request to get an + EffectiveEventThreatDetectionCustomModule. + name (:class:`str`): + Required. The resource name of the effective Event + Threat Detection custom module. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule: + An EffectiveEventThreatDetectionCustomModule is the representation of + an Event Threat Detection custom module at a + specified level of the resource hierarchy: + organization, folder, or project. If a custom module + is inherited from a parent organization or folder, + the value of the enablement_state property in + EffectiveEventThreatDetectionCustomModule is set to + the value that is effective in the parent, instead of + INHERITED. For example, if the module is enabled in a + parent organization or folder, the effective + enablement_state for the module in all child folders + or projects is also enabled. + EffectiveEventThreatDetectionCustomModule is + read-only. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_effective_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_effective_event_threat_detection_custom_modules(self, + request: Optional[Union[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, 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.ListEffectiveEventThreatDetectionCustomModulesAsyncPager: + r"""Lists all effective Event Threat Detection custom + modules for the given parent. This includes resident + modules defined at the scope of the parent along with + modules inherited from its ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_effective_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_event_threat_detection_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest, dict]]): + The request object. Request to list effective Event + Threat Detection custom modules. + parent (:class:`str`): + Required. Name of the parent to list custom modules for. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + 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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesAsyncPager: + Response for listing + EffectiveEventThreatDetectionCustomModules. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_effective_event_threat_detection_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListEffectiveEventThreatDetectionCustomModulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_create_resource_value_configs(self, + request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + requests = securitycenter_v1.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + requests.resource_value_config.resource_value = "NONE" + requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest, dict]]): + The request object. Request message to create multiple + resource value configs + parent (:class:`str`): + Required. Resource name of the new + ResourceValueConfig's parent. The parent + field in the + CreateResourceValueConfigRequest + messages must either be empty or match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (:class:`MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]`): + Required. The resource value configs + to be created. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, requests]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): + request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests: + request.requests.extend(requests) + + # 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_resource_value_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, + ) + + # Done; return the response. + return response + + async def delete_resource_value_config(self, + request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_resource_value_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest, dict]]): + The request object. Request message to delete resource + value config + name (:class:`str`): + Required. Name of the + ResourceValueConfig 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. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): + request = securitycenter_service.DeleteResourceValueConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_resource_value_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_resource_value_config(self, + request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource_value_config.ResourceValueConfig: + r"""Gets a ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest, dict]]): + The request object. Request message to get resource value + config + name (:class:`str`): + Required. Name of the resource value config to retrieve. + Its format is + ``organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v1.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): + request = securitycenter_service.GetResourceValueConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_resource_value_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_resource_value_configs(self, + request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsAsyncPager: + r"""Lists all ResourceValueConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest, dict]]): + The request object. Request message to list resource + value configs of a parent + parent (:class:`str`): + Required. The parent, which owns the collection of + resource value configs. Its format is + ``organizations/[organization_id]`` + + 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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsAsyncPager: + Response message to list resource + value configs + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): + request = securitycenter_service.ListResourceValueConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_resource_value_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.ListResourceValueConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_resource_value_config(self, + request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, + *, + resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, + update_mask: 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]] = (), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Updates an existing ResourceValueConfigs with new + rules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + resource_value_config = securitycenter_v1.ResourceValueConfig() + resource_value_config.resource_value = "NONE" + resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.UpdateResourceValueConfigRequest( + resource_value_config=resource_value_config, + ) + + # Make the request + response = await client.update_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest, dict]]): + The request object. Request message to update resource + value config + resource_value_config (:class:`google.cloud.securitycenter_v1.types.ResourceValueConfig`): + Required. The resource value config + being updated. + + This corresponds to the ``resource_value_config`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): + request = securitycenter_service.UpdateResourceValueConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if resource_value_config is not None: + request.resource_value_config = resource_value_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_resource_value_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource_value_config.name", request.resource_value_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 list_valued_resources(self, + request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesAsyncPager: + r"""Lists the valued resources for a set of simulation + results and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_valued_resources(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListValuedResourcesRequest, dict]]): + The request object. Request message for listing the + valued resources for a given simulation. + parent (:class:`str`): + Required. Name of parent to list valued resources. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + + 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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesAsyncPager: + Response message for listing the + valued resources for a given simulation. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): + request = securitycenter_service.ListValuedResourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_valued_resources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListValuedResourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_attack_paths(self, + request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsAsyncPager: + r"""Lists the attack paths for a set of simulation + results or valued resources and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + async def sample_list_attack_paths(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1.types.ListAttackPathsRequest, dict]]): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + parent (:class:`str`): + Required. Name of parent to list attack paths. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + + 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.securitycenter_v1.services.security_center.pagers.ListAttackPathsAsyncPager: + Response message for listing the + attack paths for a given simulation or + valued resource. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): + request = securitycenter_service.ListAttackPathsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_attack_paths] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListAttackPathsAsyncPager( + method=rpc, + request=request, + response=response, + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "SecurityCenterAsyncClient": + 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__ = ( + "SecurityCenterAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py new file mode 100644 index 000000000000..2224817c3303 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py @@ -0,0 +1,8455 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_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.securitycenter_v1.services.security_center import pagers +from google.cloud.securitycenter_v1.types import access +from google.cloud.securitycenter_v1.types import application +from google.cloud.securitycenter_v1.types import attack_exposure +from google.cloud.securitycenter_v1.types import attack_path +from google.cloud.securitycenter_v1.types import backup_disaster_recovery +from google.cloud.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import cloud_armor +from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile +from google.cloud.securitycenter_v1.types import cloud_dlp_inspection +from google.cloud.securitycenter_v1.types import compliance +from google.cloud.securitycenter_v1.types import connection +from google.cloud.securitycenter_v1.types import container +from google.cloud.securitycenter_v1.types import database +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors +from google.cloud.securitycenter_v1.types import exfiltration +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import file +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import group_membership +from google.cloud.securitycenter_v1.types import iam_binding +from google.cloud.securitycenter_v1.types import indicator +from google.cloud.securitycenter_v1.types import kernel_rootkit +from google.cloud.securitycenter_v1.types import kubernetes +from google.cloud.securitycenter_v1.types import load_balancer +from google.cloud.securitycenter_v1.types import log_entry +from google.cloud.securitycenter_v1.types import mitre_attack +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notebook +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import org_policy +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import process +from google.cloud.securitycenter_v1.types import resource +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import security_posture +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import toxic_combination +from google.cloud.securitycenter_v1.types import valued_resource +from google.cloud.securitycenter_v1.types import vulnerability +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 empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .transports.rest import SecurityCenterRestTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + _transport_registry["rest"] = SecurityCenterRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SecurityCenterTransport]: + """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V1 APIs for Security Center 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 = "securitycenter.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: + SecurityCenterClient: 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: + SecurityCenterClient: 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) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def asset_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified asset string.""" + return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_asset_path(path: str) -> Dict[str,str]: + """Parses a asset path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def attack_path_path(organization: str,simulation: str,valued_resource: str,attack_path: str,) -> str: + """Returns a fully-qualified attack_path string.""" + return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) + + @staticmethod + def parse_attack_path_path(path: str) -> Dict[str,str]: + """Parses a attack_path path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?P.+?)/attackPaths/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def big_query_export_path(organization: str,export: str,) -> str: + """Returns a fully-qualified big_query_export string.""" + return "organizations/{organization}/bigQueryExports/{export}".format(organization=organization, export=export, ) + + @staticmethod + def parse_big_query_export_path(path: str) -> Dict[str,str]: + """Parses a big_query_export path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/bigQueryExports/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def dlp_job_path(project: str,dlp_job: str,) -> str: + """Returns a fully-qualified dlp_job string.""" + return "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) + + @staticmethod + def parse_dlp_job_path(path: str) -> Dict[str,str]: + """Parses a dlp_job path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/dlpJobs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def effective_event_threat_detection_custom_module_path(organization: str,module: str,) -> str: + """Returns a fully-qualified effective_event_threat_detection_custom_module string.""" + return "organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}".format(organization=organization, module=module, ) + + @staticmethod + def parse_effective_event_threat_detection_custom_module_path(path: str) -> Dict[str,str]: + """Parses a effective_event_threat_detection_custom_module path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/eventThreatDetectionSettings/effectiveCustomModules/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def effective_security_health_analytics_custom_module_path(organization: str,effective_custom_module: str,) -> str: + """Returns a fully-qualified effective_security_health_analytics_custom_module string.""" + return "organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{effective_custom_module}".format(organization=organization, effective_custom_module=effective_custom_module, ) + + @staticmethod + def parse_effective_security_health_analytics_custom_module_path(path: str) -> Dict[str,str]: + """Parses a effective_security_health_analytics_custom_module path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/securityHealthAnalyticsSettings/effectiveCustomModules/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def event_threat_detection_custom_module_path(organization: str,module: str,) -> str: + """Returns a fully-qualified event_threat_detection_custom_module string.""" + return "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}".format(organization=organization, module=module, ) + + @staticmethod + def parse_event_threat_detection_custom_module_path(path: str) -> Dict[str,str]: + """Parses a event_threat_detection_custom_module path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/eventThreatDetectionSettings/customModules/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def external_system_path(organization: str,source: str,finding: str,externalsystem: str,) -> str: + """Returns a fully-qualified external_system string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) + + @staticmethod + def parse_external_system_path(path: str) -> Dict[str,str]: + """Parses a external_system path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)/externalSystems/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def finding_path(organization: str,source: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def mute_config_path(organization: str,mute_config: str,) -> str: + """Returns a fully-qualified mute_config string.""" + return "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) + + @staticmethod + def parse_mute_config_path(path: str) -> Dict[str,str]: + """Parses a mute_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/muteConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def notification_config_path(organization: str,notification_config: str,) -> str: + """Returns a fully-qualified notification_config string.""" + return "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) + + @staticmethod + def parse_notification_config_path(path: str) -> Dict[str,str]: + """Parses a notification_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def organization_settings_path(organization: str,) -> str: + """Returns a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format(organization=organization, ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str,str]: + """Parses a organization_settings path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def policy_path(organization: str,constraint_name: str,) -> str: + """Returns a fully-qualified policy string.""" + return "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) + + @staticmethod + def parse_policy_path(path: str) -> Dict[str,str]: + """Parses a policy path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/policies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def resource_value_config_path(organization: str,resource_value_config: str,) -> str: + """Returns a fully-qualified resource_value_config string.""" + return "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) + + @staticmethod + def parse_resource_value_config_path(path: str) -> Dict[str,str]: + """Parses a resource_value_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/resourceValueConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_health_analytics_custom_module_path(organization: str,custom_module: str,) -> str: + """Returns a fully-qualified security_health_analytics_custom_module string.""" + return "organizations/{organization}/securityHealthAnalyticsSettings/customModules/{custom_module}".format(organization=organization, custom_module=custom_module, ) + + @staticmethod + def parse_security_health_analytics_custom_module_path(path: str) -> Dict[str,str]: + """Parses a security_health_analytics_custom_module path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/securityHealthAnalyticsSettings/customModules/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str,str]: + """Parses a security_marks path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) + return m.groupdict() if m else {} + + @staticmethod + def simulation_path(organization: str,simulation: str,) -> str: + """Returns a fully-qualified simulation string.""" + return "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) + + @staticmethod + def parse_simulation_path(path: str) -> Dict[str,str]: + """Parses a simulation path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str,source: str,) -> str: + """Returns a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str,str]: + """Parses a source path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def table_data_profile_path(project: str,table_profile: str,) -> str: + """Returns a fully-qualified table_data_profile string.""" + return "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) + + @staticmethod + def parse_table_data_profile_path(path: str) -> Dict[str,str]: + """Parses a table_data_profile path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/tableProfiles/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def topic_path(project: str,topic: str,) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str,str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def valued_resource_path(organization: str,simulation: str,valued_resource: str,) -> str: + """Returns a fully-qualified valued_resource string.""" + return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) + + @staticmethod + def parse_valued_resource_path(path: str) -> Dict[str,str]: + """Parses a valued_resource path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 + SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient._read_environment_variables() + self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) + if transport_provided: + # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SecurityCenterTransport], 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 bulk_mute_findings(self, + request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), + ) -> operation.Operation: + r"""Kicks off an LRO to bulk mute findings for a parent + based on a filter. The parent can be either an + organization, folder or project. The findings matched by + the filter will be muted after the LRO is done. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest, dict]): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + parent (str): + Required. The parent, at which bulk action needs to be + applied. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1.types.BulkMuteFindingsResponse` + The response to a BulkMute request. Contains the LRO + 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): + request = securitycenter_service.BulkMuteFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.bulk_mute_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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + securitycenter_service.BulkMuteFindingsResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def create_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Creates a resident + SecurityHealthAnalyticsCustomModule at the scope of the + given CRM parent, and also creates inherited + SecurityHealthAnalyticsCustomModules for all CRM + descendants of the given parent. These modules are + enabled by default. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_create_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]): + The request object. Request message for creating Security + Health Analytics custom modules. + parent (str): + Required. Resource name of the new custom module's + parent. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): + Required. SecurityHealthAnalytics + custom module to create. The provided + name is ignored and reset with provided + parent information and server-generated + ID. + + This corresponds to the ``security_health_analytics_custom_module`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, security_health_analytics_custom_module]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_health_analytics_custom_module is not None: + request.security_health_analytics_custom_module = security_health_analytics_custom_module + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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 create_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v1 + + def sample_create_source(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateSourceRequest, dict]): + The request object. Request message for creating a + source. + parent (str): + Required. Resource name of the new source's parent. Its + format should be ``organizations/[organization_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (google.cloud.securitycenter_v1.types.Source): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding_id: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_create_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateFindingRequest, dict]): + The request object. Request message for creating a + finding. + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + ``organizations/[organization_id]/sources/[source_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (google.cloud.securitycenter_v1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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 create_mute_config(self, + request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + mute_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Creates a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_create_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = client.create_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateMuteConfigRequest, dict]): + The request object. Request message for creating a mute + config. + parent (str): + Required. Resource name of the new mute configs's + parent. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config (google.cloud.securitycenter_v1.types.MuteConfig): + Required. The mute config being + created. + + This corresponds to the ``mute_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``mute_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.cloud.securitycenter_v1.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): + request = securitycenter_service.CreateMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mute_config is not None: + request.mute_config = mute_config + if mute_config_id is not None: + request.mute_config_id = mute_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_mute_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 create_notification_config(self, + request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + config_id: Optional[str] = None, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_create_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest, dict]): + The request object. Request message for creating a + notification config. + parent (str): + Required. Resource name of the new notification config's + parent. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (str): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters and contain + alphanumeric characters, underscores, or + hyphens only. + + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_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.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_notification_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_mute_config(self, + request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_delete_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_mute_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest, dict]): + The request object. Request message for deleting a mute + config. + name (str): + Required. Name of the mute config to delete. Its format + is + ``organizations/{organization}/muteConfigs/{config_id}``, + ``folders/{folder}/muteConfigs/{config_id}``, + ``projects/{project}/muteConfigs/{config_id}``, + ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, + ``folders/{folder}/locations/global/muteConfigs/{config_id}``, + or + ``projects/{project}/locations/global/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): + request = securitycenter_service.DeleteMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_mute_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 delete_notification_config(self, + request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest, dict]): + The request object. Request message for deleting a + notification config. + name (str): + Required. Name of the notification config to delete. Its + format is + ``organizations/[organization_id]/notificationConfigs/[config_id]``, + ``folders/[folder_id]/notificationConfigs/[config_id]``, + or + ``projects/[project_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 delete_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]] = 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 + SecurityHealthAnalyticsCustomModule and all of its + descendants in the CRM hierarchy. This method is only + supported for resident custom modules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_delete_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + client.delete_security_health_analytics_custom_module(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]): + The request object. Request message for deleting Security + Health Analytics custom modules. + name (str): + Required. Name of the custom module to delete. Its + format is + ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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, securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + 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_simulation(self, + request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> simulation.Simulation: + r"""Get the simulation by name or the latest simulation + for the given organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_simulation(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = client.get_simulation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetSimulationRequest, dict]): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + name (str): + Required. The organization name or simulation name of + this simulation + + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Simulation: + Attack path simulation + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSimulationRequest): + request = securitycenter_service.GetSimulationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_simulation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_valued_resource(self, + request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> valued_resource.ValuedResource: + r"""Get the valued resource by 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 import securitycenter_v1 + + def sample_get_valued_resource(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_valued_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetValuedResourceRequest, dict]): + The request object. Request message for getting a valued + resource. + name (str): + Required. The name of this valued resource + + Valid format: + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v1.types.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetValuedResourceRequest): + request = securitycenter_service.GetValuedResourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_valued_resource] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_big_query_export(self, + request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Gets a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = client.get_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetBigQueryExportRequest, dict]): + The request object. Request message for retrieving a + BigQuery export. + name (str): + Required. Name of the BigQuery export to retrieve. Its + format is + ``organizations/{organization}/bigQueryExports/{export_id}``, + ``folders/{folder}/bigQueryExports/{export_id}``, or + ``projects/{project}/bigQueryExports/{export_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.cloud.securitycenter_v1.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): + request = securitycenter_service.GetBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 get_mute_config(self, + request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> mute_config.MuteConfig: + r"""Gets a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetMuteConfigRequest, dict]): + The request object. Request message for retrieving a mute + config. + name (str): + Required. Name of the mute config to retrieve. Its + format is + ``organizations/{organization}/muteConfigs/{config_id}``, + ``folders/{folder}/muteConfigs/{config_id}``, + ``projects/{project}/muteConfigs/{config_id}``, + ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, + ``folders/{folder}/locations/global/muteConfigs/{config_id}``, + or + ``projects/{project}/locations/global/muteConfigs/{config_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.cloud.securitycenter_v1.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetMuteConfigRequest): + request = securitycenter_service.GetMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_mute_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 get_notification_config(self, + request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetNotificationConfigRequest, dict]): + The request object. Request message for getting a + notification config. + name (str): + Required. Name of the notification config to get. Its + format is + ``organizations/[organization_id]/notificationConfigs/[config_id]``, + ``folders/[folder_id]/notificationConfigs/[config_id]``, + or + ``projects/[project_id]/notificationConfigs/[config_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.cloud.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 get_organization_settings(self, + request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest, dict]): + The request object. Request message for getting + organization settings. + name (str): + Required. Name of the organization to get organization + settings for. Its format is + ``organizations/[organization_id]/organizationSettings``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_organization_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 get_effective_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: + r"""Retrieves an + EffectiveSecurityHealthAnalyticsCustomModule. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_effective_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_effective_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]): + The request object. Request message for getting effective + Security Health Analytics custom + modules. + name (str): + Required. Name of the effective custom module to get. + Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule: + An EffectiveSecurityHealthAnalyticsCustomModule is the representation of + a Security Health Analytics custom module at a + specified level of the resource hierarchy: + organization, folder, or project. If a custom module + is inherited from a parent organization or folder, + the value of the enablementState property in + EffectiveSecurityHealthAnalyticsCustomModule is set + to the value that is effective in the parent, instead + of INHERITED. For example, if the module is enabled + in a parent organization or folder, the effective + enablement_state for the module in all child folders + or projects is also enabled. + EffectiveSecurityHealthAnalyticsCustomModule is + read-only. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_effective_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Retrieves a SecurityHealthAnalyticsCustomModule. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest, dict]): + The request object. Request message for getting Security + Health Analytics custom modules. + name (str): + Required. Name of the custom module to get. Its format + is + ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v1 + + def sample_get_source(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetSourceRequest, dict]): + The request object. Request message for getting a source. + name (str): + Required. Relative resource name of the source. Its + format is + ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 group_assets(self, + request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_group_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GroupAssetsRequest, dict]): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + warnings.warn("SecurityCenterClient.group_assets is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.GroupAssetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_group_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GroupFindingsRequest, dict]): + The request object. Request message for grouping by + findings. + parent (str): + Required. Name of the source to groupBy. Its format is + ``organizations/[organization_id]/sources/[source_id]``, + ``folders/[folder_id]/sources/[source_id]``, or + ``projects/[project_id]/sources/[source_id]``. To + groupBy across all sources provide a source_id of ``-``. + For example: + ``organizations/{organization_id}/sources/-, folders/{folder_id}/sources/-``, + or ``projects/{project_id}/sources/-`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (str): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported when compare_duration + is set: + + - state_change + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets(self, + request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists an organization's assets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListAssetsRequest, dict]): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsPager: + Response message for listing assets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + warnings.warn("SecurityCenterClient.list_assets is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListAssetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_descendant_security_health_analytics_custom_modules(self, + request: Optional[Union[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, 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.ListDescendantSecurityHealthAnalyticsCustomModulesPager: + r"""Returns a list of all resident + SecurityHealthAnalyticsCustomModules under the given CRM + parent and all of the parent’s CRM descendants. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_descendant_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, dict]): + The request object. Request message for listing + descendant Security Health Analytics + custom modules. + parent (str): + Required. Name of parent to list descendant custom + modules. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + 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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager: + Response message for listing + descendant Security Health Analytics + custom modules. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_descendant_security_health_analytics_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListDescendantSecurityHealthAnalyticsCustomModulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings(self, + request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListFindingsRequest( + parent="parent_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.securitycenter_v1.types.ListFindingsRequest, dict]): + The request object. Request message for listing findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.services.security_center.pagers.ListFindingsPager: + Response message for listing + findings. + 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.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_mute_configs(self, + request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsPager: + r"""Lists mute configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_mute_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListMuteConfigsRequest, dict]): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or project. + parent (str): + Required. The parent, which owns the collection of mute + configs. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + + 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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsPager: + Response message for listing mute + configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): + request = securitycenter_service.ListMuteConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_mute_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.ListMuteConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_notification_configs(self, + request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsPager: + r"""Lists notification configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest, dict]): + The request object. Request message for listing + notification configs. + parent (str): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]", + "folders/[folder_id]", or "projects/[project_id]". + + 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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListNotificationConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_effective_security_health_analytics_custom_modules(self, + request: Optional[Union[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, 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.ListEffectiveSecurityHealthAnalyticsCustomModulesPager: + r"""Returns a list of all + EffectiveSecurityHealthAnalyticsCustomModules for the + given parent. This includes resident modules defined at + the scope of the parent, and inherited modules, + inherited from CRM ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_effective_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_security_health_analytics_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, dict]): + The request object. Request message for listing effective + Security Health Analytics custom + modules. + parent (str): + Required. Name of parent to list effective custom + modules. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + 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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager: + Response message for listing + effective Security Health Analytics + custom modules. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_effective_security_health_analytics_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListEffectiveSecurityHealthAnalyticsCustomModulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_security_health_analytics_custom_modules(self, + request: Optional[Union[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, 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.ListSecurityHealthAnalyticsCustomModulesPager: + r"""Returns a list of all + SecurityHealthAnalyticsCustomModules for the given + parent. This includes resident modules defined at the + scope of the parent, and inherited modules, inherited + from CRM ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_health_analytics_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest, dict]): + The request object. Request message for listing Security + Health Analytics custom modules. + parent (str): + Required. Name of parent to list custom modules. Its + format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + + 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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesPager: + Response message for listing Security + Health Analytics custom modules. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_security_health_analytics_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListSecurityHealthAnalyticsCustomModulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_sources(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListSourcesRequest, dict]): + The request object. Request message for listing sources. + parent (str): + Required. Resource name of the parent of sources to + list. Its format should be + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + 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.securitycenter_v1.services.security_center.pagers.ListSourcesPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_asset_discovery(self, + request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), + ) -> operation.Operation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS 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 securitycenter_v1 + + def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest, dict]): + The request object. Request message for running asset + discovery for an organization. + parent (str): + Required. Name of the organization to run asset + discovery for. Its format is + ``organizations/[organization_id]``. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` + Response of asset discovery run + + """ + warnings.warn("SecurityCenterClient.run_asset_discovery is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.run_asset_discovery] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + start_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of 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 securitycenter_v1 + + def sample_set_finding_state(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.SetFindingStateRequest, dict]): + The request object. Request message for updating a + finding's state. + name (str): + Required. The `relative resource + name `__ + of the finding. Example: + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, + ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (google.cloud.securitycenter_v1.types.Finding.State): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_mute(self, + request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, + *, + name: Optional[str] = None, + mute: Optional[finding.Finding.Mute] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the mute state of 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 securitycenter_v1 + + def sample_set_mute(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = client.set_mute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.SetMuteRequest, dict]): + The request object. Request message for updating a + finding's mute status. + name (str): + Required. The `relative resource + name `__ + of the finding. Example: + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, + ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute (google.cloud.securitycenter_v1.types.Finding.Mute): + Required. The desired state of the + Mute. + + This corresponds to the ``mute`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, mute]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetMuteRequest): + request = securitycenter_service.SetMuteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if mute is not None: + request.mute = mute + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_mute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # 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 + + def simulate_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_config: Optional[security_health_analytics_custom_config.CustomConfig] = None, + resource: Optional[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: + r"""Simulates a given SecurityHealthAnalyticsCustomModule + and Resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_simulate_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + resource = securitycenter_v1.SimulatedResource() + resource.resource_type = "resource_type_value" + + request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + resource=resource, + ) + + # Make the request + response = client.simulate_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]): + The request object. Request message to simulate a + CustomConfig against a given test + resource. Maximum size of the request is + 4 MB by default. + parent (str): + Required. The relative resource name of the + organization, project, or folder. For more information + about relative resource names, see `Relative Resource + Name `__ + Example: ``organizations/{organization_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_config (google.cloud.securitycenter_v1.types.CustomConfig): + Required. The custom configuration + that you need to test. + + This corresponds to the ``custom_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource): + Required. Resource data to simulate + custom module against. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse: + Response message for simulating a SecurityHealthAnalyticsCustomModule + against a given 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, custom_config, resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_config is not None: + request.custom_config = custom_config + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.simulate_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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_external_system(self, + request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, + *, + external_system: Optional[gcs_external_system.ExternalSystem] = None, + update_mask: 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]] = (), + ) -> gcs_external_system.ExternalSystem: + r"""Updates external system. This is for a given 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 securitycenter_v1 + + def sample_update_external_system(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateExternalSystemRequest( + ) + + # Make the request + response = client.update_external_system(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest, dict]): + The request object. Request message for updating a + ExternalSystem resource. + external_system (google.cloud.securitycenter_v1.types.ExternalSystem): + Required. The external system + resource to update. + + This corresponds to the ``external_system`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the external system resource. + If empty all mutable fields 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.cloud.securitycenter_v1.types.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): + request = securitycenter_service.UpdateExternalSystemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if external_system is not None: + request.external_system = external_system + 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_external_system] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("external_system.name", request.external_system.name), + )), + ) + + # Validate the universe 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_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateFindingRequest, dict]): + The request object. Request message for updating or + creating a finding. + finding (google.cloud.securitycenter_v1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe 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_mute_config(self, + request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, + *, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + update_mask: 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]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Updates a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = client.update_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest, dict]): + The request object. Request message for updating a mute + config. + mute_config (google.cloud.securitycenter_v1.types.MuteConfig): + Required. The mute config being + updated. + + This corresponds to the ``mute_config`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): + request = securitycenter_service.UpdateMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mute_config is not None: + request.mute_config = mute_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_mute_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("mute_config.name", request.mute_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 update_notification_config(self, + request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, + *, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + update_mask: 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest, dict]): + The request object. Request message for updating a + notification config. + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the notification config. + If empty all mutable fields 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.cloud.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_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 update_organization_settings(self, + request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, + *, + organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = client.update_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest, dict]): + The request object. Request message for updating an + organization's settings. + organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_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 update_security_health_analytics_custom_module(self, + request: Optional[Union[securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, + *, + security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, + update_mask: 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]] = (), + ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Updates the SecurityHealthAnalyticsCustomModule under + the given name based on the given update mask. Updating + the enablement state is supported on both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name and custom config of a module is supported + on resident modules only. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( + ) + + # Make the request + response = client.update_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]): + The request object. Request message for updating Security + Health Analytics custom modules. + security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): + Required. The SecurityHealthAnalytics + custom module to update. + + This corresponds to the ``security_health_analytics_custom_module`` 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 only fields that + can be updated are ``enablement_state`` and + ``custom_config``. If empty or set to the wildcard value + ``*``, both ``enablement_state`` and ``custom_config`` + are 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.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_health_analytics_custom_module, 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, securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_health_analytics_custom_module is not None: + request.security_health_analytics_custom_module = security_health_analytics_custom_module + 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_security_health_analytics_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_health_analytics_custom_module.name", request.security_health_analytics_custom_module.name), + )), + ) + + # Validate the universe 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_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v1 + + def sample_update_source(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateSourceRequest, dict]): + The request object. Request message for updating a + source. + source (google.cloud.securitycenter_v1.types.Source): + Required. The source resource to + update. + + This corresponds to the ``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.cloud.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_security_marks(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest, dict]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe 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_big_query_export(self, + request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, + *, + parent: Optional[str] = None, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + big_query_export_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Creates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_create_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = client.create_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest, dict]): + The request object. Request message for creating a + BigQuery export. + parent (str): + Required. The name of the parent resource of the new + BigQuery export. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): + Required. The BigQuery export being + created. + + This corresponds to the ``big_query_export`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``big_query_export_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.cloud.securitycenter_v1.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): + request = securitycenter_service.CreateBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if big_query_export is not None: + request.big_query_export = big_query_export + if big_query_export_id is not None: + request.big_query_export_id = big_query_export_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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_big_query_export(self, + request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + client.delete_big_query_export(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest, dict]): + The request object. Request message for deleting a + BigQuery export. + name (str): + Required. The name of the BigQuery export to delete. Its + format is + ``organizations/{organization}/bigQueryExports/{export_id}``, + ``folders/{folder}/bigQueryExports/{export_id}``, or + ``projects/{project}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): + request = securitycenter_service.DeleteBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + 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_big_query_export(self, + request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, + *, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + update_mask: 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]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Updates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateBigQueryExportRequest( + ) + + # Make the request + response = client.update_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest, dict]): + The request object. Request message for updating a + BigQuery export. + big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): + Required. The BigQuery export being + updated. + + This corresponds to the ``big_query_export`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): + request = securitycenter_service.UpdateBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if big_query_export is not None: + request.big_query_export = big_query_export + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("big_query_export.name", request.big_query_export.name), + )), + ) + + # Validate the universe 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_big_query_exports(self, + request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsPager: + r"""Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are 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 securitycenter_v1 + + def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest, dict]): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or project. + parent (str): + Required. The parent, which owns the collection of + BigQuery exports. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + + 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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsPager: + Response message for listing BigQuery + exports. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): + request = securitycenter_service.ListBigQueryExportsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_big_query_exports] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListBigQueryExportsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Creates a resident Event Threat Detection custom + module at the scope of the given Resource Manager + parent, and also creates inherited custom modules for + all descendants of the given parent. These modules are + enabled by default. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_create_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest, dict]): + The request object. Request to create an Event Threat + Detection custom module. + parent (str): + Required. The new custom module's parent. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): + Required. The module to create. The + event_threat_detection_custom_module.name will be + ignored and server generated. + + This corresponds to the ``event_threat_detection_custom_module`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, event_threat_detection_custom_module]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if event_threat_detection_custom_module is not None: + request.event_threat_detection_custom_module = event_threat_detection_custom_module + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, dict]] = 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 Event Threat Detection custom + module and all of its descendants in the Resource + Manager hierarchy. This method is only supported for + resident custom modules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_delete_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + client.delete_event_threat_detection_custom_module(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest, dict]): + The request object. Request to delete an Event Threat + Detection custom module. + name (str): + Required. Name of the custom module to delete. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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, securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + 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_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.GetEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Gets an Event Threat Detection custom module. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest, dict]): + The request object. Request to get an Event Threat + Detection custom module. + name (str): + Required. Name of the custom module to get. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_descendant_event_threat_detection_custom_modules(self, + request: Optional[Union[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, 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.ListDescendantEventThreatDetectionCustomModulesPager: + r"""Lists all resident Event Threat Detection custom + modules under the given Resource Manager parent and its + descendants. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_descendant_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest, dict]): + The request object. Request to list current and + descendant resident Event Threat + Detection custom modules. + parent (str): + Required. Name of the parent to list custom modules + under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + 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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesPager: + Response for listing current and + descendant resident Event Threat + Detection custom modules. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_descendant_event_threat_detection_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListDescendantEventThreatDetectionCustomModulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_event_threat_detection_custom_modules(self, + request: Optional[Union[securitycenter_service.ListEventThreatDetectionCustomModulesRequest, 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.ListEventThreatDetectionCustomModulesPager: + r"""Lists all Event Threat Detection custom modules for + the given Resource Manager parent. This includes + resident modules defined at the scope of the parent + along with modules inherited from ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_event_threat_detection_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest, dict]): + The request object. Request to list Event Threat + Detection custom modules. + parent (str): + Required. Name of the parent to list custom modules + under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + 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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesPager: + Response for listing Event Threat + Detection custom modules. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListEventThreatDetectionCustomModulesRequest): + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_event_threat_detection_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListEventThreatDetectionCustomModulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, + update_mask: 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]] = (), + ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Updates the Event Threat Detection custom module with + the given name based on the given update mask. Updating + the enablement state is supported for both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name or configuration of a module is supported + for resident modules only. The type of a module cannot + be changed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( + ) + + # Make the request + response = client.update_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest, dict]): + The request object. Request to update an Event Threat + Detection custom module. + event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): + Required. The module being updated. + This corresponds to the ``event_threat_detection_custom_module`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([event_threat_detection_custom_module, 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, securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if event_threat_detection_custom_module is not None: + request.event_threat_detection_custom_module = event_threat_detection_custom_module + 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_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("event_threat_detection_custom_module.name", request.event_threat_detection_custom_module.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def validate_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: + r"""Validates the given Event Threat Detection custom + module. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_validate_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + raw_text="raw_text_value", + type_="type__value", + ) + + # Make the request + response = client.validate_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest, dict]): + The request object. Request to validate an Event Threat + Detection custom module. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse: + Response to validating an Event + Threat Detection custom module. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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_effective_event_threat_detection_custom_module(self, + request: Optional[Union[securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: + r"""Gets an effective Event Threat Detection custom + module at the given level. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_effective_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_effective_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]): + The request object. Request to get an + EffectiveEventThreatDetectionCustomModule. + name (str): + Required. The resource name of the effective Event + Threat Detection custom module. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule: + An EffectiveEventThreatDetectionCustomModule is the representation of + an Event Threat Detection custom module at a + specified level of the resource hierarchy: + organization, folder, or project. If a custom module + is inherited from a parent organization or folder, + the value of the enablement_state property in + EffectiveEventThreatDetectionCustomModule is set to + the value that is effective in the parent, instead of + INHERITED. For example, if the module is enabled in a + parent organization or folder, the effective + enablement_state for the module in all child folders + or projects is also enabled. + EffectiveEventThreatDetectionCustomModule is + read-only. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_effective_event_threat_detection_custom_module] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_effective_event_threat_detection_custom_modules(self, + request: Optional[Union[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, 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.ListEffectiveEventThreatDetectionCustomModulesPager: + r"""Lists all effective Event Threat Detection custom + modules for the given parent. This includes resident + modules defined at the scope of the parent along with + modules inherited from its ancestors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_effective_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_event_threat_detection_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest, dict]): + The request object. Request to list effective Event + Threat Detection custom modules. + parent (str): + Required. Name of the parent to list custom modules for. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + + 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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesPager: + Response for listing + EffectiveEventThreatDetectionCustomModules. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_effective_event_threat_detection_custom_modules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListEffectiveEventThreatDetectionCustomModulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_create_resource_value_configs(self, + request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + requests = securitycenter_v1.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + requests.resource_value_config.resource_value = "NONE" + requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest, dict]): + The request object. Request message to create multiple + resource value configs + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. The parent + field in the + CreateResourceValueConfigRequest + messages must either be empty or match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]): + Required. The resource value configs + to be created. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, requests]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): + request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_resource_value_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, + ) + + # Done; return the response. + return response + + def delete_resource_value_config(self, + request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_resource_value_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest, dict]): + The request object. Request message to delete resource + value config + name (str): + Required. Name of the + ResourceValueConfig 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. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): + request = securitycenter_service.DeleteResourceValueConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_resource_value_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_resource_value_config(self, + request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource_value_config.ResourceValueConfig: + r"""Gets a ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest, dict]): + The request object. Request message to get resource value + config + name (str): + Required. Name of the resource value config to retrieve. + Its format is + ``organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v1.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): + request = securitycenter_service.GetResourceValueConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_resource_value_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_resource_value_configs(self, + request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsPager: + r"""Lists all ResourceValueConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest, dict]): + The request object. Request message to list resource + value configs of a parent + parent (str): + Required. The parent, which owns the collection of + resource value configs. Its format is + ``organizations/[organization_id]`` + + 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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsPager: + Response message to list resource + value configs + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): + request = securitycenter_service.ListResourceValueConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_resource_value_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.ListResourceValueConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_resource_value_config(self, + request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, + *, + resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, + update_mask: 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]] = (), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Updates an existing ResourceValueConfigs with new + rules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + resource_value_config = securitycenter_v1.ResourceValueConfig() + resource_value_config.resource_value = "NONE" + resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.UpdateResourceValueConfigRequest( + resource_value_config=resource_value_config, + ) + + # Make the request + response = client.update_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest, dict]): + The request object. Request message to update resource + value config + resource_value_config (google.cloud.securitycenter_v1.types.ResourceValueConfig): + Required. The resource value config + being updated. + + This corresponds to the ``resource_value_config`` 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. + If empty all mutable fields 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.cloud.securitycenter_v1.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): + request = securitycenter_service.UpdateResourceValueConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if resource_value_config is not None: + request.resource_value_config = resource_value_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_resource_value_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource_value_config.name", request.resource_value_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 list_valued_resources(self, + request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesPager: + r"""Lists the valued resources for a set of simulation + results and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_valued_resources(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListValuedResourcesRequest, dict]): + The request object. Request message for listing the + valued resources for a given simulation. + parent (str): + Required. Name of parent to list valued resources. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + + 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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesPager: + Response message for listing the + valued resources for a given simulation. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): + request = securitycenter_service.ListValuedResourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_valued_resources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListValuedResourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_attack_paths(self, + request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsPager: + r"""Lists the attack paths for a set of simulation + results or valued resources and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1 + + def sample_list_attack_paths(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1.types.ListAttackPathsRequest, dict]): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + parent (str): + Required. Name of parent to list attack paths. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + + 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.securitycenter_v1.services.security_center.pagers.ListAttackPathsPager: + Response message for listing the + attack paths for a given simulation or + valued resource. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): + request = securitycenter_service.ListAttackPathsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_attack_paths] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListAttackPathsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SecurityCenterClient": + 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 = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + 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 = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SecurityCenterClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py new file mode 100644 index 000000000000..6fb1704f990d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py @@ -0,0 +1,2333 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.securitycenter_v1.types import attack_path +from google.cloud.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import valued_resource + + +class GroupAssetsPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupAssetsResponse], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + 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[securitycenter_service.GroupAssetsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupAssetsAsyncPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` + attributes are available on the 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[securitycenter_service.GroupAssetsResponse]], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + 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[securitycenter_service.GroupAssetsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` + attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListAssetsResponse], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + 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[securitycenter_service.ListAssetsResponse]: + 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + for page in self.pages: + yield from page.list_assets_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` + attributes are available on the 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[securitycenter_service.ListAssetsResponse]], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + 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[securitycenter_service.ListAssetsResponse]: + 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_assets_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDescendantSecurityHealthAnalyticsCustomModulesPager: + """A pager for iterating through ``list_descendant_security_health_analytics_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``security_health_analytics_custom_modules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDescendantSecurityHealthAnalyticsCustomModules`` requests and continue to iterate + through the ``security_health_analytics_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse], + request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, + response: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse): + 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 = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) + 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[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: + 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + for page in self.pages: + yield from page.security_health_analytics_custom_modules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: + """A pager for iterating through ``list_descendant_security_health_analytics_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``security_health_analytics_custom_modules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDescendantSecurityHealthAnalyticsCustomModules`` requests and continue to iterate + through the ``security_health_analytics_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` + attributes are available on the 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[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]], + request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, + response: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse): + 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 = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) + 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[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: + 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + async def async_generator(): + async for page in self.pages: + for response in page.security_health_analytics_custom_modules: + 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.securitycenter_v1.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_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[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + for page in self.pages: + yield from page.list_findings_results + + 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.securitycenter_v1.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_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[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_findings_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMuteConfigsPager: + """A pager for iterating through ``list_mute_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``mute_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMuteConfigs`` requests and continue to iterate + through the ``mute_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListMuteConfigsResponse], + request: securitycenter_service.ListMuteConfigsRequest, + response: securitycenter_service.ListMuteConfigsResponse, + *, + 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.securitycenter_v1.types.ListMuteConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListMuteConfigsResponse): + 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 = securitycenter_service.ListMuteConfigsRequest(request) + 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[securitycenter_service.ListMuteConfigsResponse]: + 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[mute_config.MuteConfig]: + for page in self.pages: + yield from page.mute_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMuteConfigsAsyncPager: + """A pager for iterating through ``list_mute_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``mute_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMuteConfigs`` requests and continue to iterate + through the ``mute_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` + attributes are available on the 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[securitycenter_service.ListMuteConfigsResponse]], + request: securitycenter_service.ListMuteConfigsRequest, + response: securitycenter_service.ListMuteConfigsResponse, + *, + 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.securitycenter_v1.types.ListMuteConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListMuteConfigsResponse): + 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 = securitycenter_service.ListMuteConfigsRequest(request) + 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[securitycenter_service.ListMuteConfigsResponse]: + 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[mute_config.MuteConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.mute_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v1.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + 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[securitycenter_service.ListNotificationConfigsResponse]: + 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[notification_config.NotificationConfig]: + for page in self.pages: + yield from page.notification_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsAsyncPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` + attributes are available on the 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[securitycenter_service.ListNotificationConfigsResponse]], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v1.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + 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[securitycenter_service.ListNotificationConfigsResponse]: + 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[notification_config.NotificationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.notification_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEffectiveSecurityHealthAnalyticsCustomModulesPager: + """A pager for iterating through ``list_effective_security_health_analytics_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``effective_security_health_analytics_custom_modules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEffectiveSecurityHealthAnalyticsCustomModules`` requests and continue to iterate + through the ``effective_security_health_analytics_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse], + request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, + response: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse): + 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 = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) + 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[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: + 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[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: + for page in self.pages: + yield from page.effective_security_health_analytics_custom_modules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: + """A pager for iterating through ``list_effective_security_health_analytics_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``effective_security_health_analytics_custom_modules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEffectiveSecurityHealthAnalyticsCustomModules`` requests and continue to iterate + through the ``effective_security_health_analytics_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` + attributes are available on the 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[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]], + request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, + response: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse): + 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 = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) + 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[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: + 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[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: + async def async_generator(): + async for page in self.pages: + for response in page.effective_security_health_analytics_custom_modules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSecurityHealthAnalyticsCustomModulesPager: + """A pager for iterating through ``list_security_health_analytics_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``security_health_analytics_custom_modules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSecurityHealthAnalyticsCustomModules`` requests and continue to iterate + through the ``security_health_analytics_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse], + request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, + response: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse): + 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 = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) + 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[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: + 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + for page in self.pages: + yield from page.security_health_analytics_custom_modules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSecurityHealthAnalyticsCustomModulesAsyncPager: + """A pager for iterating through ``list_security_health_analytics_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``security_health_analytics_custom_modules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSecurityHealthAnalyticsCustomModules`` requests and continue to iterate + through the ``security_health_analytics_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` + attributes are available on the 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[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]], + request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, + response: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse): + 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 = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) + 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[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: + 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + async def async_generator(): + async for page in self.pages: + for response in page.security_health_analytics_custom_modules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` + attributes are available on the 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[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.sources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBigQueryExportsPager: + """A pager for iterating through ``list_big_query_exports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``big_query_exports`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBigQueryExports`` requests and continue to iterate + through the ``big_query_exports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListBigQueryExportsResponse], + request: securitycenter_service.ListBigQueryExportsRequest, + response: securitycenter_service.ListBigQueryExportsResponse, + *, + 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.securitycenter_v1.types.ListBigQueryExportsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse): + 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 = securitycenter_service.ListBigQueryExportsRequest(request) + 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[securitycenter_service.ListBigQueryExportsResponse]: + 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[bigquery_export.BigQueryExport]: + for page in self.pages: + yield from page.big_query_exports + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBigQueryExportsAsyncPager: + """A pager for iterating through ``list_big_query_exports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``big_query_exports`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBigQueryExports`` requests and continue to iterate + through the ``big_query_exports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` + attributes are available on the 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[securitycenter_service.ListBigQueryExportsResponse]], + request: securitycenter_service.ListBigQueryExportsRequest, + response: securitycenter_service.ListBigQueryExportsResponse, + *, + 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.securitycenter_v1.types.ListBigQueryExportsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse): + 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 = securitycenter_service.ListBigQueryExportsRequest(request) + 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[securitycenter_service.ListBigQueryExportsResponse]: + 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[bigquery_export.BigQueryExport]: + async def async_generator(): + async for page in self.pages: + for response in page.big_query_exports: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDescendantEventThreatDetectionCustomModulesPager: + """A pager for iterating through ``list_descendant_event_threat_detection_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``event_threat_detection_custom_modules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDescendantEventThreatDetectionCustomModules`` requests and continue to iterate + through the ``event_threat_detection_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse], + request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, + response: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse): + 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 = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) + 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[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: + 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + for page in self.pages: + yield from page.event_threat_detection_custom_modules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDescendantEventThreatDetectionCustomModulesAsyncPager: + """A pager for iterating through ``list_descendant_event_threat_detection_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``event_threat_detection_custom_modules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDescendantEventThreatDetectionCustomModules`` requests and continue to iterate + through the ``event_threat_detection_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` + attributes are available on the 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[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]], + request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, + response: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse): + 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 = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) + 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[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: + 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + async def async_generator(): + async for page in self.pages: + for response in page.event_threat_detection_custom_modules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEventThreatDetectionCustomModulesPager: + """A pager for iterating through ``list_event_threat_detection_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``event_threat_detection_custom_modules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEventThreatDetectionCustomModules`` requests and continue to iterate + through the ``event_threat_detection_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListEventThreatDetectionCustomModulesResponse], + request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, + response: securitycenter_service.ListEventThreatDetectionCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse): + 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 = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) + 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[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: + 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + for page in self.pages: + yield from page.event_threat_detection_custom_modules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEventThreatDetectionCustomModulesAsyncPager: + """A pager for iterating through ``list_event_threat_detection_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``event_threat_detection_custom_modules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEventThreatDetectionCustomModules`` requests and continue to iterate + through the ``event_threat_detection_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` + attributes are available on the 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[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]], + request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, + response: securitycenter_service.ListEventThreatDetectionCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse): + 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 = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) + 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[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: + 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + async def async_generator(): + async for page in self.pages: + for response in page.event_threat_detection_custom_modules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEffectiveEventThreatDetectionCustomModulesPager: + """A pager for iterating through ``list_effective_event_threat_detection_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``effective_event_threat_detection_custom_modules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEffectiveEventThreatDetectionCustomModules`` requests and continue to iterate + through the ``effective_event_threat_detection_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse], + request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, + response: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse): + 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 = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) + 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[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: + 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[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: + for page in self.pages: + yield from page.effective_event_threat_detection_custom_modules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEffectiveEventThreatDetectionCustomModulesAsyncPager: + """A pager for iterating through ``list_effective_event_threat_detection_custom_modules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``effective_event_threat_detection_custom_modules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEffectiveEventThreatDetectionCustomModules`` requests and continue to iterate + through the ``effective_event_threat_detection_custom_modules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` + attributes are available on the 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[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]], + request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, + response: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse, + *, + 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.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse): + 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 = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) + 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[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: + 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[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: + async def async_generator(): + async for page in self.pages: + for response in page.effective_event_threat_detection_custom_modules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourceValueConfigsPager: + """A pager for iterating through ``list_resource_value_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resource_value_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListResourceValueConfigs`` requests and continue to iterate + through the ``resource_value_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListResourceValueConfigsResponse], + request: securitycenter_service.ListResourceValueConfigsRequest, + response: securitycenter_service.ListResourceValueConfigsResponse, + *, + 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.securitycenter_v1.types.ListResourceValueConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse): + 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 = securitycenter_service.ListResourceValueConfigsRequest(request) + 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[securitycenter_service.ListResourceValueConfigsResponse]: + 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[resource_value_config.ResourceValueConfig]: + for page in self.pages: + yield from page.resource_value_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourceValueConfigsAsyncPager: + """A pager for iterating through ``list_resource_value_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resource_value_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListResourceValueConfigs`` requests and continue to iterate + through the ``resource_value_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` + attributes are available on the 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[securitycenter_service.ListResourceValueConfigsResponse]], + request: securitycenter_service.ListResourceValueConfigsRequest, + response: securitycenter_service.ListResourceValueConfigsResponse, + *, + 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.securitycenter_v1.types.ListResourceValueConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse): + 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 = securitycenter_service.ListResourceValueConfigsRequest(request) + 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[securitycenter_service.ListResourceValueConfigsResponse]: + 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[resource_value_config.ResourceValueConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.resource_value_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListValuedResourcesPager: + """A pager for iterating through ``list_valued_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``valued_resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListValuedResources`` requests and continue to iterate + through the ``valued_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListValuedResourcesResponse], + request: securitycenter_service.ListValuedResourcesRequest, + response: securitycenter_service.ListValuedResourcesResponse, + *, + 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.securitycenter_v1.types.ListValuedResourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListValuedResourcesResponse): + 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 = securitycenter_service.ListValuedResourcesRequest(request) + 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[securitycenter_service.ListValuedResourcesResponse]: + 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[valued_resource.ValuedResource]: + for page in self.pages: + yield from page.valued_resources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListValuedResourcesAsyncPager: + """A pager for iterating through ``list_valued_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``valued_resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListValuedResources`` requests and continue to iterate + through the ``valued_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` + attributes are available on the 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[securitycenter_service.ListValuedResourcesResponse]], + request: securitycenter_service.ListValuedResourcesRequest, + response: securitycenter_service.ListValuedResourcesResponse, + *, + 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.securitycenter_v1.types.ListValuedResourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListValuedResourcesResponse): + 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 = securitycenter_service.ListValuedResourcesRequest(request) + 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[securitycenter_service.ListValuedResourcesResponse]: + 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[valued_resource.ValuedResource]: + async def async_generator(): + async for page in self.pages: + for response in page.valued_resources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAttackPathsPager: + """A pager for iterating through ``list_attack_paths`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``attack_paths`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAttackPaths`` requests and continue to iterate + through the ``attack_paths`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListAttackPathsResponse], + request: securitycenter_service.ListAttackPathsRequest, + response: securitycenter_service.ListAttackPathsResponse, + *, + 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.securitycenter_v1.types.ListAttackPathsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListAttackPathsResponse): + 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 = securitycenter_service.ListAttackPathsRequest(request) + 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[securitycenter_service.ListAttackPathsResponse]: + 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[attack_path.AttackPath]: + for page in self.pages: + yield from page.attack_paths + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAttackPathsAsyncPager: + """A pager for iterating through ``list_attack_paths`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``attack_paths`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAttackPaths`` requests and continue to iterate + through the ``attack_paths`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` + attributes are available on the 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[securitycenter_service.ListAttackPathsResponse]], + request: securitycenter_service.ListAttackPathsRequest, + response: securitycenter_service.ListAttackPathsResponse, + *, + 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.securitycenter_v1.types.ListAttackPathsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListAttackPathsResponse): + 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 = securitycenter_service.ListAttackPathsRequest(request) + 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[securitycenter_service.ListAttackPathsResponse]: + 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[attack_path.AttackPath]: + async def async_generator(): + async for page in self.pages: + for response in page.attack_paths: + 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-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py new file mode 100644 index 000000000000..9d36139c1a9b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/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 SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .rest import SecurityCenterRestTransport +from .rest import SecurityCenterRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry['grpc'] = SecurityCenterGrpcTransport +_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport +_transport_registry['rest'] = SecurityCenterRestTransport + +__all__ = ( + 'SecurityCenterTransport', + 'SecurityCenterGrpcTransport', + 'SecurityCenterGrpcAsyncIOTransport', + 'SecurityCenterRestTransport', + 'SecurityCenterRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py new file mode 100644 index 000000000000..0e98676ba56d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py @@ -0,0 +1,1251 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.securitycenter_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.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import valued_resource +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 empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'securitycenter.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.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: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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.bulk_mute_findings: gapic_v1.method.wrap_method( + self.bulk_mute_findings, + default_timeout=None, + client_info=client_info, + ), + self.create_security_health_analytics_custom_module: gapic_v1.method.wrap_method( + self.create_security_health_analytics_custom_module, + default_timeout=60.0, + client_info=client_info, + ), + self.create_source: gapic_v1.method.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.create_mute_config: gapic_v1.method.wrap_method( + self.create_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method.wrap_method( + self.create_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_mute_config: gapic_v1.method.wrap_method( + self.delete_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method.wrap_method( + self.delete_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_security_health_analytics_custom_module: gapic_v1.method.wrap_method( + self.delete_security_health_analytics_custom_module, + default_timeout=60.0, + client_info=client_info, + ), + self.get_simulation: gapic_v1.method.wrap_method( + self.get_simulation, + default_timeout=None, + client_info=client_info, + ), + self.get_valued_resource: gapic_v1.method.wrap_method( + self.get_valued_resource, + default_timeout=None, + client_info=client_info, + ), + self.get_big_query_export: gapic_v1.method.wrap_method( + self.get_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_mute_config: gapic_v1.method.wrap_method( + self.get_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.get_notification_config: gapic_v1.method.wrap_method( + self.get_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_settings: gapic_v1.method.wrap_method( + self.get_organization_settings, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_effective_security_health_analytics_custom_module: gapic_v1.method.wrap_method( + self.get_effective_security_health_analytics_custom_module, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_security_health_analytics_custom_module: gapic_v1.method.wrap_method( + self.get_security_health_analytics_custom_module, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_source: gapic_v1.method.wrap_method( + self.get_source, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.group_assets: gapic_v1.method.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_descendant_security_health_analytics_custom_modules: gapic_v1.method.wrap_method( + self.list_descendant_security_health_analytics_custom_modules, + 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=60.0, + ), + default_timeout=60.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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_mute_configs: gapic_v1.method.wrap_method( + self.list_mute_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method.wrap_method( + self.list_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_effective_security_health_analytics_custom_modules: gapic_v1.method.wrap_method( + self.list_effective_security_health_analytics_custom_modules, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_security_health_analytics_custom_modules: gapic_v1.method.wrap_method( + self.list_security_health_analytics_custom_modules, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_sources: gapic_v1.method.wrap_method( + self.list_sources, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.run_asset_discovery: gapic_v1.method.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_mute: gapic_v1.method.wrap_method( + self.set_mute, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.simulate_security_health_analytics_custom_module: gapic_v1.method.wrap_method( + self.simulate_security_health_analytics_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.update_external_system: gapic_v1.method.wrap_method( + self.update_external_system, + default_timeout=None, + client_info=client_info, + ), + self.update_finding: gapic_v1.method.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_mute_config: gapic_v1.method.wrap_method( + self.update_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method.wrap_method( + self.update_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_health_analytics_custom_module: gapic_v1.method.wrap_method( + self.update_security_health_analytics_custom_module, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=client_info, + ), + self.create_big_query_export: gapic_v1.method.wrap_method( + self.create_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.delete_big_query_export: gapic_v1.method.wrap_method( + self.delete_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.update_big_query_export: gapic_v1.method.wrap_method( + self.update_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.list_big_query_exports: gapic_v1.method.wrap_method( + self.list_big_query_exports, + default_timeout=None, + client_info=client_info, + ), + self.create_event_threat_detection_custom_module: gapic_v1.method.wrap_method( + self.create_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.delete_event_threat_detection_custom_module: gapic_v1.method.wrap_method( + self.delete_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.get_event_threat_detection_custom_module: gapic_v1.method.wrap_method( + self.get_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.list_descendant_event_threat_detection_custom_modules: gapic_v1.method.wrap_method( + self.list_descendant_event_threat_detection_custom_modules, + default_timeout=None, + client_info=client_info, + ), + self.list_event_threat_detection_custom_modules: gapic_v1.method.wrap_method( + self.list_event_threat_detection_custom_modules, + default_timeout=None, + client_info=client_info, + ), + self.update_event_threat_detection_custom_module: gapic_v1.method.wrap_method( + self.update_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.validate_event_threat_detection_custom_module: gapic_v1.method.wrap_method( + self.validate_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.get_effective_event_threat_detection_custom_module: gapic_v1.method.wrap_method( + self.get_effective_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.list_effective_event_threat_detection_custom_modules: gapic_v1.method.wrap_method( + self.list_effective_event_threat_detection_custom_modules, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_resource_value_configs: gapic_v1.method.wrap_method( + self.batch_create_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.delete_resource_value_config: gapic_v1.method.wrap_method( + self.delete_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_resource_value_config: gapic_v1.method.wrap_method( + self.get_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.list_resource_value_configs: gapic_v1.method.wrap_method( + self.list_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_resource_value_config: gapic_v1.method.wrap_method( + self.update_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.list_valued_resources: gapic_v1.method.wrap_method( + self.list_valued_resources, + default_timeout=None, + client_info=client_info, + ), + self.list_attack_paths: gapic_v1.method.wrap_method( + self.list_attack_paths, + 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 bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], + Union[ + gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] + ]]: + raise NotImplementedError() + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + Union[ + gcs_mute_config.MuteConfig, + Awaitable[gcs_mute_config.MuteConfig] + ]]: + raise NotImplementedError() + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def delete_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + Union[ + simulation.Simulation, + Awaitable[simulation.Simulation] + ]]: + raise NotImplementedError() + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + Union[ + valued_resource.ValuedResource, + Awaitable[valued_resource.ValuedResource] + ]]: + raise NotImplementedError() + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, + Awaitable[bigquery_export.BigQueryExport] + ]]: + 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 get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + Union[ + mute_config.MuteConfig, + Awaitable[mute_config.MuteConfig] + ]]: + raise NotImplementedError() + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Union[ + notification_config.NotificationConfig, + Awaitable[notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Union[ + organization_settings.OrganizationSettings, + Awaitable[organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def get_effective_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], + Union[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule, + Awaitable[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule] + ]]: + raise NotImplementedError() + + @property + def get_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], + Union[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + Awaitable[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] + ]]: + raise NotImplementedError() + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Union[ + source.Source, + Awaitable[source.Source] + ]]: + raise NotImplementedError() + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Union[ + securitycenter_service.GroupAssetsResponse, + Awaitable[securitycenter_service.GroupAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Union[ + securitycenter_service.GroupFindingsResponse, + Awaitable[securitycenter_service.GroupFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Union[ + securitycenter_service.ListAssetsResponse, + Awaitable[securitycenter_service.ListAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], + Union[ + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse, + Awaitable[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Union[ + securitycenter_service.ListFindingsResponse, + Awaitable[securitycenter_service.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + Union[ + securitycenter_service.ListMuteConfigsResponse, + Awaitable[securitycenter_service.ListMuteConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Union[ + securitycenter_service.ListNotificationConfigsResponse, + Awaitable[securitycenter_service.ListNotificationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_effective_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], + Union[ + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, + Awaitable[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse] + ]]: + raise NotImplementedError() + + @property + def list_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], + Union[ + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse, + Awaitable[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse] + ]]: + raise NotImplementedError() + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Union[ + securitycenter_service.ListSourcesResponse, + Awaitable[securitycenter_service.ListSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + raise NotImplementedError() + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + 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 test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + @property + def simulate_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], + Union[ + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse, + Awaitable[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse] + ]]: + raise NotImplementedError() + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + Union[ + gcs_external_system.ExternalSystem, + Awaitable[gcs_external_system.ExternalSystem] + ]]: + raise NotImplementedError() + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + Union[ + gcs_mute_config.MuteConfig, + Awaitable[gcs_mute_config.MuteConfig] + ]]: + raise NotImplementedError() + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Union[ + gcs_organization_settings.OrganizationSettings, + Awaitable[gcs_organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def update_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], + Union[ + gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] + ]]: + raise NotImplementedError() + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Union[ + gcs_security_marks.SecurityMarks, + Awaitable[gcs_security_marks.SecurityMarks] + ]]: + raise NotImplementedError() + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, + Awaitable[bigquery_export.BigQueryExport] + ]]: + raise NotImplementedError() + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, + Awaitable[bigquery_export.BigQueryExport] + ]]: + raise NotImplementedError() + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + Union[ + securitycenter_service.ListBigQueryExportsResponse, + Awaitable[securitycenter_service.ListBigQueryExportsResponse] + ]]: + raise NotImplementedError() + + @property + def create_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], + Union[ + gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, + Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] + ]]: + raise NotImplementedError() + + @property + def delete_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], + Union[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule, + Awaitable[event_threat_detection_custom_module.EventThreatDetectionCustomModule] + ]]: + raise NotImplementedError() + + @property + def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], + Union[ + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse, + Awaitable[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse] + ]]: + raise NotImplementedError() + + @property + def list_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], + Union[ + securitycenter_service.ListEventThreatDetectionCustomModulesResponse, + Awaitable[securitycenter_service.ListEventThreatDetectionCustomModulesResponse] + ]]: + raise NotImplementedError() + + @property + def update_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], + Union[ + gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, + Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] + ]]: + raise NotImplementedError() + + @property + def validate_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], + Union[ + securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse, + Awaitable[securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse] + ]]: + raise NotImplementedError() + + @property + def get_effective_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], + Union[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule, + Awaitable[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule] + ]]: + raise NotImplementedError() + + @property + def list_effective_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], + Union[ + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse, + Awaitable[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse] + ]]: + raise NotImplementedError() + + @property + def batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + Union[ + securitycenter_service.BatchCreateResourceValueConfigsResponse, + Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + Union[ + resource_value_config.ResourceValueConfig, + Awaitable[resource_value_config.ResourceValueConfig] + ]]: + raise NotImplementedError() + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + Union[ + securitycenter_service.ListResourceValueConfigsResponse, + Awaitable[securitycenter_service.ListResourceValueConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + Union[ + gcs_resource_value_config.ResourceValueConfig, + Awaitable[gcs_resource_value_config.ResourceValueConfig] + ]]: + raise NotImplementedError() + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + Union[ + securitycenter_service.ListValuedResourcesResponse, + Awaitable[securitycenter_service.ListValuedResourcesResponse] + ]]: + raise NotImplementedError() + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + Union[ + securitycenter_service.ListAttackPathsResponse, + Awaitable[securitycenter_service.ListAttackPathsResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SecurityCenterTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py new file mode 100644 index 000000000000..a8d1ee71ce17 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py @@ -0,0 +1,2103 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import valued_resource +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 empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V1 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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 bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + operations_pb2.Operation]: + r"""Return a callable for the bulk mute findings method over gRPC. + + Kicks off an LRO to bulk mute findings for a parent + based on a filter. The parent can be either an + organization, folder or project. The findings matched by + the filter will be muted after the LRO is done. + + Returns: + Callable[[~.BulkMuteFindingsRequest], + ~.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 'bulk_mute_findings' not in self._stubs: + self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/BulkMuteFindings', + request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['bulk_mute_findings'] + + @property + def create_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], + gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + r"""Return a callable for the create security health + analytics custom module method over gRPC. + + Creates a resident + SecurityHealthAnalyticsCustomModule at the scope of the + given CRM parent, and also creates inherited + SecurityHealthAnalyticsCustomModules for all CRM + descendants of the given parent. These modules are + enabled by default. + + Returns: + Callable[[~.CreateSecurityHealthAnalyticsCustomModuleRequest], + ~.SecurityHealthAnalyticsCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: + self._stubs['create_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['create_security_health_analytics_custom_module'] + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + r"""Return a callable for the create mute config method over gRPC. + + Creates a mute config. + + Returns: + Callable[[~.CreateMuteConfigRequest], + ~.MuteConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateMuteConfig', + request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['create_mute_config'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete mute config method over gRPC. + + Deletes an existing mute config. + + Returns: + Callable[[~.DeleteMuteConfigRequest], + ~.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_mute_config' not in self._stubs: + self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteMuteConfig', + request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_mute_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + ~.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_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @property + def delete_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete security health + analytics custom module method over gRPC. + + Deletes the specified + SecurityHealthAnalyticsCustomModule and all of its + descendants in the CRM hierarchy. This method is only + supported for resident custom modules. + + Returns: + Callable[[~.DeleteSecurityHealthAnalyticsCustomModuleRequest], + ~.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_security_health_analytics_custom_module' not in self._stubs: + self._stubs['delete_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_security_health_analytics_custom_module'] + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + simulation.Simulation]: + r"""Return a callable for the get simulation method over gRPC. + + Get the simulation by name or the latest simulation + for the given organization. + + Returns: + Callable[[~.GetSimulationRequest], + ~.Simulation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_simulation' not in self._stubs: + self._stubs['get_simulation'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSimulation', + request_serializer=securitycenter_service.GetSimulationRequest.serialize, + response_deserializer=simulation.Simulation.deserialize, + ) + return self._stubs['get_simulation'] + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + valued_resource.ValuedResource]: + r"""Return a callable for the get valued resource method over gRPC. + + Get the valued resource by name + + Returns: + Callable[[~.GetValuedResourceRequest], + ~.ValuedResource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_valued_resource' not in self._stubs: + self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetValuedResource', + request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, + response_deserializer=valued_resource.ValuedResource.deserialize, + ) + return self._stubs['get_valued_resource'] + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + bigquery_export.BigQueryExport]: + r"""Return a callable for the get big query export method over gRPC. + + Gets a BigQuery export. + + Returns: + Callable[[~.GetBigQueryExportRequest], + ~.BigQueryExport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_big_query_export' not in self._stubs: + self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetBigQueryExport', + request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['get_big_query_export'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + mute_config.MuteConfig]: + r"""Return a callable for the get mute config method over gRPC. + + Gets a mute config. + + Returns: + Callable[[~.GetMuteConfigRequest], + ~.MuteConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_mute_config' not in self._stubs: + self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetMuteConfig', + request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, + response_deserializer=mute_config.MuteConfig.deserialize, + ) + return self._stubs['get_mute_config'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_effective_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: + r"""Return a callable for the get effective security health + analytics custom module method over gRPC. + + Retrieves an + EffectiveSecurityHealthAnalyticsCustomModule. + + Returns: + Callable[[~.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], + ~.EffectiveSecurityHealthAnalyticsCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_effective_security_health_analytics_custom_module' not in self._stubs: + self._stubs['get_effective_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['get_effective_security_health_analytics_custom_module'] + + @property + def get_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + r"""Return a callable for the get security health analytics + custom module method over gRPC. + + Retrieves a SecurityHealthAnalyticsCustomModule. + + Returns: + Callable[[~.GetSecurityHealthAnalyticsCustomModuleRequest], + ~.SecurityHealthAnalyticsCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_security_health_analytics_custom_module' not in self._stubs: + self._stubs['get_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['get_security_health_analytics_custom_module'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + ~.GroupAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: + r"""Return a callable for the list descendant security + health analytics custom modules method over gRPC. + + Returns a list of all resident + SecurityHealthAnalyticsCustomModules under the given CRM + parent and all of the parent’s CRM descendants. + + Returns: + Callable[[~.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], + ~.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_descendant_security_health_analytics_custom_modules' not in self._stubs: + self._stubs['list_descendant_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantSecurityHealthAnalyticsCustomModules', + request_serializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.deserialize, + ) + return self._stubs['list_descendant_security_health_analytics_custom_modules'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + 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.securitycenter.v1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + securitycenter_service.ListMuteConfigsResponse]: + r"""Return a callable for the list mute configs method over gRPC. + + Lists mute configs. + + Returns: + Callable[[~.ListMuteConfigsRequest], + ~.ListMuteConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_mute_configs' not in self._stubs: + self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListMuteConfigs', + request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, + ) + return self._stubs['list_mute_configs'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + ~.ListNotificationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_effective_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: + r"""Return a callable for the list effective security health + analytics custom modules method over gRPC. + + Returns a list of all + EffectiveSecurityHealthAnalyticsCustomModules for the + given parent. This includes resident modules defined at + the scope of the parent, and inherited modules, + inherited from CRM ancestors. + + Returns: + Callable[[~.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], + ~.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_effective_security_health_analytics_custom_modules' not in self._stubs: + self._stubs['list_effective_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveSecurityHealthAnalyticsCustomModules', + request_serializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.deserialize, + ) + return self._stubs['list_effective_security_health_analytics_custom_modules'] + + @property + def list_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: + r"""Return a callable for the list security health analytics + custom modules method over gRPC. + + Returns a list of all + SecurityHealthAnalyticsCustomModules for the given + parent. This includes resident modules defined at the + scope of the parent, and inherited modules, inherited + from CRM ancestors. + + Returns: + Callable[[~.ListSecurityHealthAnalyticsCustomModulesRequest], + ~.ListSecurityHealthAnalyticsCustomModulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_security_health_analytics_custom_modules' not in self._stubs: + self._stubs['list_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListSecurityHealthAnalyticsCustomModules', + request_serializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.deserialize, + ) + return self._stubs['list_security_health_analytics_custom_modules'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + operations_pb2.Operation]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + ~.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 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + ~.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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + finding.Finding]: + r"""Return a callable for the set mute method over gRPC. + + Updates the mute state of a finding. + + Returns: + Callable[[~.SetMuteRequest], + ~.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 'set_mute' not in self._stubs: + self._stubs['set_mute'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SetMute', + request_serializer=securitycenter_service.SetMuteRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_mute'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def simulate_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse]: + r"""Return a callable for the simulate security health + analytics custom module method over gRPC. + + Simulates a given SecurityHealthAnalyticsCustomModule + and Resource. + + Returns: + Callable[[~.SimulateSecurityHealthAnalyticsCustomModuleRequest], + ~.SimulateSecurityHealthAnalyticsCustomModuleResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'simulate_security_health_analytics_custom_module' not in self._stubs: + self._stubs['simulate_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SimulateSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.deserialize, + ) + return self._stubs['simulate_security_health_analytics_custom_module'] + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + gcs_external_system.ExternalSystem]: + r"""Return a callable for the update external system method over gRPC. + + Updates external system. This is for a given finding. + + Returns: + Callable[[~.UpdateExternalSystemRequest], + ~.ExternalSystem]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_external_system' not in self._stubs: + self._stubs['update_external_system'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateExternalSystem', + request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, + response_deserializer=gcs_external_system.ExternalSystem.deserialize, + ) + return self._stubs['update_external_system'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + r"""Return a callable for the update mute config method over gRPC. + + Updates a mute config. + + Returns: + Callable[[~.UpdateMuteConfigRequest], + ~.MuteConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateMuteConfig', + request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['update_mute_config'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], + gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + r"""Return a callable for the update security health + analytics custom module method over gRPC. + + Updates the SecurityHealthAnalyticsCustomModule under + the given name based on the given update mask. Updating + the enablement state is supported on both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name and custom config of a module is supported + on resident modules only. + + Returns: + Callable[[~.UpdateSecurityHealthAnalyticsCustomModuleRequest], + ~.SecurityHealthAnalyticsCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: + self._stubs['update_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['update_security_health_analytics_custom_module'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + r"""Return a callable for the create big query export method over gRPC. + + Creates a BigQuery export. + + Returns: + Callable[[~.CreateBigQueryExportRequest], + ~.BigQueryExport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateBigQueryExport', + request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['create_big_query_export'] + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete big query export method over gRPC. + + Deletes an existing BigQuery export. + + Returns: + Callable[[~.DeleteBigQueryExportRequest], + ~.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_big_query_export' not in self._stubs: + self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteBigQueryExport', + request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_big_query_export'] + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + r"""Return a callable for the update big query export method over gRPC. + + Updates a BigQuery export. + + Returns: + Callable[[~.UpdateBigQueryExportRequest], + ~.BigQueryExport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateBigQueryExport', + request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['update_big_query_export'] + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + securitycenter_service.ListBigQueryExportsResponse]: + r"""Return a callable for the list big query exports method over gRPC. + + Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are returned. + + Returns: + Callable[[~.ListBigQueryExportsRequest], + ~.ListBigQueryExportsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_big_query_exports' not in self._stubs: + self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListBigQueryExports', + request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, + response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, + ) + return self._stubs['list_big_query_exports'] + + @property + def create_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], + gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + r"""Return a callable for the create event threat detection + custom module method over gRPC. + + Creates a resident Event Threat Detection custom + module at the scope of the given Resource Manager + parent, and also creates inherited custom modules for + all descendants of the given parent. These modules are + enabled by default. + + Returns: + Callable[[~.CreateEventThreatDetectionCustomModuleRequest], + ~.EventThreatDetectionCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['create_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['create_event_threat_detection_custom_module'] + + @property + def delete_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete event threat detection + custom module method over gRPC. + + Deletes the specified Event Threat Detection custom + module and all of its descendants in the Resource + Manager hierarchy. This method is only supported for + resident custom modules. + + Returns: + Callable[[~.DeleteEventThreatDetectionCustomModuleRequest], + ~.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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['delete_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_event_threat_detection_custom_module'] + + @property + def get_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], + event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + r"""Return a callable for the get event threat detection + custom module method over gRPC. + + Gets an Event Threat Detection custom module. + + Returns: + Callable[[~.GetEventThreatDetectionCustomModuleRequest], + ~.EventThreatDetectionCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_event_threat_detection_custom_module' not in self._stubs: + self._stubs['get_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.GetEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['get_event_threat_detection_custom_module'] + + @property + def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: + r"""Return a callable for the list descendant event threat + detection custom modules method over gRPC. + + Lists all resident Event Threat Detection custom + modules under the given Resource Manager parent and its + descendants. + + Returns: + Callable[[~.ListDescendantEventThreatDetectionCustomModulesRequest], + ~.ListDescendantEventThreatDetectionCustomModulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_descendant_event_threat_detection_custom_modules' not in self._stubs: + self._stubs['list_descendant_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantEventThreatDetectionCustomModules', + request_serializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.deserialize, + ) + return self._stubs['list_descendant_event_threat_detection_custom_modules'] + + @property + def list_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], + securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: + r"""Return a callable for the list event threat detection + custom modules method over gRPC. + + Lists all Event Threat Detection custom modules for + the given Resource Manager parent. This includes + resident modules defined at the scope of the parent + along with modules inherited from ancestors. + + Returns: + Callable[[~.ListEventThreatDetectionCustomModulesRequest], + ~.ListEventThreatDetectionCustomModulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_event_threat_detection_custom_modules' not in self._stubs: + self._stubs['list_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListEventThreatDetectionCustomModules', + request_serializer=securitycenter_service.ListEventThreatDetectionCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListEventThreatDetectionCustomModulesResponse.deserialize, + ) + return self._stubs['list_event_threat_detection_custom_modules'] + + @property + def update_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], + gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + r"""Return a callable for the update event threat detection + custom module method over gRPC. + + Updates the Event Threat Detection custom module with + the given name based on the given update mask. Updating + the enablement state is supported for both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name or configuration of a module is supported + for resident modules only. The type of a module cannot + be changed. + + Returns: + Callable[[~.UpdateEventThreatDetectionCustomModuleRequest], + ~.EventThreatDetectionCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['update_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['update_event_threat_detection_custom_module'] + + @property + def validate_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], + securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse]: + r"""Return a callable for the validate event threat + detection custom module method over gRPC. + + Validates the given Event Threat Detection custom + module. + + Returns: + Callable[[~.ValidateEventThreatDetectionCustomModuleRequest], + ~.ValidateEventThreatDetectionCustomModuleResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['validate_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ValidateEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.deserialize, + ) + return self._stubs['validate_event_threat_detection_custom_module'] + + @property + def get_effective_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: + r"""Return a callable for the get effective event threat + detection custom module method over gRPC. + + Gets an effective Event Threat Detection custom + module at the given level. + + Returns: + Callable[[~.GetEffectiveEventThreatDetectionCustomModuleRequest], + ~.EffectiveEventThreatDetectionCustomModule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_effective_event_threat_detection_custom_module' not in self._stubs: + self._stubs['get_effective_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['get_effective_event_threat_detection_custom_module'] + + @property + def list_effective_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: + r"""Return a callable for the list effective event threat + detection custom modules method over gRPC. + + Lists all effective Event Threat Detection custom + modules for the given parent. This includes resident + modules defined at the scope of the parent along with + modules inherited from its ancestors. + + Returns: + Callable[[~.ListEffectiveEventThreatDetectionCustomModulesRequest], + ~.ListEffectiveEventThreatDetectionCustomModulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_effective_event_threat_detection_custom_modules' not in self._stubs: + self._stubs['list_effective_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveEventThreatDetectionCustomModules', + request_serializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.deserialize, + ) + return self._stubs['list_effective_event_threat_detection_custom_modules'] + + @property + def batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + securitycenter_service.BatchCreateResourceValueConfigsResponse]: + r"""Return a callable for the batch create resource value + configs method over gRPC. + + Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + Returns: + Callable[[~.BatchCreateResourceValueConfigsRequest], + ~.BatchCreateResourceValueConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: + self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/BatchCreateResourceValueConfigs', + request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, + ) + return self._stubs['batch_create_resource_value_configs'] + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete resource value config method over gRPC. + + Deletes a ResourceValueConfig. + + Returns: + Callable[[~.DeleteResourceValueConfigRequest], + ~.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_resource_value_config' not in self._stubs: + self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteResourceValueConfig', + request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_resource_value_config'] + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + resource_value_config.ResourceValueConfig]: + r"""Return a callable for the get resource value config method over gRPC. + + Gets a ResourceValueConfig. + + Returns: + Callable[[~.GetResourceValueConfigRequest], + ~.ResourceValueConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_resource_value_config' not in self._stubs: + self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetResourceValueConfig', + request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, + response_deserializer=resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['get_resource_value_config'] + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + securitycenter_service.ListResourceValueConfigsResponse]: + r"""Return a callable for the list resource value configs method over gRPC. + + Lists all ResourceValueConfigs. + + Returns: + Callable[[~.ListResourceValueConfigsRequest], + ~.ListResourceValueConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_resource_value_configs' not in self._stubs: + self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListResourceValueConfigs', + request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, + ) + return self._stubs['list_resource_value_configs'] + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + gcs_resource_value_config.ResourceValueConfig]: + r"""Return a callable for the update resource value config method over gRPC. + + Updates an existing ResourceValueConfigs with new + rules. + + Returns: + Callable[[~.UpdateResourceValueConfigRequest], + ~.ResourceValueConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: + self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateResourceValueConfig', + request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, + response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['update_resource_value_config'] + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + securitycenter_service.ListValuedResourcesResponse]: + r"""Return a callable for the list valued resources method over gRPC. + + Lists the valued resources for a set of simulation + results and filter. + + Returns: + Callable[[~.ListValuedResourcesRequest], + ~.ListValuedResourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_valued_resources' not in self._stubs: + self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListValuedResources', + request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, + response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, + ) + return self._stubs['list_valued_resources'] + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + securitycenter_service.ListAttackPathsResponse]: + r"""Return a callable for the list attack paths method over gRPC. + + Lists the attack paths for a set of simulation + results or valued resources and filter. + + Returns: + Callable[[~.ListAttackPathsRequest], + ~.ListAttackPathsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_attack_paths' not in self._stubs: + self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListAttackPaths', + request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, + response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, + ) + return self._stubs['list_attack_paths'] + + 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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SecurityCenterGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 000000000000..9e0a84336159 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,2583 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import valued_resource +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 empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V1 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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._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 bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the bulk mute findings method over gRPC. + + Kicks off an LRO to bulk mute findings for a parent + based on a filter. The parent can be either an + organization, folder or project. The findings matched by + the filter will be muted after the LRO is done. + + Returns: + Callable[[~.BulkMuteFindingsRequest], + 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 'bulk_mute_findings' not in self._stubs: + self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/BulkMuteFindings', + request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['bulk_mute_findings'] + + @property + def create_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]]: + r"""Return a callable for the create security health + analytics custom module method over gRPC. + + Creates a resident + SecurityHealthAnalyticsCustomModule at the scope of the + given CRM parent, and also creates inherited + SecurityHealthAnalyticsCustomModules for all CRM + descendants of the given parent. These modules are + enabled by default. + + Returns: + Callable[[~.CreateSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[~.SecurityHealthAnalyticsCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: + self._stubs['create_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['create_security_health_analytics_custom_module'] + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + 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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + Awaitable[gcs_mute_config.MuteConfig]]: + r"""Return a callable for the create mute config method over gRPC. + + Creates a mute config. + + Returns: + Callable[[~.CreateMuteConfigRequest], + Awaitable[~.MuteConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateMuteConfig', + request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['create_mute_config'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete mute config method over gRPC. + + Deletes an existing mute config. + + Returns: + Callable[[~.DeleteMuteConfigRequest], + 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_mute_config' not in self._stubs: + self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteMuteConfig', + request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_mute_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + 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_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @property + def delete_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete security health + analytics custom module method over gRPC. + + Deletes the specified + SecurityHealthAnalyticsCustomModule and all of its + descendants in the CRM hierarchy. This method is only + supported for resident custom modules. + + Returns: + Callable[[~.DeleteSecurityHealthAnalyticsCustomModuleRequest], + 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_security_health_analytics_custom_module' not in self._stubs: + self._stubs['delete_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_security_health_analytics_custom_module'] + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + Awaitable[simulation.Simulation]]: + r"""Return a callable for the get simulation method over gRPC. + + Get the simulation by name or the latest simulation + for the given organization. + + Returns: + Callable[[~.GetSimulationRequest], + Awaitable[~.Simulation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_simulation' not in self._stubs: + self._stubs['get_simulation'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSimulation', + request_serializer=securitycenter_service.GetSimulationRequest.serialize, + response_deserializer=simulation.Simulation.deserialize, + ) + return self._stubs['get_simulation'] + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + Awaitable[valued_resource.ValuedResource]]: + r"""Return a callable for the get valued resource method over gRPC. + + Get the valued resource by name + + Returns: + Callable[[~.GetValuedResourceRequest], + Awaitable[~.ValuedResource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_valued_resource' not in self._stubs: + self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetValuedResource', + request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, + response_deserializer=valued_resource.ValuedResource.deserialize, + ) + return self._stubs['get_valued_resource'] + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport]]: + r"""Return a callable for the get big query export method over gRPC. + + Gets a BigQuery export. + + Returns: + Callable[[~.GetBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_big_query_export' not in self._stubs: + self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetBigQueryExport', + request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['get_big_query_export'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + Awaitable[mute_config.MuteConfig]]: + r"""Return a callable for the get mute config method over gRPC. + + Gets a mute config. + + Returns: + Callable[[~.GetMuteConfigRequest], + Awaitable[~.MuteConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_mute_config' not in self._stubs: + self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetMuteConfig', + request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, + response_deserializer=mute_config.MuteConfig.deserialize, + ) + return self._stubs['get_mute_config'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Awaitable[notification_config.NotificationConfig]]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Awaitable[organization_settings.OrganizationSettings]]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_effective_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]]: + r"""Return a callable for the get effective security health + analytics custom module method over gRPC. + + Retrieves an + EffectiveSecurityHealthAnalyticsCustomModule. + + Returns: + Callable[[~.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[~.EffectiveSecurityHealthAnalyticsCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_effective_security_health_analytics_custom_module' not in self._stubs: + self._stubs['get_effective_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['get_effective_security_health_analytics_custom_module'] + + @property + def get_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]]: + r"""Return a callable for the get security health analytics + custom module method over gRPC. + + Retrieves a SecurityHealthAnalyticsCustomModule. + + Returns: + Callable[[~.GetSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[~.SecurityHealthAnalyticsCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_security_health_analytics_custom_module' not in self._stubs: + self._stubs['get_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['get_security_health_analytics_custom_module'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Awaitable[securitycenter_service.GroupAssetsResponse]]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + Awaitable[~.GroupAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse]]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Awaitable[securitycenter_service.ListAssetsResponse]]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], + Awaitable[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]]: + r"""Return a callable for the list descendant security + health analytics custom modules method over gRPC. + + Returns a list of all resident + SecurityHealthAnalyticsCustomModules under the given CRM + parent and all of the parent’s CRM descendants. + + Returns: + Callable[[~.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], + Awaitable[~.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_descendant_security_health_analytics_custom_modules' not in self._stubs: + self._stubs['list_descendant_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantSecurityHealthAnalyticsCustomModules', + request_serializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.deserialize, + ) + return self._stubs['list_descendant_security_health_analytics_custom_modules'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + 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.securitycenter.v1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + Awaitable[securitycenter_service.ListMuteConfigsResponse]]: + r"""Return a callable for the list mute configs method over gRPC. + + Lists mute configs. + + Returns: + Callable[[~.ListMuteConfigsRequest], + Awaitable[~.ListMuteConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_mute_configs' not in self._stubs: + self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListMuteConfigs', + request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, + ) + return self._stubs['list_mute_configs'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + Awaitable[~.ListNotificationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_effective_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], + Awaitable[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]]: + r"""Return a callable for the list effective security health + analytics custom modules method over gRPC. + + Returns a list of all + EffectiveSecurityHealthAnalyticsCustomModules for the + given parent. This includes resident modules defined at + the scope of the parent, and inherited modules, + inherited from CRM ancestors. + + Returns: + Callable[[~.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], + Awaitable[~.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_effective_security_health_analytics_custom_modules' not in self._stubs: + self._stubs['list_effective_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveSecurityHealthAnalyticsCustomModules', + request_serializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.deserialize, + ) + return self._stubs['list_effective_security_health_analytics_custom_modules'] + + @property + def list_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], + Awaitable[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]]: + r"""Return a callable for the list security health analytics + custom modules method over gRPC. + + Returns a list of all + SecurityHealthAnalyticsCustomModules for the given + parent. This includes resident modules defined at the + scope of the parent, and inherited modules, inherited + from CRM ancestors. + + Returns: + Callable[[~.ListSecurityHealthAnalyticsCustomModulesRequest], + Awaitable[~.ListSecurityHealthAnalyticsCustomModulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_security_health_analytics_custom_modules' not in self._stubs: + self._stubs['list_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListSecurityHealthAnalyticsCustomModules', + request_serializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.deserialize, + ) + return self._stubs['list_security_health_analytics_custom_modules'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse]]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + 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 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + 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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set mute method over gRPC. + + Updates the mute state of a finding. + + Returns: + Callable[[~.SetMuteRequest], + 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 'set_mute' not in self._stubs: + self._stubs['set_mute'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SetMute', + request_serializer=securitycenter_service.SetMuteRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_mute'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.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.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def simulate_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse]]: + r"""Return a callable for the simulate security health + analytics custom module method over gRPC. + + Simulates a given SecurityHealthAnalyticsCustomModule + and Resource. + + Returns: + Callable[[~.SimulateSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[~.SimulateSecurityHealthAnalyticsCustomModuleResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'simulate_security_health_analytics_custom_module' not in self._stubs: + self._stubs['simulate_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SimulateSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.deserialize, + ) + return self._stubs['simulate_security_health_analytics_custom_module'] + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + Awaitable[gcs_external_system.ExternalSystem]]: + r"""Return a callable for the update external system method over gRPC. + + Updates external system. This is for a given finding. + + Returns: + Callable[[~.UpdateExternalSystemRequest], + Awaitable[~.ExternalSystem]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_external_system' not in self._stubs: + self._stubs['update_external_system'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateExternalSystem', + request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, + response_deserializer=gcs_external_system.ExternalSystem.deserialize, + ) + return self._stubs['update_external_system'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + 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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + Awaitable[gcs_mute_config.MuteConfig]]: + r"""Return a callable for the update mute config method over gRPC. + + Updates a mute config. + + Returns: + Callable[[~.UpdateMuteConfigRequest], + Awaitable[~.MuteConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateMuteConfig', + request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['update_mute_config'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Awaitable[gcs_organization_settings.OrganizationSettings]]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]]: + r"""Return a callable for the update security health + analytics custom module method over gRPC. + + Updates the SecurityHealthAnalyticsCustomModule under + the given name based on the given update mask. Updating + the enablement state is supported on both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name and custom config of a module is supported + on resident modules only. + + Returns: + Callable[[~.UpdateSecurityHealthAnalyticsCustomModuleRequest], + Awaitable[~.SecurityHealthAnalyticsCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: + self._stubs['update_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityHealthAnalyticsCustomModule', + request_serializer=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.serialize, + response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, + ) + return self._stubs['update_security_health_analytics_custom_module'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks]]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport]]: + r"""Return a callable for the create big query export method over gRPC. + + Creates a BigQuery export. + + Returns: + Callable[[~.CreateBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateBigQueryExport', + request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['create_big_query_export'] + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete big query export method over gRPC. + + Deletes an existing BigQuery export. + + Returns: + Callable[[~.DeleteBigQueryExportRequest], + 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_big_query_export' not in self._stubs: + self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteBigQueryExport', + request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_big_query_export'] + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport]]: + r"""Return a callable for the update big query export method over gRPC. + + Updates a BigQuery export. + + Returns: + Callable[[~.UpdateBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateBigQueryExport', + request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['update_big_query_export'] + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + Awaitable[securitycenter_service.ListBigQueryExportsResponse]]: + r"""Return a callable for the list big query exports method over gRPC. + + Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are returned. + + Returns: + Callable[[~.ListBigQueryExportsRequest], + Awaitable[~.ListBigQueryExportsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_big_query_exports' not in self._stubs: + self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListBigQueryExports', + request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, + response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, + ) + return self._stubs['list_big_query_exports'] + + @property + def create_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], + Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]]: + r"""Return a callable for the create event threat detection + custom module method over gRPC. + + Creates a resident Event Threat Detection custom + module at the scope of the given Resource Manager + parent, and also creates inherited custom modules for + all descendants of the given parent. These modules are + enabled by default. + + Returns: + Callable[[~.CreateEventThreatDetectionCustomModuleRequest], + Awaitable[~.EventThreatDetectionCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['create_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['create_event_threat_detection_custom_module'] + + @property + def delete_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete event threat detection + custom module method over gRPC. + + Deletes the specified Event Threat Detection custom + module and all of its descendants in the Resource + Manager hierarchy. This method is only supported for + resident custom modules. + + Returns: + Callable[[~.DeleteEventThreatDetectionCustomModuleRequest], + 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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['delete_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_event_threat_detection_custom_module'] + + @property + def get_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], + Awaitable[event_threat_detection_custom_module.EventThreatDetectionCustomModule]]: + r"""Return a callable for the get event threat detection + custom module method over gRPC. + + Gets an Event Threat Detection custom module. + + Returns: + Callable[[~.GetEventThreatDetectionCustomModuleRequest], + Awaitable[~.EventThreatDetectionCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_event_threat_detection_custom_module' not in self._stubs: + self._stubs['get_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.GetEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['get_event_threat_detection_custom_module'] + + @property + def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], + Awaitable[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]]: + r"""Return a callable for the list descendant event threat + detection custom modules method over gRPC. + + Lists all resident Event Threat Detection custom + modules under the given Resource Manager parent and its + descendants. + + Returns: + Callable[[~.ListDescendantEventThreatDetectionCustomModulesRequest], + Awaitable[~.ListDescendantEventThreatDetectionCustomModulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_descendant_event_threat_detection_custom_modules' not in self._stubs: + self._stubs['list_descendant_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantEventThreatDetectionCustomModules', + request_serializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.deserialize, + ) + return self._stubs['list_descendant_event_threat_detection_custom_modules'] + + @property + def list_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], + Awaitable[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]]: + r"""Return a callable for the list event threat detection + custom modules method over gRPC. + + Lists all Event Threat Detection custom modules for + the given Resource Manager parent. This includes + resident modules defined at the scope of the parent + along with modules inherited from ancestors. + + Returns: + Callable[[~.ListEventThreatDetectionCustomModulesRequest], + Awaitable[~.ListEventThreatDetectionCustomModulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_event_threat_detection_custom_modules' not in self._stubs: + self._stubs['list_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListEventThreatDetectionCustomModules', + request_serializer=securitycenter_service.ListEventThreatDetectionCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListEventThreatDetectionCustomModulesResponse.deserialize, + ) + return self._stubs['list_event_threat_detection_custom_modules'] + + @property + def update_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], + Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]]: + r"""Return a callable for the update event threat detection + custom module method over gRPC. + + Updates the Event Threat Detection custom module with + the given name based on the given update mask. Updating + the enablement state is supported for both resident and + inherited modules (though resident modules cannot have + an enablement state of "inherited"). Updating the + display name or configuration of a module is supported + for resident modules only. The type of a module cannot + be changed. + + Returns: + Callable[[~.UpdateEventThreatDetectionCustomModuleRequest], + Awaitable[~.EventThreatDetectionCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['update_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['update_event_threat_detection_custom_module'] + + @property + def validate_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], + Awaitable[securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse]]: + r"""Return a callable for the validate event threat + detection custom module method over gRPC. + + Validates the given Event Threat Detection custom + module. + + Returns: + Callable[[~.ValidateEventThreatDetectionCustomModuleRequest], + Awaitable[~.ValidateEventThreatDetectionCustomModuleResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: + self._stubs['validate_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ValidateEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.deserialize, + ) + return self._stubs['validate_event_threat_detection_custom_module'] + + @property + def get_effective_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], + Awaitable[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]]: + r"""Return a callable for the get effective event threat + detection custom module method over gRPC. + + Gets an effective Event Threat Detection custom + module at the given level. + + Returns: + Callable[[~.GetEffectiveEventThreatDetectionCustomModuleRequest], + Awaitable[~.EffectiveEventThreatDetectionCustomModule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_effective_event_threat_detection_custom_module' not in self._stubs: + self._stubs['get_effective_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveEventThreatDetectionCustomModule', + request_serializer=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.serialize, + response_deserializer=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.deserialize, + ) + return self._stubs['get_effective_event_threat_detection_custom_module'] + + @property + def list_effective_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], + Awaitable[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]]: + r"""Return a callable for the list effective event threat + detection custom modules method over gRPC. + + Lists all effective Event Threat Detection custom + modules for the given parent. This includes resident + modules defined at the scope of the parent along with + modules inherited from its ancestors. + + Returns: + Callable[[~.ListEffectiveEventThreatDetectionCustomModulesRequest], + Awaitable[~.ListEffectiveEventThreatDetectionCustomModulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_effective_event_threat_detection_custom_modules' not in self._stubs: + self._stubs['list_effective_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveEventThreatDetectionCustomModules', + request_serializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.serialize, + response_deserializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.deserialize, + ) + return self._stubs['list_effective_event_threat_detection_custom_modules'] + + @property + def batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse]]: + r"""Return a callable for the batch create resource value + configs method over gRPC. + + Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + Returns: + Callable[[~.BatchCreateResourceValueConfigsRequest], + Awaitable[~.BatchCreateResourceValueConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: + self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/BatchCreateResourceValueConfigs', + request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, + ) + return self._stubs['batch_create_resource_value_configs'] + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete resource value config method over gRPC. + + Deletes a ResourceValueConfig. + + Returns: + Callable[[~.DeleteResourceValueConfigRequest], + 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_resource_value_config' not in self._stubs: + self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteResourceValueConfig', + request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_resource_value_config'] + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + Awaitable[resource_value_config.ResourceValueConfig]]: + r"""Return a callable for the get resource value config method over gRPC. + + Gets a ResourceValueConfig. + + Returns: + Callable[[~.GetResourceValueConfigRequest], + Awaitable[~.ResourceValueConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_resource_value_config' not in self._stubs: + self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetResourceValueConfig', + request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, + response_deserializer=resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['get_resource_value_config'] + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + Awaitable[securitycenter_service.ListResourceValueConfigsResponse]]: + r"""Return a callable for the list resource value configs method over gRPC. + + Lists all ResourceValueConfigs. + + Returns: + Callable[[~.ListResourceValueConfigsRequest], + Awaitable[~.ListResourceValueConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_resource_value_configs' not in self._stubs: + self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListResourceValueConfigs', + request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, + ) + return self._stubs['list_resource_value_configs'] + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + Awaitable[gcs_resource_value_config.ResourceValueConfig]]: + r"""Return a callable for the update resource value config method over gRPC. + + Updates an existing ResourceValueConfigs with new + rules. + + Returns: + Callable[[~.UpdateResourceValueConfigRequest], + Awaitable[~.ResourceValueConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: + self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateResourceValueConfig', + request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, + response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['update_resource_value_config'] + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + Awaitable[securitycenter_service.ListValuedResourcesResponse]]: + r"""Return a callable for the list valued resources method over gRPC. + + Lists the valued resources for a set of simulation + results and filter. + + Returns: + Callable[[~.ListValuedResourcesRequest], + Awaitable[~.ListValuedResourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_valued_resources' not in self._stubs: + self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListValuedResources', + request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, + response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, + ) + return self._stubs['list_valued_resources'] + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + Awaitable[securitycenter_service.ListAttackPathsResponse]]: + r"""Return a callable for the list attack paths method over gRPC. + + Lists the attack paths for a set of simulation + results or valued resources and filter. + + Returns: + Callable[[~.ListAttackPathsRequest], + Awaitable[~.ListAttackPathsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_attack_paths' not in self._stubs: + self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListAttackPaths', + request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, + response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, + ) + return self._stubs['list_attack_paths'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.bulk_mute_findings: gapic_v1.method_async.wrap_method( + self.bulk_mute_findings, + default_timeout=None, + client_info=client_info, + ), + self.create_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( + self.create_security_health_analytics_custom_module, + default_timeout=60.0, + client_info=client_info, + ), + self.create_source: gapic_v1.method_async.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method_async.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.create_mute_config: gapic_v1.method_async.wrap_method( + self.create_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method_async.wrap_method( + self.create_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_mute_config: gapic_v1.method_async.wrap_method( + self.delete_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method_async.wrap_method( + self.delete_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( + self.delete_security_health_analytics_custom_module, + default_timeout=60.0, + client_info=client_info, + ), + self.get_simulation: gapic_v1.method_async.wrap_method( + self.get_simulation, + default_timeout=None, + client_info=client_info, + ), + self.get_valued_resource: gapic_v1.method_async.wrap_method( + self.get_valued_resource, + default_timeout=None, + client_info=client_info, + ), + self.get_big_query_export: gapic_v1.method_async.wrap_method( + self.get_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_mute_config: gapic_v1.method_async.wrap_method( + self.get_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.get_notification_config: gapic_v1.method_async.wrap_method( + self.get_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_settings: gapic_v1.method_async.wrap_method( + self.get_organization_settings, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_effective_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( + self.get_effective_security_health_analytics_custom_module, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( + self.get_security_health_analytics_custom_module, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_source: gapic_v1.method_async.wrap_method( + self.get_source, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.group_assets: gapic_v1.method_async.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method_async.wrap_method( + self.group_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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method_async.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_descendant_security_health_analytics_custom_modules: gapic_v1.method_async.wrap_method( + self.list_descendant_security_health_analytics_custom_modules, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method_async.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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_mute_configs: gapic_v1.method_async.wrap_method( + self.list_mute_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method_async.wrap_method( + self.list_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_effective_security_health_analytics_custom_modules: gapic_v1.method_async.wrap_method( + self.list_effective_security_health_analytics_custom_modules, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_security_health_analytics_custom_modules: gapic_v1.method_async.wrap_method( + self.list_security_health_analytics_custom_modules, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_sources: gapic_v1.method_async.wrap_method( + self.list_sources, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.run_asset_discovery: gapic_v1.method_async.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method_async.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_mute: gapic_v1.method_async.wrap_method( + self.set_mute, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.simulate_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( + self.simulate_security_health_analytics_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.update_external_system: gapic_v1.method_async.wrap_method( + self.update_external_system, + default_timeout=None, + client_info=client_info, + ), + self.update_finding: gapic_v1.method_async.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_mute_config: gapic_v1.method_async.wrap_method( + self.update_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method_async.wrap_method( + self.update_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method_async.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( + self.update_security_health_analytics_custom_module, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method_async.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method_async.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=client_info, + ), + self.create_big_query_export: gapic_v1.method_async.wrap_method( + self.create_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.delete_big_query_export: gapic_v1.method_async.wrap_method( + self.delete_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.update_big_query_export: gapic_v1.method_async.wrap_method( + self.update_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.list_big_query_exports: gapic_v1.method_async.wrap_method( + self.list_big_query_exports, + default_timeout=None, + client_info=client_info, + ), + self.create_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( + self.create_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.delete_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( + self.delete_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.get_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( + self.get_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.list_descendant_event_threat_detection_custom_modules: gapic_v1.method_async.wrap_method( + self.list_descendant_event_threat_detection_custom_modules, + default_timeout=None, + client_info=client_info, + ), + self.list_event_threat_detection_custom_modules: gapic_v1.method_async.wrap_method( + self.list_event_threat_detection_custom_modules, + default_timeout=None, + client_info=client_info, + ), + self.update_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( + self.update_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.validate_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( + self.validate_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.get_effective_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( + self.get_effective_event_threat_detection_custom_module, + default_timeout=None, + client_info=client_info, + ), + self.list_effective_event_threat_detection_custom_modules: gapic_v1.method_async.wrap_method( + self.list_effective_event_threat_detection_custom_modules, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_resource_value_configs: gapic_v1.method_async.wrap_method( + self.batch_create_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.delete_resource_value_config: gapic_v1.method_async.wrap_method( + self.delete_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_resource_value_config: gapic_v1.method_async.wrap_method( + self.get_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.list_resource_value_configs: gapic_v1.method_async.wrap_method( + self.list_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_resource_value_config: gapic_v1.method_async.wrap_method( + self.update_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.list_valued_resources: gapic_v1.method_async.wrap_method( + self.list_valued_resources, + default_timeout=None, + client_info=client_info, + ), + self.list_attack_paths: gapic_v1.method_async.wrap_method( + self.list_attack_paths, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return 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"] + + +__all__ = ( + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py new file mode 100644 index 000000000000..cafbd10f6efa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py @@ -0,0 +1,8529 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # 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 path_template +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 +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import valued_resource +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SecurityCenterRestInterceptor: + """Interceptor for SecurityCenter. + + 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 SecurityCenterRestTransport. + + .. code-block:: python + class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): + def pre_batch_create_resource_value_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_resource_value_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_bulk_mute_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_bulk_mute_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_event_threat_detection_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_event_threat_detection_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_security_health_analytics_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_security_health_analytics_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_event_threat_detection_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_security_health_analytics_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_effective_event_threat_detection_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_effective_event_threat_detection_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_effective_security_health_analytics_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_effective_security_health_analytics_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_event_threat_detection_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_event_threat_detection_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_organization_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_organization_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_resource_value_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_security_health_analytics_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_security_health_analytics_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_simulation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_simulation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_valued_resource(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_valued_resource(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_attack_paths(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_attack_paths(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_big_query_exports(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_big_query_exports(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_descendant_event_threat_detection_custom_modules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_descendant_event_threat_detection_custom_modules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_descendant_security_health_analytics_custom_modules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_descendant_security_health_analytics_custom_modules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_effective_event_threat_detection_custom_modules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_effective_event_threat_detection_custom_modules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_effective_security_health_analytics_custom_modules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_effective_security_health_analytics_custom_modules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_event_threat_detection_custom_modules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_event_threat_detection_custom_modules(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_mute_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_mute_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_notification_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_notification_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_resource_value_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_resource_value_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_security_health_analytics_custom_modules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_security_health_analytics_custom_modules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_valued_resources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_valued_resources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_run_asset_discovery(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_asset_discovery(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_finding_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_finding_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_mute(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_mute(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_simulate_security_health_analytics_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_simulate_security_health_analytics_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_event_threat_detection_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_event_threat_detection_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_external_system(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_external_system(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_organization_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_organization_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_resource_value_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_security_health_analytics_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_security_health_analytics_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_security_marks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_security_marks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_validate_event_threat_detection_custom_module(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_validate_event_threat_detection_custom_module(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) + client = SecurityCenterClient(transport=transport) + + + """ + def pre_batch_create_resource_value_configs(self, request: securitycenter_service.BatchCreateResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BatchCreateResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_create_resource_value_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_batch_create_resource_value_configs(self, response: securitycenter_service.BatchCreateResourceValueConfigsResponse) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + """Post-rpc interceptor for batch_create_resource_value_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_bulk_mute_findings(self, request: securitycenter_service.BulkMuteFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BulkMuteFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for bulk_mute_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_bulk_mute_findings(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for bulk_mute_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_big_query_export(self, request: securitycenter_service.CreateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for create_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_event_threat_detection_custom_module(self, request: securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_event_threat_detection_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_event_threat_detection_custom_module(self, response: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + """Post-rpc interceptor for create_event_threat_detection_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for create_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_mute_config(self, request: securitycenter_service.CreateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: + """Post-rpc interceptor for create_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_notification_config(self, request: securitycenter_service.CreateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_security_health_analytics_custom_module(self, request: securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_security_health_analytics_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_security_health_analytics_custom_module(self, response: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + """Post-rpc interceptor for create_security_health_analytics_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for create_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_delete_big_query_export(self, request: securitycenter_service.DeleteBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_event_threat_detection_custom_module(self, request: securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_event_threat_detection_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_mute_config(self, request: securitycenter_service.DeleteMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_notification_config(self, request: securitycenter_service.DeleteNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_resource_value_config(self, request: securitycenter_service.DeleteResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteResourceValueConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_security_health_analytics_custom_module(self, request: securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_security_health_analytics_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_get_big_query_export(self, request: securitycenter_service.GetBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for get_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_effective_event_threat_detection_custom_module(self, request: securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_effective_event_threat_detection_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_effective_event_threat_detection_custom_module(self, response: effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: + """Post-rpc interceptor for get_effective_event_threat_detection_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_effective_security_health_analytics_custom_module(self, request: securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_effective_security_health_analytics_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_effective_security_health_analytics_custom_module(self, response: effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: + """Post-rpc interceptor for get_effective_security_health_analytics_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_event_threat_detection_custom_module(self, request: securitycenter_service.GetEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_event_threat_detection_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_event_threat_detection_custom_module(self, response: event_threat_detection_custom_module.EventThreatDetectionCustomModule) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: + """Post-rpc interceptor for get_event_threat_detection_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_mute_config(self, request: securitycenter_service.GetMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_mute_config(self, response: mute_config.MuteConfig) -> mute_config.MuteConfig: + """Post-rpc interceptor for get_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_notification_config(self, request: securitycenter_service.GetNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_notification_config(self, response: notification_config.NotificationConfig) -> notification_config.NotificationConfig: + """Post-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_organization_settings(self, request: securitycenter_service.GetOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_organization_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_organization_settings(self, response: organization_settings.OrganizationSettings) -> organization_settings.OrganizationSettings: + """Post-rpc interceptor for get_organization_settings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_resource_value_config(self, request: securitycenter_service.GetResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetResourceValueConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_resource_value_config(self, response: resource_value_config.ResourceValueConfig) -> resource_value_config.ResourceValueConfig: + """Post-rpc interceptor for get_resource_value_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_security_health_analytics_custom_module(self, request: securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_security_health_analytics_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_security_health_analytics_custom_module(self, response: security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + """Post-rpc interceptor for get_security_health_analytics_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_simulation(self, request: securitycenter_service.GetSimulationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSimulationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_simulation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_simulation(self, response: simulation.Simulation) -> simulation.Simulation: + """Post-rpc interceptor for get_simulation + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_source(self, response: source.Source) -> source.Source: + """Post-rpc interceptor for get_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_valued_resource(self, request: securitycenter_service.GetValuedResourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetValuedResourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_valued_resource + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_valued_resource(self, response: valued_resource.ValuedResource) -> valued_resource.ValuedResource: + """Post-rpc interceptor for get_valued_resource + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_assets(self, request: securitycenter_service.GroupAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_assets(self, response: securitycenter_service.GroupAssetsResponse) -> securitycenter_service.GroupAssetsResponse: + """Post-rpc interceptor for group_assets + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: + """Post-rpc interceptor for group_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_assets(self, request: securitycenter_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_assets(self, response: securitycenter_service.ListAssetsResponse) -> securitycenter_service.ListAssetsResponse: + """Post-rpc interceptor for list_assets + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_attack_paths(self, request: securitycenter_service.ListAttackPathsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAttackPathsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_attack_paths + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_attack_paths(self, response: securitycenter_service.ListAttackPathsResponse) -> securitycenter_service.ListAttackPathsResponse: + """Post-rpc interceptor for list_attack_paths + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_big_query_exports(self, request: securitycenter_service.ListBigQueryExportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListBigQueryExportsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_big_query_exports + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_big_query_exports(self, response: securitycenter_service.ListBigQueryExportsResponse) -> securitycenter_service.ListBigQueryExportsResponse: + """Post-rpc interceptor for list_big_query_exports + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_descendant_event_threat_detection_custom_modules(self, request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_descendant_event_threat_detection_custom_modules + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_descendant_event_threat_detection_custom_modules(self, response: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse) -> securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse: + """Post-rpc interceptor for list_descendant_event_threat_detection_custom_modules + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_descendant_security_health_analytics_custom_modules(self, request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_descendant_security_health_analytics_custom_modules + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_descendant_security_health_analytics_custom_modules(self, response: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse) -> securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse: + """Post-rpc interceptor for list_descendant_security_health_analytics_custom_modules + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_effective_event_threat_detection_custom_modules(self, request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_effective_event_threat_detection_custom_modules + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_effective_event_threat_detection_custom_modules(self, response: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse) -> securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse: + """Post-rpc interceptor for list_effective_event_threat_detection_custom_modules + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_effective_security_health_analytics_custom_modules(self, request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_effective_security_health_analytics_custom_modules + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_effective_security_health_analytics_custom_modules(self, response: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse) -> securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse: + """Post-rpc interceptor for list_effective_security_health_analytics_custom_modules + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_event_threat_detection_custom_modules(self, request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListEventThreatDetectionCustomModulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_event_threat_detection_custom_modules + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_event_threat_detection_custom_modules(self, response: securitycenter_service.ListEventThreatDetectionCustomModulesResponse) -> securitycenter_service.ListEventThreatDetectionCustomModulesResponse: + """Post-rpc interceptor for list_event_threat_detection_custom_modules + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. + """ + return request, metadata + + def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_mute_configs(self, request: securitycenter_service.ListMuteConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListMuteConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_mute_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_mute_configs(self, response: securitycenter_service.ListMuteConfigsResponse) -> securitycenter_service.ListMuteConfigsResponse: + """Post-rpc interceptor for list_mute_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_notification_configs(self, request: securitycenter_service.ListNotificationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListNotificationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_notification_configs(self, response: securitycenter_service.ListNotificationConfigsResponse) -> securitycenter_service.ListNotificationConfigsResponse: + """Post-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_resource_value_configs(self, request: securitycenter_service.ListResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_resource_value_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_resource_value_configs(self, response: securitycenter_service.ListResourceValueConfigsResponse) -> securitycenter_service.ListResourceValueConfigsResponse: + """Post-rpc interceptor for list_resource_value_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_security_health_analytics_custom_modules(self, request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_security_health_analytics_custom_modules + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_security_health_analytics_custom_modules(self, response: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse) -> securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse: + """Post-rpc interceptor for list_security_health_analytics_custom_modules + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_sources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: + """Post-rpc interceptor for list_sources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_valued_resources(self, request: securitycenter_service.ListValuedResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListValuedResourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_valued_resources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_valued_resources(self, response: securitycenter_service.ListValuedResourcesResponse) -> securitycenter_service.ListValuedResourcesResponse: + """Post-rpc interceptor for list_valued_resources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_run_asset_discovery(self, request: securitycenter_service.RunAssetDiscoveryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.RunAssetDiscoveryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for run_asset_discovery + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_run_asset_discovery(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for run_asset_discovery + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_set_mute(self, request: securitycenter_service.SetMuteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetMuteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_mute + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_mute(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_mute + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_simulate_security_health_analytics_custom_module(self, request: securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for simulate_security_health_analytics_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_simulate_security_health_analytics_custom_module(self, response: securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: + """Post-rpc interceptor for simulate_security_health_analytics_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_big_query_export(self, request: securitycenter_service.UpdateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for update_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_event_threat_detection_custom_module(self, request: securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_event_threat_detection_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_event_threat_detection_custom_module(self, response: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + """Post-rpc interceptor for update_event_threat_detection_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_external_system(self, request: securitycenter_service.UpdateExternalSystemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateExternalSystemRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_external_system + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_external_system(self, response: gcs_external_system.ExternalSystem) -> gcs_external_system.ExternalSystem: + """Post-rpc interceptor for update_external_system + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for update_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_mute_config(self, request: securitycenter_service.UpdateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: + """Post-rpc interceptor for update_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_notification_config(self, request: securitycenter_service.UpdateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_organization_settings(self, request: securitycenter_service.UpdateOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_organization_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_organization_settings(self, response: gcs_organization_settings.OrganizationSettings) -> gcs_organization_settings.OrganizationSettings: + """Post-rpc interceptor for update_organization_settings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_resource_value_config(self, request: securitycenter_service.UpdateResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateResourceValueConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_resource_value_config(self, response: gcs_resource_value_config.ResourceValueConfig) -> gcs_resource_value_config.ResourceValueConfig: + """Post-rpc interceptor for update_resource_value_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_security_health_analytics_custom_module(self, request: securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_security_health_analytics_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_security_health_analytics_custom_module(self, response: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + """Post-rpc interceptor for update_security_health_analytics_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: + """Post-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for update_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_validate_event_threat_detection_custom_module(self, request: securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for validate_event_threat_detection_custom_module + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_validate_event_threat_detection_custom_module(self, response: securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: + """Post-rpc interceptor for validate_event_threat_detection_custom_module + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SecurityCenterRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SecurityCenterRestInterceptor + + +class SecurityCenterRestTransport(SecurityCenterTransport): + """REST backend transport for SecurityCenter. + + V1 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[SecurityCenterRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 + 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 + ) + 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 SecurityCenterRestInterceptor() + 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=organizations/*/operations/*}:cancel', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/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 _BatchCreateResourceValueConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("BatchCreateResourceValueConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.BatchCreateResourceValueConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Call the batch create resource + value configs method over HTTP. + + Args: + request (~.securitycenter_service.BatchCreateResourceValueConfigsRequest): + The request object. Request message to create multiple + resource value configs + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/resourceValueConfigs:batchCreate', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_batch_create_resource_value_configs(request, metadata) + pb_request = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.BatchCreateResourceValueConfigsResponse() + pb_resp = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_create_resource_value_configs(resp) + return resp + + class _BulkMuteFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("BulkMuteFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.BulkMuteFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the bulk mute findings method over HTTP. + + Args: + request (~.securitycenter_service.BulkMuteFindingsRequest): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/findings:bulkMute', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_bulk_mute_findings(request, metadata) + pb_request = securitycenter_service.BulkMuteFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_bulk_mute_findings(resp) + return resp + + class _CreateBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "bigQueryExportId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> bigquery_export.BigQueryExport: + r"""Call the create big query export method over HTTP. + + Args: + request (~.securitycenter_service.CreateBigQueryExportRequest): + The request object. Request message for creating a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/bigQueryExports', + 'body': 'big_query_export', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*}/bigQueryExports', + 'body': 'big_query_export', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/bigQueryExports', + 'body': 'big_query_export', + }, + ] + request, metadata = self._interceptor.pre_create_big_query_export(request, metadata) + pb_request = securitycenter_service.CreateBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_big_query_export(resp) + return resp + + class _CreateEventThreatDetectionCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateEventThreatDetectionCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Call the create event threat + detection custom module method over HTTP. + + Args: + request (~.securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): + The request object. Request to create an Event Threat + Detection custom module. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/customModules', + 'body': 'event_threat_detection_custom_module', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/customModules', + 'body': 'event_threat_detection_custom_module', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/customModules', + 'body': 'event_threat_detection_custom_module', + }, + ] + request, metadata = self._interceptor.pre_create_event_threat_detection_custom_module(request, metadata) + pb_request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + pb_resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_event_threat_detection_custom_module(resp) + return resp + + class _CreateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "findingId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the create finding method over HTTP. + + Args: + request (~.securitycenter_service.CreateFindingRequest): + The request object. Request message for creating a + finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/sources/*}/findings', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_create_finding(request, metadata) + pb_request = securitycenter_service.CreateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_finding(resp) + return resp + + class _CreateMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "muteConfigId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_mute_config.MuteConfig: + r"""Call the create mute config method over HTTP. + + Args: + request (~.securitycenter_service.CreateMuteConfigRequest): + The request object. Request message for creating a mute + config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/locations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*/locations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/muteConfigs', + 'body': 'mute_config', + }, + ] + request, metadata = self._interceptor.pre_create_mute_config(request, metadata) + pb_request = securitycenter_service.CreateMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_mute_config.MuteConfig() + pb_resp = gcs_mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_mute_config(resp) + return resp + + class _CreateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "configId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the create notification + config method over HTTP. + + Args: + request (~.securitycenter_service.CreateNotificationConfigRequest): + The request object. Request message for creating a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/notificationConfigs', + 'body': 'notification_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*}/notificationConfigs', + 'body': 'notification_config', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/notificationConfigs', + 'body': 'notification_config', + }, + ] + request, metadata = self._interceptor.pre_create_notification_config(request, metadata) + pb_request = securitycenter_service.CreateNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_notification_config(resp) + return resp + + class _CreateSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateSecurityHealthAnalyticsCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Call the create security health + analytics custom module method over HTTP. + + Args: + request (~.securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): + The request object. Request message for creating Security + Health Analytics custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules', + 'body': 'security_health_analytics_custom_module', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules', + 'body': 'security_health_analytics_custom_module', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules', + 'body': 'security_health_analytics_custom_module', + }, + ] + request, metadata = self._interceptor.pre_create_security_health_analytics_custom_module(request, metadata) + pb_request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + pb_resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_security_health_analytics_custom_module(resp) + return resp + + class _CreateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the create source method over HTTP. + + Args: + request (~.securitycenter_service.CreateSourceRequest): + The request object. Request message for creating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/sources', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_create_source(request, metadata) + pb_request = securitycenter_service.CreateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_source(resp) + return resp + + class _DeleteBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete big query export method over HTTP. + + Args: + request (~.securitycenter_service.DeleteBigQueryExportRequest): + The request object. Request message for deleting a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/bigQueryExports/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=folders/*/bigQueryExports/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/bigQueryExports/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_big_query_export(request, metadata) + pb_request = securitycenter_service.DeleteBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteEventThreatDetectionCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteEventThreatDetectionCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete event threat + detection custom module method over HTTP. + + Args: + request (~.securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): + The request object. Request to delete an Event Threat + Detection custom module. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/eventThreatDetectionSettings/customModules/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=folders/*/eventThreatDetectionSettings/customModules/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/eventThreatDetectionSettings/customModules/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_event_threat_detection_custom_module(request, metadata) + pb_request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete mute config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteMuteConfigRequest): + The request object. Request message for deleting a mute + config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=folders/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=folders/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/muteConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_mute_config(request, metadata) + pb_request = securitycenter_service.DeleteMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete notification + config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteNotificationConfigRequest): + The request object. Request message for deleting a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/notificationConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=folders/*/notificationConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/notificationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_notification_config(request, metadata) + pb_request = securitycenter_service.DeleteNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteResourceValueConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteResourceValueConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete resource value + config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteResourceValueConfigRequest): + The request object. Request message to delete resource + value config + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/resourceValueConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_resource_value_config(request, metadata) + pb_request = securitycenter_service.DeleteResourceValueConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteSecurityHealthAnalyticsCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete security health + analytics custom module method over HTTP. + + Args: + request (~.securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): + The request object. Request message for deleting Security + Health Analytics custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/securityHealthAnalyticsSettings/customModules/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=folders/*/securityHealthAnalyticsSettings/customModules/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/securityHealthAnalyticsSettings/customModules/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_security_health_analytics_custom_module(request, metadata) + pb_request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _GetBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("GetBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> bigquery_export.BigQueryExport: + r"""Call the get big query export method over HTTP. + + Args: + request (~.securitycenter_service.GetBigQueryExportRequest): + The request object. Request message for retrieving a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/bigQueryExports/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/bigQueryExports/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/bigQueryExports/*}', + }, + ] + request, metadata = self._interceptor.pre_get_big_query_export(request, metadata) + pb_request = securitycenter_service.GetBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_big_query_export(resp) + return resp + + class _GetEffectiveEventThreatDetectionCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("GetEffectiveEventThreatDetectionCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: + r"""Call the get effective event + threat detection custom module method over HTTP. + + Args: + request (~.securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): + The request object. Request to get an + EffectiveEventThreatDetectionCustomModule. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: + An EffectiveEventThreatDetectionCustomModule is the + representation of an Event Threat Detection custom + module at a specified level of the resource hierarchy: + organization, folder, or project. If a custom module is + inherited from a parent organization or folder, the + value of the ``enablement_state`` property in + EffectiveEventThreatDetectionCustomModule is set to the + value that is effective in the parent, instead of + ``INHERITED``. For example, if the module is enabled in + a parent organization or folder, the effective + ``enablement_state`` for the module in all child folders + or projects is also ``enabled``. + EffectiveEventThreatDetectionCustomModule is read-only. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/eventThreatDetectionSettings/effectiveCustomModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/eventThreatDetectionSettings/effectiveCustomModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/eventThreatDetectionSettings/effectiveCustomModules/*}', + }, + ] + request, metadata = self._interceptor.pre_get_effective_event_threat_detection_custom_module(request, metadata) + pb_request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + pb_resp = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_effective_event_threat_detection_custom_module(resp) + return resp + + class _GetEffectiveSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("GetEffectiveSecurityHealthAnalyticsCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: + r"""Call the get effective security + health analytics custom module method over HTTP. + + Args: + request (~.securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): + The request object. Request message for getting effective + Security Health Analytics custom + modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: + An EffectiveSecurityHealthAnalyticsCustomModule is the + representation of a Security Health Analytics custom + module at a specified level of the resource hierarchy: + organization, folder, or project. If a custom module is + inherited from a parent organization or folder, the + value of the ``enablementState`` property in + EffectiveSecurityHealthAnalyticsCustomModule is set to + the value that is effective in the parent, instead of + ``INHERITED``. For example, if the module is enabled in + a parent organization or folder, the effective + enablement_state for the module in all child folders or + projects is also ``enabled``. + EffectiveSecurityHealthAnalyticsCustomModule is + read-only. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}', + }, + ] + request, metadata = self._interceptor.pre_get_effective_security_health_analytics_custom_module(request, metadata) + pb_request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + pb_resp = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_effective_security_health_analytics_custom_module(resp) + return resp + + class _GetEventThreatDetectionCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("GetEventThreatDetectionCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetEventThreatDetectionCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Call the get event threat + detection custom module method over HTTP. + + Args: + request (~.securitycenter_service.GetEventThreatDetectionCustomModuleRequest): + The request object. Request to get an Event Threat + Detection custom module. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.event_threat_detection_custom_module.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/eventThreatDetectionSettings/customModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/eventThreatDetectionSettings/customModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/eventThreatDetectionSettings/customModules/*}', + }, + ] + request, metadata = self._interceptor.pre_get_event_threat_detection_custom_module(request, metadata) + pb_request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + pb_resp = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_event_threat_detection_custom_module(resp) + return resp + + class _GetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=organizations/*/sources/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> mute_config.MuteConfig: + r"""Call the get mute config method over HTTP. + + Args: + request (~.securitycenter_service.GetMuteConfigRequest): + The request object. Request message for retrieving a mute + config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/muteConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_mute_config(request, metadata) + pb_request = securitycenter_service.GetMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = mute_config.MuteConfig() + pb_resp = mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_mute_config(resp) + return resp + + class _GetNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> notification_config.NotificationConfig: + r"""Call the get notification config method over HTTP. + + Args: + request (~.securitycenter_service.GetNotificationConfigRequest): + The request object. Request message for getting a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/notificationConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/notificationConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/notificationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_notification_config(request, metadata) + pb_request = securitycenter_service.GetNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = notification_config.NotificationConfig() + pb_resp = notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_notification_config(resp) + return resp + + class _GetOrganizationSettings(SecurityCenterRestStub): + def __hash__(self): + return hash("GetOrganizationSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetOrganizationSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> organization_settings.OrganizationSettings: + r"""Call the get organization settings method over HTTP. + + Args: + request (~.securitycenter_service.GetOrganizationSettingsRequest): + The request object. Request message for getting + organization 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: + ~.organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/organizationSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_organization_settings(request, metadata) + pb_request = securitycenter_service.GetOrganizationSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = organization_settings.OrganizationSettings() + pb_resp = organization_settings.OrganizationSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_organization_settings(resp) + return resp + + class _GetResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetResourceValueConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetResourceValueConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resource_value_config.ResourceValueConfig: + r"""Call the get resource value config method over HTTP. + + Args: + request (~.securitycenter_service.GetResourceValueConfigRequest): + The request object. Request message to get resource value + config + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource_value_config.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/resourceValueConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_resource_value_config(request, metadata) + pb_request = securitycenter_service.GetResourceValueConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource_value_config.ResourceValueConfig() + pb_resp = resource_value_config.ResourceValueConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_resource_value_config(resp) + return resp + + class _GetSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSecurityHealthAnalyticsCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Call the get security health + analytics custom module method over HTTP. + + Args: + request (~.securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): + The request object. Request message for getting Security + Health Analytics custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/securityHealthAnalyticsSettings/customModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/securityHealthAnalyticsSettings/customModules/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/securityHealthAnalyticsSettings/customModules/*}', + }, + ] + request, metadata = self._interceptor.pre_get_security_health_analytics_custom_module(request, metadata) + pb_request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + pb_resp = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_security_health_analytics_custom_module(resp) + return resp + + class _GetSimulation(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSimulation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSimulationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> simulation.Simulation: + r"""Call the get simulation method over HTTP. + + Args: + request (~.securitycenter_service.GetSimulationRequest): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.simulation.Simulation: + Attack path simulation + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/simulations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_simulation(request, metadata) + pb_request = securitycenter_service.GetSimulationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = simulation.Simulation() + pb_resp = simulation.Simulation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_simulation(resp) + return resp + + class _GetSource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> source.Source: + r"""Call the get source method over HTTP. + + Args: + request (~.securitycenter_service.GetSourceRequest): + The request object. Request message for getting a source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/sources/*}', + }, + ] + request, metadata = self._interceptor.pre_get_source(request, metadata) + pb_request = securitycenter_service.GetSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = source.Source() + pb_resp = source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_source(resp) + return resp + + class _GetValuedResource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetValuedResource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetValuedResourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> valued_resource.ValuedResource: + r"""Call the get valued resource method over HTTP. + + Args: + request (~.securitycenter_service.GetValuedResourceRequest): + The request object. Request message for getting a valued + resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.valued_resource.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/simulations/*/valuedResources/*}', + }, + ] + request, metadata = self._interceptor.pre_get_valued_resource(request, metadata) + pb_request = securitycenter_service.GetValuedResourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = valued_resource.ValuedResource() + pb_resp = valued_resource.ValuedResource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_valued_resource(resp) + return resp + + class _GroupAssets(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupAssetsResponse: + r"""Call the group assets method over HTTP. + + Args: + request (~.securitycenter_service.GroupAssetsRequest): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupAssetsResponse: + Response message for grouping by + assets. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/assets:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*}/assets:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*}/assets:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_assets(request, metadata) + pb_request = securitycenter_service.GroupAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupAssetsResponse() + pb_resp = securitycenter_service.GroupAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_assets(resp) + return resp + + class _GroupFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupFindingsResponse: + r"""Call the group findings method over HTTP. + + Args: + request (~.securitycenter_service.GroupFindingsRequest): + The request object. Request message for grouping by + findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupFindingsResponse: + Response message for group by + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/sources/*}/findings:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_findings(request, metadata) + pb_request = securitycenter_service.GroupFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupFindingsResponse() + pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_findings(resp) + return resp + + class _ListAssets(SecurityCenterRestStub): + def __hash__(self): + return hash("ListAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListAssetsResponse: + r"""Call the list assets method over HTTP. + + Args: + request (~.securitycenter_service.ListAssetsRequest): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListAssetsResponse: + Response message for listing assets. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*}/assets', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*}/assets', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*}/assets', + }, + ] + request, metadata = self._interceptor.pre_list_assets(request, metadata) + pb_request = securitycenter_service.ListAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListAssetsResponse() + pb_resp = securitycenter_service.ListAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_assets(resp) + return resp + + class _ListAttackPaths(SecurityCenterRestStub): + def __hash__(self): + return hash("ListAttackPaths") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListAttackPathsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListAttackPathsResponse: + r"""Call the list attack paths method over HTTP. + + Args: + request (~.securitycenter_service.ListAttackPathsRequest): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListAttackPathsResponse: + Response message for listing the + attack paths for a given simulation or + valued resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/simulations/*}/attackPaths', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/simulations/*/valuedResources/*}/attackPaths', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/simulations/*/attackExposureResults/*}/attackPaths', + }, + ] + request, metadata = self._interceptor.pre_list_attack_paths(request, metadata) + pb_request = securitycenter_service.ListAttackPathsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListAttackPathsResponse() + pb_resp = securitycenter_service.ListAttackPathsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_attack_paths(resp) + return resp + + class _ListBigQueryExports(SecurityCenterRestStub): + def __hash__(self): + return hash("ListBigQueryExports") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListBigQueryExportsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListBigQueryExportsResponse: + r"""Call the list big query exports method over HTTP. + + Args: + request (~.securitycenter_service.ListBigQueryExportsRequest): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or 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: + ~.securitycenter_service.ListBigQueryExportsResponse: + Response message for listing BigQuery + exports. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*}/bigQueryExports', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*}/bigQueryExports', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*}/bigQueryExports', + }, + ] + request, metadata = self._interceptor.pre_list_big_query_exports(request, metadata) + pb_request = securitycenter_service.ListBigQueryExportsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListBigQueryExportsResponse() + pb_resp = securitycenter_service.ListBigQueryExportsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_big_query_exports(resp) + return resp + + class _ListDescendantEventThreatDetectionCustomModules(SecurityCenterRestStub): + def __hash__(self): + return hash("ListDescendantEventThreatDetectionCustomModules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse: + r"""Call the list descendant event + threat detection custom modules method over HTTP. + + Args: + request (~.securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): + The request object. Request to list current and + descendant resident Event Threat + Detection custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse: + Response for listing current and + descendant resident Event Threat + Detection custom modules. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/customModules:listDescendant', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/customModules:listDescendant', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/customModules:listDescendant', + }, + ] + request, metadata = self._interceptor.pre_list_descendant_event_threat_detection_custom_modules(request, metadata) + pb_request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + pb_resp = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_descendant_event_threat_detection_custom_modules(resp) + return resp + + class _ListDescendantSecurityHealthAnalyticsCustomModules(SecurityCenterRestStub): + def __hash__(self): + return hash("ListDescendantSecurityHealthAnalyticsCustomModules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse: + r"""Call the list descendant security + health analytics custom modules method over HTTP. + + Args: + request (~.securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + The request object. Request message for listing + descendant Security Health Analytics + custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse: + Response message for listing + descendant Security Health Analytics + custom modules. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules:listDescendant', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules:listDescendant', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules:listDescendant', + }, + ] + request, metadata = self._interceptor.pre_list_descendant_security_health_analytics_custom_modules(request, metadata) + pb_request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + pb_resp = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_descendant_security_health_analytics_custom_modules(resp) + return resp + + class _ListEffectiveEventThreatDetectionCustomModules(SecurityCenterRestStub): + def __hash__(self): + return hash("ListEffectiveEventThreatDetectionCustomModules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse: + r"""Call the list effective event + threat detection custom modules method over HTTP. + + Args: + request (~.securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): + The request object. Request to list effective Event + Threat Detection custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse: + Response for listing + EffectiveEventThreatDetectionCustomModules. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/effectiveCustomModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/effectiveCustomModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/effectiveCustomModules', + }, + ] + request, metadata = self._interceptor.pre_list_effective_event_threat_detection_custom_modules(request, metadata) + pb_request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + pb_resp = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_effective_event_threat_detection_custom_modules(resp) + return resp + + class _ListEffectiveSecurityHealthAnalyticsCustomModules(SecurityCenterRestStub): + def __hash__(self): + return hash("ListEffectiveSecurityHealthAnalyticsCustomModules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse: + r"""Call the list effective security + health analytics custom modules method over HTTP. + + Args: + request (~.securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + The request object. Request message for listing effective + Security Health Analytics custom + modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse: + Response message for listing + effective Security Health Analytics + custom modules. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/effectiveCustomModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/effectiveCustomModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/effectiveCustomModules', + }, + ] + request, metadata = self._interceptor.pre_list_effective_security_health_analytics_custom_modules(request, metadata) + pb_request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + pb_resp = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_effective_security_health_analytics_custom_modules(resp) + return resp + + class _ListEventThreatDetectionCustomModules(SecurityCenterRestStub): + def __hash__(self): + return hash("ListEventThreatDetectionCustomModules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListEventThreatDetectionCustomModulesResponse: + r"""Call the list event threat + detection custom modules method over HTTP. + + Args: + request (~.securitycenter_service.ListEventThreatDetectionCustomModulesRequest): + The request object. Request to list Event Threat + Detection custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListEventThreatDetectionCustomModulesResponse: + Response for listing Event Threat + Detection custom modules. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/customModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/customModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/customModules', + }, + ] + request, metadata = self._interceptor.pre_list_event_threat_detection_custom_modules(request, metadata) + pb_request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + pb_resp = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_event_threat_detection_custom_modules(resp) + return resp + + class _ListFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("ListFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.securitycenter_service.ListFindingsRequest): + The request object. Request message for listing findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListFindingsResponse: + Response message for listing + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/sources/*}/findings', + }, + ] + request, metadata = self._interceptor.pre_list_findings(request, metadata) + pb_request = securitycenter_service.ListFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListFindingsResponse() + pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListMuteConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListMuteConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListMuteConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListMuteConfigsResponse: + r"""Call the list mute configs method over HTTP. + + Args: + request (~.securitycenter_service.ListMuteConfigsRequest): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or 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: + ~.securitycenter_service.ListMuteConfigsResponse: + Response message for listing mute + configs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/locations/*/muteConfigs}', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/locations/*/muteConfigs}', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/muteConfigs}', + }, + ] + request, metadata = self._interceptor.pre_list_mute_configs(request, metadata) + pb_request = securitycenter_service.ListMuteConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListMuteConfigsResponse() + pb_resp = securitycenter_service.ListMuteConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_mute_configs(resp) + return resp + + class _ListNotificationConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListNotificationConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListNotificationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListNotificationConfigsResponse: + r"""Call the list notification configs method over HTTP. + + Args: + request (~.securitycenter_service.ListNotificationConfigsRequest): + The request object. Request message for listing + notification configs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListNotificationConfigsResponse: + Response message for listing + notification configs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*}/notificationConfigs', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*}/notificationConfigs', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*}/notificationConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_notification_configs(request, metadata) + pb_request = securitycenter_service.ListNotificationConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListNotificationConfigsResponse() + pb_resp = securitycenter_service.ListNotificationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_notification_configs(resp) + return resp + + class _ListResourceValueConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListResourceValueConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListResourceValueConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListResourceValueConfigsResponse: + r"""Call the list resource value + configs method over HTTP. + + Args: + request (~.securitycenter_service.ListResourceValueConfigsRequest): + The request object. Request message to list resource + value configs of a parent + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListResourceValueConfigsResponse: + Response message to list resource + value configs + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*}/resourceValueConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_resource_value_configs(request, metadata) + pb_request = securitycenter_service.ListResourceValueConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListResourceValueConfigsResponse() + pb_resp = securitycenter_service.ListResourceValueConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_resource_value_configs(resp) + return resp + + class _ListSecurityHealthAnalyticsCustomModules(SecurityCenterRestStub): + def __hash__(self): + return hash("ListSecurityHealthAnalyticsCustomModules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse: + r"""Call the list security health + analytics custom modules method over HTTP. + + Args: + request (~.securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): + The request object. Request message for listing Security + Health Analytics custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse: + Response message for listing Security + Health Analytics custom modules. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules', + }, + ] + request, metadata = self._interceptor.pre_list_security_health_analytics_custom_modules(request, metadata) + pb_request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + pb_resp = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_security_health_analytics_custom_modules(resp) + return resp + + class _ListSources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListSources") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListSourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListSourcesResponse: + r"""Call the list sources method over HTTP. + + Args: + request (~.securitycenter_service.ListSourcesRequest): + The request object. Request message for listing sources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListSourcesResponse: + Response message for listing sources. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*}/sources', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=folders/*}/sources', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*}/sources', + }, + ] + request, metadata = self._interceptor.pre_list_sources(request, metadata) + pb_request = securitycenter_service.ListSourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListSourcesResponse() + pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sources(resp) + return resp + + class _ListValuedResources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListValuedResources") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListValuedResourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListValuedResourcesResponse: + r"""Call the list valued resources method over HTTP. + + Args: + request (~.securitycenter_service.ListValuedResourcesRequest): + The request object. Request message for listing the + valued resources for a given simulation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListValuedResourcesResponse: + Response message for listing the + valued resources for a given simulation. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/simulations/*}/valuedResources', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/simulations/*/attackExposureResults/*}/valuedResources', + }, + ] + request, metadata = self._interceptor.pre_list_valued_resources(request, metadata) + pb_request = securitycenter_service.ListValuedResourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListValuedResourcesResponse() + pb_resp = securitycenter_service.ListValuedResourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_valued_resources(resp) + return resp + + class _RunAssetDiscovery(SecurityCenterRestStub): + def __hash__(self): + return hash("RunAssetDiscovery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.RunAssetDiscoveryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the run asset discovery method over HTTP. + + Args: + request (~.securitycenter_service.RunAssetDiscoveryRequest): + The request object. Request message for running asset + discovery for an organization. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*}/assets:runDiscovery', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_run_asset_discovery(request, metadata) + pb_request = securitycenter_service.RunAssetDiscoveryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_run_asset_discovery(resp) + return resp + + class _SetFindingState(SecurityCenterRestStub): + def __hash__(self): + return hash("SetFindingState") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SetFindingStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the set finding state method over HTTP. + + Args: + request (~.securitycenter_service.SetFindingStateRequest): + The request object. Request message for updating a + finding's state. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=organizations/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{name=folders/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/sources/*/findings/*}:setState', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_finding_state(request, metadata) + pb_request = securitycenter_service.SetFindingStateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_set_finding_state(resp) + return resp + + class _SetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=organizations/*/sources/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _SetMute(SecurityCenterRestStub): + def __hash__(self): + return hash("SetMute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SetMuteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the set mute method over HTTP. + + Args: + request (~.securitycenter_service.SetMuteRequest): + The request object. Request message for updating a + finding's mute status. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=organizations/*/sources/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{name=folders/*/sources/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/sources/*/findings/*}:setMute', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_mute(request, metadata) + pb_request = securitycenter_service.SetMuteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_set_mute(resp) + return resp + + class _SimulateSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("SimulateSecurityHealthAnalyticsCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: + r"""Call the simulate security health + analytics custom module method over HTTP. + + Args: + request (~.securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): + The request object. Request message to simulate a + CustomConfig against a given test + resource. Maximum size of the request is + 4 MB by default. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: + Response message for simulating a + ``SecurityHealthAnalyticsCustomModule`` against a given + resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules:simulate', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules:simulate', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules:simulate', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_simulate_security_health_analytics_custom_module(request, metadata) + pb_request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + pb_resp = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_simulate_security_health_analytics_custom_module(resp) + return resp + + class _TestIamPermissions(SecurityCenterRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=organizations/*/sources/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UpdateBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> bigquery_export.BigQueryExport: + r"""Call the update big query export method over HTTP. + + Args: + request (~.securitycenter_service.UpdateBigQueryExportRequest): + The request object. Request message for updating a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{big_query_export.name=organizations/*/bigQueryExports/*}', + 'body': 'big_query_export', + }, +{ + 'method': 'patch', + 'uri': '/v1/{big_query_export.name=folders/*/bigQueryExports/*}', + 'body': 'big_query_export', + }, +{ + 'method': 'patch', + 'uri': '/v1/{big_query_export.name=projects/*/bigQueryExports/*}', + 'body': 'big_query_export', + }, + ] + request, metadata = self._interceptor.pre_update_big_query_export(request, metadata) + pb_request = securitycenter_service.UpdateBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_big_query_export(resp) + return resp + + class _UpdateEventThreatDetectionCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateEventThreatDetectionCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + r"""Call the update event threat + detection custom module method over HTTP. + + Args: + request (~.securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): + The request object. Request to update an Event Threat + Detection custom module. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: + Represents an instance of an Event + Threat Detection custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by child folders and projects. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{event_threat_detection_custom_module.name=organizations/*/eventThreatDetectionSettings/customModules/*}', + 'body': 'event_threat_detection_custom_module', + }, +{ + 'method': 'patch', + 'uri': '/v1/{event_threat_detection_custom_module.name=folders/*/eventThreatDetectionSettings/customModules/*}', + 'body': 'event_threat_detection_custom_module', + }, +{ + 'method': 'patch', + 'uri': '/v1/{event_threat_detection_custom_module.name=projects/*/eventThreatDetectionSettings/customModules/*}', + 'body': 'event_threat_detection_custom_module', + }, + ] + request, metadata = self._interceptor.pre_update_event_threat_detection_custom_module(request, metadata) + pb_request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + pb_resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_event_threat_detection_custom_module(resp) + return resp + + class _UpdateExternalSystem(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateExternalSystem") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateExternalSystemRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_external_system.ExternalSystem: + r"""Call the update external system method over HTTP. + + Args: + request (~.securitycenter_service.UpdateExternalSystemRequest): + The request object. Request message for updating a + ExternalSystem resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_external_system.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v1/{external_system.name=folders/*/sources/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v1/{external_system.name=projects/*/sources/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, + ] + request, metadata = self._interceptor.pre_update_external_system(request, metadata) + pb_request = securitycenter_service.UpdateExternalSystemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_external_system.ExternalSystem() + pb_resp = gcs_external_system.ExternalSystem.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_external_system(resp) + return resp + + class _UpdateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the update finding method over HTTP. + + Args: + request (~.securitycenter_service.UpdateFindingRequest): + The request object. Request message for updating or + creating a finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{finding.name=organizations/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v1/{finding.name=folders/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v1/{finding.name=projects/*/sources/*/findings/*}', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_update_finding(request, metadata) + pb_request = securitycenter_service.UpdateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_finding(resp) + return resp + + class _UpdateMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_mute_config.MuteConfig: + r"""Call the update mute config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateMuteConfigRequest): + The request object. Request message for updating a mute + config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{mute_config.name=organizations/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{mute_config.name=folders/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{mute_config.name=projects/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{mute_config.name=organizations/*/locations/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{mute_config.name=folders/*/locations/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{mute_config.name=projects/*/locations/*/muteConfigs/*}', + 'body': 'mute_config', + }, + ] + request, metadata = self._interceptor.pre_update_mute_config(request, metadata) + pb_request = securitycenter_service.UpdateMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_mute_config.MuteConfig() + pb_resp = gcs_mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_mute_config(resp) + return resp + + class _UpdateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the update notification + config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateNotificationConfigRequest): + The request object. Request message for updating a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{notification_config.name=organizations/*/notificationConfigs/*}', + 'body': 'notification_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{notification_config.name=folders/*/notificationConfigs/*}', + 'body': 'notification_config', + }, +{ + 'method': 'patch', + 'uri': '/v1/{notification_config.name=projects/*/notificationConfigs/*}', + 'body': 'notification_config', + }, + ] + request, metadata = self._interceptor.pre_update_notification_config(request, metadata) + pb_request = securitycenter_service.UpdateNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_notification_config(resp) + return resp + + class _UpdateOrganizationSettings(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateOrganizationSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateOrganizationSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Call the update organization + settings method over HTTP. + + Args: + request (~.securitycenter_service.UpdateOrganizationSettingsRequest): + The request object. Request message for updating an + organization's 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: + ~.gcs_organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{organization_settings.name=organizations/*/organizationSettings}', + 'body': 'organization_settings', + }, + ] + request, metadata = self._interceptor.pre_update_organization_settings(request, metadata) + pb_request = securitycenter_service.UpdateOrganizationSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_organization_settings.OrganizationSettings() + pb_resp = gcs_organization_settings.OrganizationSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_organization_settings(resp) + return resp + + class _UpdateResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateResourceValueConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateResourceValueConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Call the update resource value + config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateResourceValueConfigRequest): + The request object. Request message to update resource + value config + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_resource_value_config.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{resource_value_config.name=organizations/*/resourceValueConfigs/*}', + 'body': 'resource_value_config', + }, + ] + request, metadata = self._interceptor.pre_update_resource_value_config(request, metadata) + pb_request = securitycenter_service.UpdateResourceValueConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_resource_value_config.ResourceValueConfig() + pb_resp = gcs_resource_value_config.ResourceValueConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_resource_value_config(resp) + return resp + + class _UpdateSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSecurityHealthAnalyticsCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + r"""Call the update security health + analytics custom module method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): + The request object. Request message for updating Security + Health Analytics custom modules. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: + Represents an instance of a Security + Health Analytics custom module, + including its full module name, display + name, enablement state, and last updated + time. You can create a custom module at + the organization, folder, or project + level. Custom modules that you create at + the organization or folder level are + inherited by the child folders and + projects. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{security_health_analytics_custom_module.name=organizations/*/securityHealthAnalyticsSettings/customModules/*}', + 'body': 'security_health_analytics_custom_module', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_health_analytics_custom_module.name=folders/*/securityHealthAnalyticsSettings/customModules/*}', + 'body': 'security_health_analytics_custom_module', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_health_analytics_custom_module.name=projects/*/securityHealthAnalyticsSettings/customModules/*}', + 'body': 'security_health_analytics_custom_module', + }, + ] + request, metadata = self._interceptor.pre_update_security_health_analytics_custom_module(request, metadata) + pb_request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + pb_resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_security_health_analytics_custom_module(resp) + return resp + + class _UpdateSecurityMarks(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSecurityMarks") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSecurityMarksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_security_marks.SecurityMarks: + r"""Call the update security marks method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSecurityMarksRequest): + The request object. Request message for updating a + SecurityMarks resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{security_marks.name=organizations/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_marks.name=folders/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_marks.name=projects/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, + ] + request, metadata = self._interceptor.pre_update_security_marks(request, metadata) + pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_security_marks.SecurityMarks() + pb_resp = gcs_security_marks.SecurityMarks.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_security_marks(resp) + return resp + + class _UpdateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the update source method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSourceRequest): + The request object. Request message for updating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{source.name=organizations/*/sources/*}', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_update_source(request, metadata) + pb_request = securitycenter_service.UpdateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_source(resp) + return resp + + class _ValidateEventThreatDetectionCustomModule(SecurityCenterRestStub): + def __hash__(self): + return hash("ValidateEventThreatDetectionCustomModule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: + r"""Call the validate event threat + detection custom module method over HTTP. + + Args: + request (~.securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): + The request object. Request to validate an Event Threat + Detection custom module. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: + Response to validating an Event + Threat Detection custom module. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}:validateCustomModule', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}:validateCustomModule', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}:validateCustomModule', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_validate_event_threat_detection_custom_module(request, metadata) + pb_request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() + pb_resp = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_validate_event_threat_detection_custom_module(resp) + return resp + + @property + def batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + securitycenter_service.BatchCreateResourceValueConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreateResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + 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._BulkMuteFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], + gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], + gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + 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._DeleteBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], + 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._DeleteEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + 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._DeleteMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + 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._DeleteNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + 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._DeleteResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], + 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._DeleteSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + bigquery_export.BigQueryExport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_effective_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEffectiveEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_effective_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEffectiveSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], + event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + mute_config.MuteConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + resource_value_config.ResourceValueConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + simulation.Simulation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSimulation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + valued_resource.ValuedResource]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetValuedResource(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + securitycenter_service.ListAttackPathsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAttackPaths(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + securitycenter_service.ListBigQueryExportsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBigQueryExports(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDescendantEventThreatDetectionCustomModules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDescendantSecurityHealthAnalyticsCustomModules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_effective_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEffectiveEventThreatDetectionCustomModules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_effective_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEffectiveSecurityHealthAnalyticsCustomModules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_event_threat_detection_custom_modules(self) -> Callable[ + [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], + securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEventThreatDetectionCustomModules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.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_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + securitycenter_service.ListMuteConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMuteConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListNotificationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + securitycenter_service.ListResourceValueConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_security_health_analytics_custom_modules(self) -> Callable[ + [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSecurityHealthAnalyticsCustomModules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + securitycenter_service.ListValuedResourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListValuedResources(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + 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._RunAssetDiscovery(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + 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._SetMute(self._session, self._host, self._interceptor) # type: ignore + + @property + def simulate_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SimulateSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], + gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + gcs_external_system.ExternalSystem]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateExternalSystem(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + gcs_resource_value_config.ResourceValueConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_security_health_analytics_custom_module(self) -> Callable[ + [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], + gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def validate_event_threat_detection_custom_module(self) -> Callable[ + [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], + securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ValidateEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=organizations/*/operations/*}:cancel', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In 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(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In 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(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), 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(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/operations}', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SecurityCenterRestTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py new file mode 100644 index 000000000000..fae209c726d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py @@ -0,0 +1,440 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .access import ( + Access, + Geolocation, + ServiceAccountDelegationInfo, +) +from .application import ( + Application, +) +from .asset import ( + Asset, +) +from .attack_exposure import ( + AttackExposure, +) +from .attack_path import ( + AttackPath, +) +from .backup_disaster_recovery import ( + BackupDisasterRecovery, +) +from .bigquery_export import ( + BigQueryExport, +) +from .cloud_armor import ( + AdaptiveProtection, + Attack, + CloudArmor, + Requests, + SecurityPolicy, +) +from .cloud_dlp_data_profile import ( + CloudDlpDataProfile, +) +from .cloud_dlp_inspection import ( + CloudDlpInspection, +) +from .compliance import ( + Compliance, +) +from .connection import ( + Connection, +) +from .contact_details import ( + Contact, + ContactDetails, +) +from .container import ( + Container, +) +from .database import ( + Database, +) +from .effective_event_threat_detection_custom_module import ( + EffectiveEventThreatDetectionCustomModule, +) +from .effective_security_health_analytics_custom_module import ( + EffectiveSecurityHealthAnalyticsCustomModule, +) +from .event_threat_detection_custom_module import ( + EventThreatDetectionCustomModule, +) +from .event_threat_detection_custom_module_validation_errors import ( + CustomModuleValidationError, + CustomModuleValidationErrors, + Position, +) +from .exfiltration import ( + ExfilResource, + Exfiltration, +) +from .external_system import ( + ExternalSystem, +) +from .file import ( + File, +) +from .finding import ( + Finding, +) +from .folder import ( + Folder, +) +from .group_membership import ( + GroupMembership, +) +from .iam_binding import ( + IamBinding, +) +from .indicator import ( + Indicator, +) +from .kernel_rootkit import ( + KernelRootkit, +) +from .kubernetes import ( + Kubernetes, +) +from .label import ( + Label, +) +from .load_balancer import ( + LoadBalancer, +) +from .log_entry import ( + CloudLoggingEntry, + LogEntry, +) +from .mitre_attack import ( + MitreAttack, +) +from .mute_config import ( + MuteConfig, +) +from .notebook import ( + Notebook, +) +from .notification_config import ( + NotificationConfig, +) +from .notification_message import ( + NotificationMessage, +) +from .org_policy import ( + OrgPolicy, +) +from .organization_settings import ( + OrganizationSettings, +) +from .process import ( + EnvironmentVariable, + Process, +) +from .resource import ( + AwsMetadata, + AzureMetadata, + Resource, + ResourcePath, + CloudProvider, +) +from .resource_value_config import ( + ResourceValueConfig, + ResourceValue, +) +from .run_asset_discovery_response import ( + RunAssetDiscoveryResponse, +) +from .security_health_analytics_custom_config import ( + CustomConfig, +) +from .security_health_analytics_custom_module import ( + SecurityHealthAnalyticsCustomModule, +) +from .security_marks import ( + SecurityMarks, +) +from .security_posture import ( + SecurityPosture, +) +from .securitycenter_service import ( + BatchCreateResourceValueConfigsRequest, + BatchCreateResourceValueConfigsResponse, + BulkMuteFindingsRequest, + BulkMuteFindingsResponse, + CreateBigQueryExportRequest, + CreateEventThreatDetectionCustomModuleRequest, + CreateFindingRequest, + CreateMuteConfigRequest, + CreateNotificationConfigRequest, + CreateResourceValueConfigRequest, + CreateSecurityHealthAnalyticsCustomModuleRequest, + CreateSourceRequest, + DeleteBigQueryExportRequest, + DeleteEventThreatDetectionCustomModuleRequest, + DeleteMuteConfigRequest, + DeleteNotificationConfigRequest, + DeleteResourceValueConfigRequest, + DeleteSecurityHealthAnalyticsCustomModuleRequest, + GetBigQueryExportRequest, + GetEffectiveEventThreatDetectionCustomModuleRequest, + GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, + GetEventThreatDetectionCustomModuleRequest, + GetMuteConfigRequest, + GetNotificationConfigRequest, + GetOrganizationSettingsRequest, + GetResourceValueConfigRequest, + GetSecurityHealthAnalyticsCustomModuleRequest, + GetSimulationRequest, + GetSourceRequest, + GetValuedResourceRequest, + GroupAssetsRequest, + GroupAssetsResponse, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListAssetsRequest, + ListAssetsResponse, + ListAttackPathsRequest, + ListAttackPathsResponse, + ListBigQueryExportsRequest, + ListBigQueryExportsResponse, + ListDescendantEventThreatDetectionCustomModulesRequest, + ListDescendantEventThreatDetectionCustomModulesResponse, + ListDescendantSecurityHealthAnalyticsCustomModulesRequest, + ListDescendantSecurityHealthAnalyticsCustomModulesResponse, + ListEffectiveEventThreatDetectionCustomModulesRequest, + ListEffectiveEventThreatDetectionCustomModulesResponse, + ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, + ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, + ListEventThreatDetectionCustomModulesRequest, + ListEventThreatDetectionCustomModulesResponse, + ListFindingsRequest, + ListFindingsResponse, + ListMuteConfigsRequest, + ListMuteConfigsResponse, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListResourceValueConfigsRequest, + ListResourceValueConfigsResponse, + ListSecurityHealthAnalyticsCustomModulesRequest, + ListSecurityHealthAnalyticsCustomModulesResponse, + ListSourcesRequest, + ListSourcesResponse, + ListValuedResourcesRequest, + ListValuedResourcesResponse, + RunAssetDiscoveryRequest, + SetFindingStateRequest, + SetMuteRequest, + SimulateSecurityHealthAnalyticsCustomModuleRequest, + SimulateSecurityHealthAnalyticsCustomModuleResponse, + UpdateBigQueryExportRequest, + UpdateEventThreatDetectionCustomModuleRequest, + UpdateExternalSystemRequest, + UpdateFindingRequest, + UpdateMuteConfigRequest, + UpdateNotificationConfigRequest, + UpdateOrganizationSettingsRequest, + UpdateResourceValueConfigRequest, + UpdateSecurityHealthAnalyticsCustomModuleRequest, + UpdateSecurityMarksRequest, + UpdateSourceRequest, + ValidateEventThreatDetectionCustomModuleRequest, + ValidateEventThreatDetectionCustomModuleResponse, +) +from .simulation import ( + Simulation, +) +from .source import ( + Source, +) +from .toxic_combination import ( + ToxicCombination, +) +from .valued_resource import ( + ResourceValueConfigMetadata, + ValuedResource, +) +from .vulnerability import ( + Cve, + Cvssv3, + Package, + Reference, + SecurityBulletin, + Vulnerability, +) + +__all__ = ( + 'Access', + 'Geolocation', + 'ServiceAccountDelegationInfo', + 'Application', + 'Asset', + 'AttackExposure', + 'AttackPath', + 'BackupDisasterRecovery', + 'BigQueryExport', + 'AdaptiveProtection', + 'Attack', + 'CloudArmor', + 'Requests', + 'SecurityPolicy', + 'CloudDlpDataProfile', + 'CloudDlpInspection', + 'Compliance', + 'Connection', + 'Contact', + 'ContactDetails', + 'Container', + 'Database', + 'EffectiveEventThreatDetectionCustomModule', + 'EffectiveSecurityHealthAnalyticsCustomModule', + 'EventThreatDetectionCustomModule', + 'CustomModuleValidationError', + 'CustomModuleValidationErrors', + 'Position', + 'ExfilResource', + 'Exfiltration', + 'ExternalSystem', + 'File', + 'Finding', + 'Folder', + 'GroupMembership', + 'IamBinding', + 'Indicator', + 'KernelRootkit', + 'Kubernetes', + 'Label', + 'LoadBalancer', + 'CloudLoggingEntry', + 'LogEntry', + 'MitreAttack', + 'MuteConfig', + 'Notebook', + 'NotificationConfig', + 'NotificationMessage', + 'OrgPolicy', + 'OrganizationSettings', + 'EnvironmentVariable', + 'Process', + 'AwsMetadata', + 'AzureMetadata', + 'Resource', + 'ResourcePath', + 'CloudProvider', + 'ResourceValueConfig', + 'ResourceValue', + 'RunAssetDiscoveryResponse', + 'CustomConfig', + 'SecurityHealthAnalyticsCustomModule', + 'SecurityMarks', + 'SecurityPosture', + 'BatchCreateResourceValueConfigsRequest', + 'BatchCreateResourceValueConfigsResponse', + 'BulkMuteFindingsRequest', + 'BulkMuteFindingsResponse', + 'CreateBigQueryExportRequest', + 'CreateEventThreatDetectionCustomModuleRequest', + 'CreateFindingRequest', + 'CreateMuteConfigRequest', + 'CreateNotificationConfigRequest', + 'CreateResourceValueConfigRequest', + 'CreateSecurityHealthAnalyticsCustomModuleRequest', + 'CreateSourceRequest', + 'DeleteBigQueryExportRequest', + 'DeleteEventThreatDetectionCustomModuleRequest', + 'DeleteMuteConfigRequest', + 'DeleteNotificationConfigRequest', + 'DeleteResourceValueConfigRequest', + 'DeleteSecurityHealthAnalyticsCustomModuleRequest', + 'GetBigQueryExportRequest', + 'GetEffectiveEventThreatDetectionCustomModuleRequest', + 'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', + 'GetEventThreatDetectionCustomModuleRequest', + 'GetMuteConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetResourceValueConfigRequest', + 'GetSecurityHealthAnalyticsCustomModuleRequest', + 'GetSimulationRequest', + 'GetSourceRequest', + 'GetValuedResourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListAttackPathsRequest', + 'ListAttackPathsResponse', + 'ListBigQueryExportsRequest', + 'ListBigQueryExportsResponse', + 'ListDescendantEventThreatDetectionCustomModulesRequest', + 'ListDescendantEventThreatDetectionCustomModulesResponse', + 'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', + 'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', + 'ListEffectiveEventThreatDetectionCustomModulesRequest', + 'ListEffectiveEventThreatDetectionCustomModulesResponse', + 'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', + 'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', + 'ListEventThreatDetectionCustomModulesRequest', + 'ListEventThreatDetectionCustomModulesResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListMuteConfigsRequest', + 'ListMuteConfigsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListResourceValueConfigsRequest', + 'ListResourceValueConfigsResponse', + 'ListSecurityHealthAnalyticsCustomModulesRequest', + 'ListSecurityHealthAnalyticsCustomModulesResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListValuedResourcesRequest', + 'ListValuedResourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'SetMuteRequest', + 'SimulateSecurityHealthAnalyticsCustomModuleRequest', + 'SimulateSecurityHealthAnalyticsCustomModuleResponse', + 'UpdateBigQueryExportRequest', + 'UpdateEventThreatDetectionCustomModuleRequest', + 'UpdateExternalSystemRequest', + 'UpdateFindingRequest', + 'UpdateMuteConfigRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateResourceValueConfigRequest', + 'UpdateSecurityHealthAnalyticsCustomModuleRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'ValidateEventThreatDetectionCustomModuleRequest', + 'ValidateEventThreatDetectionCustomModuleResponse', + 'Simulation', + 'Source', + 'ToxicCombination', + 'ResourceValueConfigMetadata', + 'ValuedResource', + 'Cve', + 'Cvssv3', + 'Package', + 'Reference', + 'SecurityBulletin', + 'Vulnerability', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py new file mode 100644 index 000000000000..46f1bc1e8a57 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v1', + manifest={ + 'Access', + 'ServiceAccountDelegationInfo', + 'Geolocation', + }, +) + + +class Access(proto.Message): + r"""Represents an access event. + + Attributes: + principal_email (str): + Associated email, such as "foo@google.com". + + The email address of the authenticated user or a service + account acting on behalf of a third party principal making + the request. For third party identity callers, the + ``principal_subject`` field is populated instead of this + field. For privacy reasons, the principal email address is + sometimes redacted. For more information, see `Caller + identities in audit + logs `__. + caller_ip (str): + Caller's IP address, such as "1.1.1.1". + caller_ip_geo (google.cloud.securitycenter_v1.types.Geolocation): + The caller IP's geolocation, which identifies + where the call came from. + user_agent_family (str): + Type of user agent associated with the + finding. For example, an operating system shell + or an embedded or standalone application. + user_agent (str): + The caller's user agent string associated + with the finding. + service_name (str): + This is the API service that the service + account made a call to, e.g. + "iam.googleapis.com". + method_name (str): + The method that the service account called, + e.g. "SetIamPolicy". + principal_subject (str): + A string that represents the principal_subject that is + associated with the identity. Unlike ``principal_email``, + ``principal_subject`` supports principals that aren't + associated with email addresses, such as third party + principals. For most identities, the format is + ``principal://iam.googleapis.com/{identity pool name}/subject/{subject}``. + Some GKE identities, such as GKE_WORKLOAD, FREEFORM, and + GKE_HUB_WORKLOAD, still use the legacy format + ``serviceAccount:{identity pool name}[{subject}]``. + service_account_key_name (str): + The name of the service account key that was used to create + or exchange credentials when authenticating the service + account that made the request. This is a scheme-less URI + full resource name. For example: + + "//iam.googleapis.com/projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}". + service_account_delegation_info (MutableSequence[google.cloud.securitycenter_v1.types.ServiceAccountDelegationInfo]): + The identity delegation history of an authenticated service + account that made the request. The + ``serviceAccountDelegationInfo[]`` object contains + information about the real authorities that try to access + Google Cloud resources by delegating on a service account. + When multiple authorities are present, they are guaranteed + to be sorted based on the original ordering of the identity + delegation events. + user_name (str): + A string that represents a username. The + username provided depends on the type of the + finding and is likely not an IAM principal. For + example, this can be a system username if the + finding is related to a virtual machine, or it + can be an application login username. + """ + + principal_email: str = proto.Field( + proto.STRING, + number=1, + ) + caller_ip: str = proto.Field( + proto.STRING, + number=2, + ) + caller_ip_geo: 'Geolocation' = proto.Field( + proto.MESSAGE, + number=3, + message='Geolocation', + ) + user_agent_family: str = proto.Field( + proto.STRING, + number=4, + ) + user_agent: str = proto.Field( + proto.STRING, + number=12, + ) + service_name: str = proto.Field( + proto.STRING, + number=5, + ) + method_name: str = proto.Field( + proto.STRING, + number=6, + ) + principal_subject: str = proto.Field( + proto.STRING, + number=7, + ) + service_account_key_name: str = proto.Field( + proto.STRING, + number=8, + ) + service_account_delegation_info: MutableSequence['ServiceAccountDelegationInfo'] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='ServiceAccountDelegationInfo', + ) + user_name: str = proto.Field( + proto.STRING, + number=11, + ) + + +class ServiceAccountDelegationInfo(proto.Message): + r"""Identity delegation history of an authenticated service + account. + + Attributes: + principal_email (str): + The email address of a Google account. + principal_subject (str): + A string representing the principal_subject associated with + the identity. As compared to ``principal_email``, supports + principals that aren't associated with email addresses, such + as third party principals. For most identities, the format + will be + ``principal://iam.googleapis.com/{identity pool name}/subjects/{subject}`` + except for some GKE identities (GKE_WORKLOAD, FREEFORM, + GKE_HUB_WORKLOAD) that are still in the legacy format + ``serviceAccount:{identity pool name}[{subject}]`` + """ + + principal_email: str = proto.Field( + proto.STRING, + number=1, + ) + principal_subject: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Geolocation(proto.Message): + r"""Represents a geographical location for a given access. + + Attributes: + region_code (str): + A CLDR. + """ + + region_code: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.py new file mode 100644 index 000000000000..96e0a3cd61dc --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Application', + }, +) + + +class Application(proto.Message): + r"""Represents an application associated with a finding. + + Attributes: + base_uri (str): + The base URI that identifies the network location of the + application in which the vulnerability was detected. For + example, ``http://example.com``. + full_uri (str): + The full URI with payload that can be used to reproduce the + vulnerability. For example, + ``http://example.com?p=aMmYgI6H``. + """ + + base_uri: str = proto.Field( + proto.STRING, + number=1, + ) + full_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py new file mode 100644 index 000000000000..5c4a957c4d1e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py @@ -0,0 +1,227 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1.types import folder +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Asset', + }, +) + + +class Asset(proto.Message): + r"""Security Command Center representation of a Google Cloud + resource. + + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All + modifications to an Asset are only within the context of + Security Command Center and don't affect the referenced Google + Cloud resource. + + Attributes: + name (str): + The relative resource name of this asset. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/assets/{asset_id}". + security_center_properties (google.cloud.securitycenter_v1.types.Asset.SecurityCenterProperties): + Security Command Center managed properties. + These properties are managed by Security Command + Center and cannot be modified by the user. + resource_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Resource managed properties. These properties + are managed and defined by the Google Cloud + resource and cannot be modified by the user. + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): + User specified security marks. These marks + are entirely managed by the user and come from + the SecurityMarks resource that belongs to the + asset. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was last updated + or added in Cloud SCC. + iam_policy (google.cloud.securitycenter_v1.types.Asset.IamPolicy): + Cloud IAM Policy information associated with + the Google Cloud resource described by the + Security Command Center asset. This information + is managed and defined by the Google Cloud + resource and cannot be modified by the user. + canonical_name (str): + The canonical name of the resource. It's either + "organizations/{organization_id}/assets/{asset_id}", + "folders/{folder_id}/assets/{asset_id}" or + "projects/{project_number}/assets/{asset_id}", depending on + the closest CRM ancestor of the resource. + """ + + class SecurityCenterProperties(proto.Message): + r"""Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified by + the user. + + Attributes: + resource_name (str): + The full resource name of the Google Cloud resource this + asset represents. This field is immutable after create time. + See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_type (str): + The type of the Google Cloud resource. + Examples include: APPLICATION, PROJECT, and + ORGANIZATION. This is a case insensitive field + defined by Security Command Center and/or the + producer of the resource and is immutable after + create time. + resource_parent (str): + The full resource name of the immediate parent of the + resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_project (str): + The full resource name of the project the resource belongs + to. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_owners (MutableSequence[str]): + Owners of the Google Cloud resource. + resource_display_name (str): + The user defined display name for this + resource. + resource_parent_display_name (str): + The user defined display name for the parent + of this resource. + resource_project_display_name (str): + The user defined display name for the project + of this resource. + folders (MutableSequence[google.cloud.securitycenter_v1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. + """ + + resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + resource_parent: str = proto.Field( + proto.STRING, + number=3, + ) + resource_project: str = proto.Field( + proto.STRING, + number=4, + ) + resource_owners: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + resource_display_name: str = proto.Field( + proto.STRING, + number=6, + ) + resource_parent_display_name: str = proto.Field( + proto.STRING, + number=7, + ) + resource_project_display_name: str = proto.Field( + proto.STRING, + number=8, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=folder.Folder, + ) + + class IamPolicy(proto.Message): + r"""Cloud IAM Policy information associated with the Google Cloud + resource described by the Security Command Center asset. This + information is managed and defined by the Google Cloud resource + and cannot be modified by the user. + + Attributes: + policy_blob (str): + The JSON representation of the Policy + associated with the asset. See + https://cloud.google.com/iam/reference/rest/v1/Policy + for format details. + """ + + policy_blob: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + security_center_properties: SecurityCenterProperties = proto.Field( + proto.MESSAGE, + number=2, + message=SecurityCenterProperties, + ) + resource_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + iam_policy: IamPolicy = proto.Field( + proto.MESSAGE, + number=11, + message=IamPolicy, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=13, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.py new file mode 100644 index 000000000000..71c641c4f226 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'AttackExposure', + }, +) + + +class AttackExposure(proto.Message): + r"""An attack exposure contains the results of an attack path + simulation run. + + Attributes: + score (float): + A number between 0 (inclusive) and infinity + that represents how important this finding is to + remediate. The higher the score, the more + important it is to remediate. + latest_calculation_time (google.protobuf.timestamp_pb2.Timestamp): + The most recent time the attack exposure was + updated on this finding. + attack_exposure_result (str): + The resource name of the attack path simulation result that + contains the details regarding this attack exposure score. + Example: + ``organizations/123/simulations/456/attackExposureResults/789`` + state (google.cloud.securitycenter_v1.types.AttackExposure.State): + What state this AttackExposure is in. This + captures whether or not an attack exposure has + been calculated or not. + exposed_high_value_resources_count (int): + The number of high value resources that are + exposed as a result of this finding. + exposed_medium_value_resources_count (int): + The number of medium value resources that are + exposed as a result of this finding. + exposed_low_value_resources_count (int): + The number of high value resources that are + exposed as a result of this finding. + """ + class State(proto.Enum): + r"""This enum defines the various states an AttackExposure can be + in. + + Values: + STATE_UNSPECIFIED (0): + The state is not specified. + CALCULATED (1): + The attack exposure has been calculated. + NOT_CALCULATED (2): + The attack exposure has not been calculated. + """ + STATE_UNSPECIFIED = 0 + CALCULATED = 1 + NOT_CALCULATED = 2 + + score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + latest_calculation_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + attack_exposure_result: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + exposed_high_value_resources_count: int = proto.Field( + proto.INT32, + number=5, + ) + exposed_medium_value_resources_count: int = proto.Field( + proto.INT32, + number=6, + ) + exposed_low_value_resources_count: int = proto.Field( + proto.INT32, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py new file mode 100644 index 000000000000..d298b28f7407 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v1', + manifest={ + 'AttackPath', + }, +) + + +class AttackPath(proto.Message): + r"""A path that an attacker could take to reach an exposed + resource. + + Attributes: + name (str): + The attack path name, for example, + ``organizations/12/simulation/34/valuedResources/56/attackPaths/78`` + path_nodes (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode]): + A list of nodes that exist in this attack + path. + edges (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathEdge]): + A list of the edges between nodes in this + attack path. + """ + + class AttackPathNode(proto.Message): + r"""Represents one point that an attacker passes through in this + attack path. + + Attributes: + resource (str): + The name of the resource at this point in the attack path. + The format of the name follows the Cloud Asset Inventory + `resource name + format `__ + resource_type (str): + The `supported resource + type `__ + display_name (str): + Human-readable name of this resource. + associated_findings (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode.PathNodeAssociatedFinding]): + The findings associated with this node in the + attack path. + uuid (str): + Unique id of the attack path node. + attack_steps (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode.AttackStepNode]): + A list of attack step nodes that exist in + this attack path node. + """ + class NodeType(proto.Enum): + r"""The type of the incoming attack step node. + + Values: + NODE_TYPE_UNSPECIFIED (0): + Type not specified + NODE_TYPE_AND (1): + Incoming edge joined with AND + NODE_TYPE_OR (2): + Incoming edge joined with OR + NODE_TYPE_DEFENSE (3): + Incoming edge is defense + NODE_TYPE_ATTACKER (4): + Incoming edge is attacker + """ + NODE_TYPE_UNSPECIFIED = 0 + NODE_TYPE_AND = 1 + NODE_TYPE_OR = 2 + NODE_TYPE_DEFENSE = 3 + NODE_TYPE_ATTACKER = 4 + + class PathNodeAssociatedFinding(proto.Message): + r"""A finding that is associated with this node in the attack + path. + + Attributes: + canonical_finding (str): + Canonical name of the associated findings. Example: + ``organizations/123/sources/456/findings/789`` + finding_category (str): + The additional taxonomy group within findings + from a given source. + name (str): + Full resource name of the finding. + """ + + canonical_finding: str = proto.Field( + proto.STRING, + number=1, + ) + finding_category: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class AttackStepNode(proto.Message): + r"""Detailed steps the attack can take between path nodes. + + Attributes: + uuid (str): + Unique ID for one Node + type_ (google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode.NodeType): + Attack step type. Can be either AND, OR or + DEFENSE + display_name (str): + User friendly name of the attack step + labels (MutableMapping[str, str]): + Attack step labels for metadata + description (str): + Attack step description + """ + + uuid: str = proto.Field( + proto.STRING, + number=1, + ) + type_: 'AttackPath.AttackPathNode.NodeType' = proto.Field( + proto.ENUM, + number=2, + enum='AttackPath.AttackPathNode.NodeType', + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + + resource: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + associated_findings: MutableSequence['AttackPath.AttackPathNode.PathNodeAssociatedFinding'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AttackPath.AttackPathNode.PathNodeAssociatedFinding', + ) + uuid: str = proto.Field( + proto.STRING, + number=5, + ) + attack_steps: MutableSequence['AttackPath.AttackPathNode.AttackStepNode'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='AttackPath.AttackPathNode.AttackStepNode', + ) + + class AttackPathEdge(proto.Message): + r"""Represents a connection between a source node and a + destination node in this attack path. + + Attributes: + source (str): + The attack node uuid of the source node. + destination (str): + The attack node uuid of the destination node. + """ + + source: str = proto.Field( + proto.STRING, + number=1, + ) + destination: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + path_nodes: MutableSequence[AttackPathNode] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=AttackPathNode, + ) + edges: MutableSequence[AttackPathEdge] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=AttackPathEdge, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py new file mode 100644 index 000000000000..2497cff8afd8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v1', + manifest={ + 'BackupDisasterRecovery', + }, +) + + +class BackupDisasterRecovery(proto.Message): + r"""Information related to Google Cloud Backup and DR Service + findings. + + Attributes: + backup_template (str): + The name of a Backup and DR template which comprises one or + more backup policies. See the `Backup and DR + documentation `__ + for more information. For example, ``snap-ov``. + policies (MutableSequence[str]): + The names of Backup and DR policies that are associated with + a template and that define when to run a backup, how + frequently to run a backup, and how long to retain the + backup image. For example, ``onvaults``. + host (str): + The name of a Backup and DR host, which is managed by the + backup and recovery appliance and known to the management + console. The host can be of type Generic (for example, + Compute Engine, SQL Server, Oracle DB, SMB file system, + etc.), vCenter, or an ESX server. See the `Backup and DR + documentation on + hosts `__ + for more information. For example, ``centos7-01``. + applications (MutableSequence[str]): + The names of Backup and DR applications. An application is a + VM, database, or file system on a managed host monitored by + a backup and recovery appliance. For example, + ``centos7-01-vol00``, ``centos7-01-vol01``, + ``centos7-01-vol02``. + storage_pool (str): + The name of the Backup and DR storage pool that the backup + and recovery appliance is storing data in. The storage pool + could be of type Cloud, Primary, Snapshot, or OnVault. See + the `Backup and DR documentation on storage + pools `__. + For example, ``DiskPoolOne``. + policy_options (MutableSequence[str]): + The names of Backup and DR advanced policy options of a + policy applying to an application. See the `Backup and DR + documentation on policy + options `__. + For example, ``skipofflineappsincongrp, nounmap``. + profile (str): + The name of the Backup and DR resource profile that + specifies the storage media for backups of application and + VM data. See the `Backup and DR documentation on + profiles `__. + For example, ``GCP``. + appliance (str): + The name of the Backup and DR appliance that captures, + moves, and manages the lifecycle of backup data. For + example, ``backup-server-57137``. + backup_type (str): + The backup type of the Backup and DR image. For example, + ``Snapshot``, ``Remote Snapshot``, ``OnVault``. + backup_create_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp at which the Backup and DR + backup was created. + """ + + backup_template: str = proto.Field( + proto.STRING, + number=1, + ) + policies: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + host: str = proto.Field( + proto.STRING, + number=3, + ) + applications: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + storage_pool: str = proto.Field( + proto.STRING, + number=5, + ) + policy_options: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + profile: str = proto.Field( + proto.STRING, + number=7, + ) + appliance: str = proto.Field( + proto.STRING, + number=8, + ) + backup_type: str = proto.Field( + proto.STRING, + number=9, + ) + backup_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py new file mode 100644 index 000000000000..9e8288f7fd7b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py @@ -0,0 +1,135 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v1', + manifest={ + 'BigQueryExport', + }, +) + + +class BigQueryExport(proto.Message): + r"""Configures how to deliver Findings to BigQuery Instance. + + Attributes: + name (str): + The relative resource name of this export. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name. + Example format: + "organizations/{organization_id}/bigQueryExports/{export_id}" + Example format: + "folders/{folder_id}/bigQueryExports/{export_id}" Example + format: "projects/{project_id}/bigQueryExports/{export_id}" + This field is provided in responses, and is ignored when + provided in create requests. + description (str): + The description of the export (max of 1024 + characters). + filter (str): + Expression that defines the filter to apply across + create/update events of findings. The expression is a list + of zero or more restrictions combined via logical operators + ``AND`` and ``OR``. Parentheses are supported, and ``OR`` + has higher precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + dataset (str): + The dataset to write findings' updates to. Its format is + "projects/[project_id]/datasets/[bigquery_dataset_id]". + BigQuery Dataset unique ID must contain only letters (a-z, + A-Z), numbers (0-9), or underscores (_). + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the BigQuery + export was created. This field is set by the + server and will be ignored if provided on export + on creation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time at which + the BigQuery export was updated. This field is + set by the server and will be ignored if + provided on export creation or update. + most_recent_editor (str): + Output only. Email address of the user who + last edited the BigQuery export. This field is + set by the server and will be ignored if + provided on export creation or update. + principal (str): + Output only. The service account that needs + permission to create table and upload data to + the BigQuery dataset. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + dataset: 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, + ) + most_recent_editor: str = proto.Field( + proto.STRING, + number=7, + ) + principal: str = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.py new file mode 100644 index 000000000000..45b7e2fb7d51 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.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.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'CloudArmor', + 'SecurityPolicy', + 'Requests', + 'AdaptiveProtection', + 'Attack', + }, +) + + +class CloudArmor(proto.Message): + r"""Fields related to Google Cloud Armor findings. + + Attributes: + security_policy (google.cloud.securitycenter_v1.types.SecurityPolicy): + Information about the `Google Cloud Armor security + policy `__ + relevant to the finding. + requests (google.cloud.securitycenter_v1.types.Requests): + Information about incoming requests evaluated by `Google + Cloud Armor security + policies `__. + adaptive_protection (google.cloud.securitycenter_v1.types.AdaptiveProtection): + Information about potential Layer 7 DDoS attacks identified + by `Google Cloud Armor Adaptive + Protection `__. + attack (google.cloud.securitycenter_v1.types.Attack): + Information about DDoS attack volume and + classification. + threat_vector (str): + Distinguish between volumetric & protocol DDoS attack and + application layer attacks. For example, "L3_4" for Layer 3 + and Layer 4 DDoS attacks, or "L_7" for Layer 7 DDoS attacks. + duration (google.protobuf.duration_pb2.Duration): + Duration of attack from the start until the + current moment (updated every 5 minutes). + """ + + security_policy: 'SecurityPolicy' = proto.Field( + proto.MESSAGE, + number=1, + message='SecurityPolicy', + ) + requests: 'Requests' = proto.Field( + proto.MESSAGE, + number=2, + message='Requests', + ) + adaptive_protection: 'AdaptiveProtection' = proto.Field( + proto.MESSAGE, + number=3, + message='AdaptiveProtection', + ) + attack: 'Attack' = proto.Field( + proto.MESSAGE, + number=4, + message='Attack', + ) + threat_vector: str = proto.Field( + proto.STRING, + number=5, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + + +class SecurityPolicy(proto.Message): + r"""Information about the `Google Cloud Armor security + policy `__ + relevant to the finding. + + Attributes: + name (str): + The name of the Google Cloud Armor security + policy, for example, "my-security-policy". + type_ (str): + The type of Google Cloud Armor security + policy for example, 'backend security policy', + 'edge security policy', 'network edge security + policy', or 'always-on DDoS protection'. + preview (bool): + Whether or not the associated rule or policy + is in preview mode. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + preview: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class Requests(proto.Message): + r"""Information about the requests relevant to the finding. + + Attributes: + ratio (float): + For 'Increasing deny ratio', the ratio is the + denied traffic divided by the allowed traffic. + For 'Allowed traffic spike', the ratio is the + allowed traffic in the short term divided by + allowed traffic in the long term. + short_term_allowed (int): + Allowed RPS (requests per second) in the + short term. + long_term_allowed (int): + Allowed RPS (requests per second) over the + long term. + long_term_denied (int): + Denied RPS (requests per second) over the + long term. + """ + + ratio: float = proto.Field( + proto.DOUBLE, + number=1, + ) + short_term_allowed: int = proto.Field( + proto.INT32, + number=2, + ) + long_term_allowed: int = proto.Field( + proto.INT32, + number=3, + ) + long_term_denied: int = proto.Field( + proto.INT32, + number=4, + ) + + +class AdaptiveProtection(proto.Message): + r"""Information about `Google Cloud Armor Adaptive + Protection `__. + + Attributes: + confidence (float): + A score of 0 means that there is low confidence that the + detected event is an actual attack. A score of 1 means that + there is high confidence that the detected event is an + attack. See the `Adaptive Protection + documentation `__ + for further explanation. + """ + + confidence: float = proto.Field( + proto.DOUBLE, + number=1, + ) + + +class Attack(proto.Message): + r"""Information about DDoS attack volume and classification. + + Attributes: + volume_pps (int): + Total PPS (packets per second) volume of + attack. + volume_bps (int): + Total BPS (bytes per second) volume of + attack. + classification (str): + Type of attack, for example, 'SYN-flood', + 'NTP-udp', or 'CHARGEN-udp'. + """ + + volume_pps: int = proto.Field( + proto.INT32, + number=1, + ) + volume_bps: int = proto.Field( + proto.INT32, + number=2, + ) + classification: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.py new file mode 100644 index 000000000000..52cece2651fc --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.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.cloud.securitycenter.v1', + manifest={ + 'CloudDlpDataProfile', + }, +) + + +class CloudDlpDataProfile(proto.Message): + r"""The `data + profile `__ + associated with the finding. + + Attributes: + data_profile (str): + Name of the data profile, for example, + ``projects/123/locations/europe/tableProfiles/8383929``. + parent_type (google.cloud.securitycenter_v1.types.CloudDlpDataProfile.ParentType): + The resource hierarchy level at which the + data profile was generated. + """ + class ParentType(proto.Enum): + r"""Parents for configurations that produce data profile + findings. + + Values: + PARENT_TYPE_UNSPECIFIED (0): + Unspecified parent type. + ORGANIZATION (1): + Organization-level configurations. + PROJECT (2): + Project-level configurations. + """ + PARENT_TYPE_UNSPECIFIED = 0 + ORGANIZATION = 1 + PROJECT = 2 + + data_profile: str = proto.Field( + proto.STRING, + number=1, + ) + parent_type: ParentType = proto.Field( + proto.ENUM, + number=2, + enum=ParentType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.py new file mode 100644 index 000000000000..46b9848965a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'CloudDlpInspection', + }, +) + + +class CloudDlpInspection(proto.Message): + r"""Details about the Cloud Data Loss Prevention (Cloud DLP) `inspection + job `__ + that produced the finding. + + Attributes: + inspect_job (str): + Name of the inspection job, for example, + ``projects/123/locations/europe/dlpJobs/i-8383929``. + info_type (str): + The type of information (or + `infoType `__) + found, for example, ``EMAIL_ADDRESS`` or ``STREET_ADDRESS``. + info_type_count (int): + The number of times Cloud DLP found this + infoType within this job and resource. + full_scan (bool): + Whether Cloud DLP scanned the complete + resource or a sampled subset. + """ + + inspect_job: str = proto.Field( + proto.STRING, + number=1, + ) + info_type: str = proto.Field( + proto.STRING, + number=2, + ) + info_type_count: int = proto.Field( + proto.INT64, + number=3, + ) + full_scan: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.py new file mode 100644 index 000000000000..432ca7841d82 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Compliance', + }, +) + + +class Compliance(proto.Message): + r"""Contains compliance information about a security standard + indicating unmet recommendations. + + Attributes: + standard (str): + Industry-wide compliance standards or + benchmarks, such as CIS, PCI, and OWASP. + version (str): + Version of the standard or benchmark, for + example, 1.1 + ids (MutableSequence[str]): + Policies within the standard or benchmark, + for example, A.12.4.1 + """ + + standard: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.py new file mode 100644 index 000000000000..0f36fbdfd761 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.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.cloud.securitycenter.v1', + manifest={ + 'Connection', + }, +) + + +class Connection(proto.Message): + r"""Contains information about the IP connection associated with + the finding. + + Attributes: + destination_ip (str): + Destination IP address. Not present for + sockets that are listening and not connected. + destination_port (int): + Destination port. Not present for sockets + that are listening and not connected. + source_ip (str): + Source IP address. + source_port (int): + Source port. + protocol (google.cloud.securitycenter_v1.types.Connection.Protocol): + IANA Internet Protocol Number such as TCP(6) + and UDP(17). + """ + class Protocol(proto.Enum): + r"""IANA Internet Protocol Number such as TCP(6) and UDP(17). + + Values: + PROTOCOL_UNSPECIFIED (0): + Unspecified protocol (not HOPOPT). + ICMP (1): + Internet Control Message Protocol. + TCP (6): + Transmission Control Protocol. + UDP (17): + User Datagram Protocol. + GRE (47): + Generic Routing Encapsulation. + ESP (50): + Encap Security Payload. + """ + PROTOCOL_UNSPECIFIED = 0 + ICMP = 1 + TCP = 6 + UDP = 17 + GRE = 47 + ESP = 50 + + destination_ip: str = proto.Field( + proto.STRING, + number=1, + ) + destination_port: int = proto.Field( + proto.INT32, + number=2, + ) + source_ip: str = proto.Field( + proto.STRING, + number=3, + ) + source_port: int = proto.Field( + proto.INT32, + number=4, + ) + protocol: Protocol = proto.Field( + proto.ENUM, + number=5, + enum=Protocol, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.py new file mode 100644 index 000000000000..7fdd88c15c7e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'ContactDetails', + 'Contact', + }, +) + + +class ContactDetails(proto.Message): + r"""Details about specific contacts + + Attributes: + contacts (MutableSequence[google.cloud.securitycenter_v1.types.Contact]): + A list of contacts + """ + + contacts: MutableSequence['Contact'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Contact', + ) + + +class Contact(proto.Message): + r"""The email address of a contact. + + Attributes: + email (str): + An email address. For example, "``person123@company.com``". + """ + + email: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.py new file mode 100644 index 000000000000..d953244d3583 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v1.types import label +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Container', + }, +) + + +class Container(proto.Message): + r"""Container associated with the finding. + + Attributes: + name (str): + Name of the container. + uri (str): + Container image URI provided when configuring + a pod or container. This string can identify a + container image version using mutable tags. + image_id (str): + Optional container image ID, if provided by + the container runtime. Uniquely identifies the + container image launched using a container image + digest. + labels (MutableSequence[google.cloud.securitycenter_v1.types.Label]): + Container labels, as provided by the + container runtime. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time that the container was created. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + image_id: str = proto.Field( + proto.STRING, + number=3, + ) + labels: MutableSequence[label.Label] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=label.Label, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.py new file mode 100644 index 000000000000..3372ba324532 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Database', + }, +) + + +class Database(proto.Message): + r"""Represents database access information, such as queries. A database + may be a sub-resource of an instance (as in the case of Cloud SQL + instances or Cloud Spanner instances), or the database instance + itself. Some database resources might not have the `full resource + name `__ populated + because these resource types, such as Cloud SQL databases, are not + yet supported by Cloud Asset Inventory. In these cases only the + display name is provided. + + Attributes: + name (str): + Some database resources may not have the `full resource + name `__ + populated because these resource types are not yet supported + by Cloud Asset Inventory (e.g. Cloud SQL databases). In + these cases only the display name will be provided. The + `full resource + name `__ of + the database that the user connected to, if it is supported + by Cloud Asset Inventory. + display_name (str): + The human-readable name of the database that + the user connected to. + user_name (str): + The username used to connect to the database. + The username might not be an IAM principal and + does not have a set format. + query (str): + The SQL statement that is associated with the + database access. + grantees (MutableSequence[str]): + The target usernames, roles, or groups of an + SQL privilege grant, which is not an IAM policy + change. + version (str): + The version of the database, for example, POSTGRES_14. See + `the complete + list `__. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + user_name: str = proto.Field( + proto.STRING, + number=3, + ) + query: str = proto.Field( + proto.STRING, + number=4, + ) + grantees: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + version: str = proto.Field( + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.py new file mode 100644 index 000000000000..ba51ed0b1ec6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.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.cloud.securitycenter.v1', + manifest={ + 'EffectiveEventThreatDetectionCustomModule', + }, +) + + +class EffectiveEventThreatDetectionCustomModule(proto.Message): + r"""An EffectiveEventThreatDetectionCustomModule is the representation + of an Event Threat Detection custom module at a specified level of + the resource hierarchy: organization, folder, or project. If a + custom module is inherited from a parent organization or folder, the + value of the ``enablement_state`` property in + EffectiveEventThreatDetectionCustomModule is set to the value that + is effective in the parent, instead of ``INHERITED``. For example, + if the module is enabled in a parent organization or folder, the + effective ``enablement_state`` for the module in all child folders + or projects is also ``enabled``. + EffectiveEventThreatDetectionCustomModule is read-only. + + Attributes: + name (str): + Output only. The resource name of the effective ETD custom + module. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + config (google.protobuf.struct_pb2.Struct): + Output only. Config for the effective module. + enablement_state (google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule.EnablementState): + Output only. The effective state of + enablement for the module at the given level of + the hierarchy. + type_ (str): + Output only. Type for the module. e.g. CONFIGURABLE_BAD_IP. + display_name (str): + Output only. The human readable name to be + displayed for the module. + description (str): + Output only. The description for the module. + """ + class EnablementState(proto.Enum): + r"""The enablement state of the module. + + Values: + ENABLEMENT_STATE_UNSPECIFIED (0): + Unspecified enablement state. + ENABLED (1): + The module is enabled at the given level. + DISABLED (2): + The module is disabled at the given level. + """ + ENABLEMENT_STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + config: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + enablement_state: EnablementState = proto.Field( + proto.ENUM, + number=3, + enum=EnablementState, + ) + type_: str = proto.Field( + proto.STRING, + number=4, + ) + display_name: str = proto.Field( + proto.STRING, + number=5, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.py new file mode 100644 index 000000000000..2396c38d1aaf --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'EffectiveSecurityHealthAnalyticsCustomModule', + }, +) + + +class EffectiveSecurityHealthAnalyticsCustomModule(proto.Message): + r"""An EffectiveSecurityHealthAnalyticsCustomModule is the + representation of a Security Health Analytics custom module at a + specified level of the resource hierarchy: organization, folder, or + project. If a custom module is inherited from a parent organization + or folder, the value of the ``enablementState`` property in + EffectiveSecurityHealthAnalyticsCustomModule is set to the value + that is effective in the parent, instead of ``INHERITED``. For + example, if the module is enabled in a parent organization or + folder, the effective enablement_state for the module in all child + folders or projects is also ``enabled``. + EffectiveSecurityHealthAnalyticsCustomModule is read-only. + + Attributes: + name (str): + Output only. The resource name of the custom + module. Its format is + "organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}", + or + "folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}", + or + "projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}". + custom_config (google.cloud.securitycenter_v1.types.CustomConfig): + Output only. The user-specified configuration + for the module. + enablement_state (google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState): + Output only. The effective state of + enablement for the module at the given level of + the hierarchy. + display_name (str): + Output only. The display name for the custom + module. The name must be between 1 and 128 + characters, start with a lowercase letter, and + contain alphanumeric characters or underscores + only. + """ + class EnablementState(proto.Enum): + r"""The enablement state of the module. + + Values: + ENABLEMENT_STATE_UNSPECIFIED (0): + Unspecified enablement state. + ENABLED (1): + The module is enabled at the given level. + DISABLED (2): + The module is disabled at the given level. + """ + ENABLEMENT_STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + custom_config: security_health_analytics_custom_config.CustomConfig = proto.Field( + proto.MESSAGE, + number=2, + message=security_health_analytics_custom_config.CustomConfig, + ) + enablement_state: EnablementState = proto.Field( + proto.ENUM, + number=3, + enum=EnablementState, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.py new file mode 100644 index 000000000000..6b6e83626bb9 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'EventThreatDetectionCustomModule', + }, +) + + +class EventThreatDetectionCustomModule(proto.Message): + r"""Represents an instance of an Event Threat Detection custom + module, including its full module name, display name, enablement + state, and last updated time. You can create a custom module at + the organization, folder, or project level. Custom modules that + you create at the organization or folder level are inherited by + child folders and projects. + + Attributes: + name (str): + Immutable. The resource name of the Event Threat Detection + custom module. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. + config (google.protobuf.struct_pb2.Struct): + Config for the module. For the resident + module, its config value is defined at this + level. For the inherited module, its config + value is inherited from the ancestor module. + ancestor_module (str): + Output only. The closest ancestor module that + this module inherits the enablement state from. + The format is the same as the + EventThreatDetectionCustomModule resource name. + enablement_state (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule.EnablementState): + The state of enablement for the module at the + given level of the hierarchy. + type_ (str): + Type for the module. e.g. CONFIGURABLE_BAD_IP. + display_name (str): + The human readable name to be displayed for + the module. + description (str): + The description for the module. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the module was last + updated. + last_editor (str): + Output only. The editor the module was last + updated by. + """ + class EnablementState(proto.Enum): + r"""The enablement state of the module. + + Values: + ENABLEMENT_STATE_UNSPECIFIED (0): + Unspecified enablement state. + ENABLED (1): + The module is enabled at the given level. + DISABLED (2): + The module is disabled at the given level. + INHERITED (3): + When the enablement state is inherited. + """ + ENABLEMENT_STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + INHERITED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + config: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + ancestor_module: str = proto.Field( + proto.STRING, + number=3, + ) + enablement_state: EnablementState = proto.Field( + proto.ENUM, + number=4, + enum=EnablementState, + ) + type_: str = proto.Field( + proto.STRING, + number=5, + ) + display_name: str = proto.Field( + proto.STRING, + number=6, + ) + description: str = proto.Field( + proto.STRING, + number=7, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + last_editor: str = proto.Field( + proto.STRING, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.py new file mode 100644 index 000000000000..12b7e815de3f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'CustomModuleValidationErrors', + 'CustomModuleValidationError', + 'Position', + }, +) + + +class CustomModuleValidationErrors(proto.Message): + r"""A list of zero or more errors encountered while validating + the uploaded configuration of an Event Threat Detection Custom + Module. + + Attributes: + errors (MutableSequence[google.cloud.securitycenter_v1.types.CustomModuleValidationError]): + + """ + + errors: MutableSequence['CustomModuleValidationError'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CustomModuleValidationError', + ) + + +class CustomModuleValidationError(proto.Message): + r"""An error encountered while validating the uploaded + configuration of an Event Threat Detection Custom Module. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + description (str): + A description of the error, suitable for + human consumption. Required. + field_path (str): + The path, in RFC 8901 JSON Pointer format, to + the field that failed validation. This may be + left empty if no specific field is affected. + start (google.cloud.securitycenter_v1.types.Position): + The initial position of the error in the + uploaded text version of the module. This field + may be omitted if no specific position applies, + or if one could not be computed. + + This field is a member of `oneof`_ ``_start``. + end (google.cloud.securitycenter_v1.types.Position): + The end position of the error in the uploaded + text version of the module. This field may be + omitted if no specific position applies, or if + one could not be computed.. + + This field is a member of `oneof`_ ``_end``. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + field_path: str = proto.Field( + proto.STRING, + number=2, + ) + start: 'Position' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='Position', + ) + end: 'Position' = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message='Position', + ) + + +class Position(proto.Message): + r"""A position in the uploaded text version of a module. + + Attributes: + line_number (int): + + column_number (int): + + """ + + line_number: int = proto.Field( + proto.INT32, + number=1, + ) + column_number: int = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.py new file mode 100644 index 000000000000..68a2b9fd7d98 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Exfiltration', + 'ExfilResource', + }, +) + + +class Exfiltration(proto.Message): + r"""Exfiltration represents a data exfiltration attempt from one or more + sources to one or more targets. The ``sources`` attribute lists the + sources of the exfiltrated data. The ``targets`` attribute lists the + destinations the data was copied to. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v1.types.ExfilResource]): + If there are multiple sources, then the data + is considered "joined" between them. For + instance, BigQuery can join multiple tables, and + each table would be considered a source. + targets (MutableSequence[google.cloud.securitycenter_v1.types.ExfilResource]): + If there are multiple targets, each target + would get a complete copy of the "joined" source + data. + total_exfiltrated_bytes (int): + Total exfiltrated bytes processed for the + entire job. + """ + + sources: MutableSequence['ExfilResource'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ExfilResource', + ) + targets: MutableSequence['ExfilResource'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ExfilResource', + ) + total_exfiltrated_bytes: int = proto.Field( + proto.INT64, + number=3, + ) + + +class ExfilResource(proto.Message): + r"""Resource where data was exfiltrated from or exfiltrated to. + + Attributes: + name (str): + The resource's `full resource + name `__. + components (MutableSequence[str]): + Subcomponents of the asset that was + exfiltrated, like URIs used during exfiltration, + table names, databases, and filenames. For + example, multiple tables might have been + exfiltrated from the same Cloud SQL instance, or + multiple files might have been exfiltrated from + the same Cloud Storage bucket. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + components: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py new file mode 100644 index 000000000000..50a7a7e921f6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v1', + manifest={ + 'ExternalSystem', + }, +) + + +class ExternalSystem(proto.Message): + r"""Representation of third party SIEM/SOAR fields within SCC. + + Attributes: + name (str): + Full resource name of the external system, + for example: + "organizations/1234/sources/5678/findings/123456/externalSystems/jira", + "folders/1234/sources/5678/findings/123456/externalSystems/jira", + "projects/1234/sources/5678/findings/123456/externalSystems/jira". + assignees (MutableSequence[str]): + References primary/secondary etc assignees in + the external system. + external_uid (str): + The identifier that's used to track the + finding's corresponding case in the external + system. + status (str): + The most recent status of the finding's + corresponding case, as reported by the external + system. + external_system_update_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was last updated, as + reported by the external system. + case_uri (str): + The link to the finding's corresponding case + in the external system. + case_priority (str): + The priority of the finding's corresponding + case in the external system. + case_sla (google.protobuf.timestamp_pb2.Timestamp): + The SLA of the finding's corresponding case + in the external system. + case_create_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was created, as + reported by the external system. + case_close_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was closed, as + reported by the external system. + ticket_info (google.cloud.securitycenter_v1.types.ExternalSystem.TicketInfo): + Information about the ticket, if any, that is + being used to track the resolution of the issue + that is identified by this finding. + """ + + class TicketInfo(proto.Message): + r"""Information about the ticket, if any, that is being used to + track the resolution of the issue that is identified by this + finding. + + Attributes: + id (str): + The identifier of the ticket in the ticket + system. + assignee (str): + The assignee of the ticket in the ticket + system. + description (str): + The description of the ticket in the ticket + system. + uri (str): + The link to the ticket in the ticket system. + status (str): + The latest status of the ticket, as reported + by the ticket system. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the ticket was last updated, as + reported by the ticket system. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + assignee: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + uri: str = proto.Field( + proto.STRING, + number=4, + ) + status: str = proto.Field( + proto.STRING, + number=5, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + assignees: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + external_uid: str = proto.Field( + proto.STRING, + number=3, + ) + status: str = proto.Field( + proto.STRING, + number=4, + ) + external_system_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + case_uri: str = proto.Field( + proto.STRING, + number=6, + ) + case_priority: str = proto.Field( + proto.STRING, + number=7, + ) + case_sla: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + case_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + case_close_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + ticket_info: TicketInfo = proto.Field( + proto.MESSAGE, + number=8, + message=TicketInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.py new file mode 100644 index 000000000000..017abee53151 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'File', + }, +) + + +class File(proto.Message): + r"""File information about the related binary/library used by an + executable, or the script used by a script interpreter + + Attributes: + path (str): + Absolute path of the file as a JSON encoded + string. + size (int): + Size of the file in bytes. + sha256 (str): + SHA256 hash of the first hashed_size bytes of the file + encoded as a hex string. If hashed_size == size, sha256 + represents the SHA256 hash of the entire file. + hashed_size (int): + The length in bytes of the file prefix that was hashed. If + hashed_size == size, any hashes reported represent the + entire file. + partially_hashed (bool): + True when the hash covers only a prefix of + the file. + contents (str): + Prefix of the file contents as a JSON-encoded + string. + disk_path (google.cloud.securitycenter_v1.types.File.DiskPath): + Path of the file in terms of underlying + disk/partition identifiers. + """ + + class DiskPath(proto.Message): + r"""Path of the file in terms of underlying disk/partition + identifiers. + + Attributes: + partition_uuid (str): + UUID of the partition (format + https://wiki.archlinux.org/title/persistent_block_device_naming#by-uuid) + relative_path (str): + Relative path of the file in the partition as a JSON encoded + string. Example: /home/user1/executable_file.sh + """ + + partition_uuid: str = proto.Field( + proto.STRING, + number=1, + ) + relative_path: str = proto.Field( + proto.STRING, + number=2, + ) + + path: str = proto.Field( + proto.STRING, + number=1, + ) + size: int = proto.Field( + proto.INT64, + number=2, + ) + sha256: str = proto.Field( + proto.STRING, + number=3, + ) + hashed_size: int = proto.Field( + proto.INT64, + number=4, + ) + partially_hashed: bool = proto.Field( + proto.BOOL, + number=5, + ) + contents: str = proto.Field( + proto.STRING, + number=6, + ) + disk_path: DiskPath = proto.Field( + proto.MESSAGE, + number=7, + message=DiskPath, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py new file mode 100644 index 000000000000..cc8deabeef4b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py @@ -0,0 +1,774 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1.types import access as gcs_access +from google.cloud.securitycenter_v1.types import application as gcs_application +from google.cloud.securitycenter_v1.types import attack_exposure as gcs_attack_exposure +from google.cloud.securitycenter_v1.types import backup_disaster_recovery as gcs_backup_disaster_recovery +from google.cloud.securitycenter_v1.types import cloud_armor as gcs_cloud_armor +from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile as gcs_cloud_dlp_data_profile +from google.cloud.securitycenter_v1.types import cloud_dlp_inspection as gcs_cloud_dlp_inspection +from google.cloud.securitycenter_v1.types import compliance +from google.cloud.securitycenter_v1.types import connection +from google.cloud.securitycenter_v1.types import contact_details +from google.cloud.securitycenter_v1.types import container +from google.cloud.securitycenter_v1.types import database as gcs_database +from google.cloud.securitycenter_v1.types import exfiltration as gcs_exfiltration +from google.cloud.securitycenter_v1.types import external_system +from google.cloud.securitycenter_v1.types import file +from google.cloud.securitycenter_v1.types import group_membership +from google.cloud.securitycenter_v1.types import iam_binding +from google.cloud.securitycenter_v1.types import indicator as gcs_indicator +from google.cloud.securitycenter_v1.types import kernel_rootkit as gcs_kernel_rootkit +from google.cloud.securitycenter_v1.types import kubernetes as gcs_kubernetes +from google.cloud.securitycenter_v1.types import load_balancer +from google.cloud.securitycenter_v1.types import log_entry +from google.cloud.securitycenter_v1.types import mitre_attack as gcs_mitre_attack +from google.cloud.securitycenter_v1.types import notebook as gcs_notebook +from google.cloud.securitycenter_v1.types import org_policy +from google.cloud.securitycenter_v1.types import process +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import security_posture as gcs_security_posture +from google.cloud.securitycenter_v1.types import toxic_combination as gcs_toxic_combination +from google.cloud.securitycenter_v1.types import vulnerability as gcs_vulnerability +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + + A finding is a record of assessment data like security, risk, + health, or privacy, that is ingested into Security Command + Center for presentation, notification, analysis, policy testing, + and enforcement. For example, a cross-site scripting (XSS) + vulnerability in an App Engine application is a finding. + + Attributes: + name (str): + The `relative resource + name `__ + of the finding. Example: + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}", + "projects/{project_id}/sources/{source_id}/findings/{finding_id}". + parent (str): + The relative resource name of the source the finding belongs + to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. For example: + "organizations/{organization_id}/sources/{source_id}". + resource_name (str): + For findings on Google Cloud resources, the full resource + name of the Google Cloud resource this finding is for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + This field is immutable after creation time. + state (google.cloud.securitycenter_v1.types.Finding.State): + The state of the finding. + category (str): + The additional taxonomy group within findings from a given + source. This field is immutable after creation time. + Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (google.protobuf.timestamp_pb2.Timestamp): + The time the finding was first detected. If + an existing finding is updated, then this is the + time the update occurred. For example, if the + finding represents an open firewall, this + property captures the time the detector believes + the firewall became open. The accuracy is + determined by the detector. If the finding is + later resolved, then this time reflects when the + finding was resolved. This must not be set to a + value greater than the current timestamp. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the finding was created in + Security Command Center. + severity (google.cloud.securitycenter_v1.types.Finding.Severity): + The severity of the finding. This field is + managed by the source that writes the finding. + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" + or + "projects/{project_number}/sources/{source_id}/findings/{finding_id}", + depending on the closest CRM ancestor of the resource + associated with the finding. + mute (google.cloud.securitycenter_v1.types.Finding.Mute): + Indicates the mute state of a finding (either + muted, unmuted or undefined). Unlike other + attributes of a finding, a finding provider + shouldn't set the value of mute. + finding_class (google.cloud.securitycenter_v1.types.Finding.FindingClass): + The class of the finding. + indicator (google.cloud.securitycenter_v1.types.Indicator): + Represents what's commonly known as an *indicator of + compromise* (IoC) in computer forensics. This is an artifact + observed on a network or in an operating system that, with + high confidence, indicates a computer intrusion. For more + information, see `Indicator of + compromise `__. + vulnerability (google.cloud.securitycenter_v1.types.Vulnerability): + Represents vulnerability-specific fields like + CVE and CVSS scores. CVE stands for Common + Vulnerabilities and Exposures + (https://cve.mitre.org/about/) + mute_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time this + finding was muted or unmuted. + external_systems (MutableMapping[str, google.cloud.securitycenter_v1.types.ExternalSystem]): + Output only. Third party SIEM/SOAR fields + within SCC, contains external system information + and external system finding fields. + mitre_attack (google.cloud.securitycenter_v1.types.MitreAttack): + MITRE ATT&CK tactics and techniques related + to this finding. See: https://attack.mitre.org + access (google.cloud.securitycenter_v1.types.Access): + Access details associated with the finding, + such as more information on the caller, which + method was accessed, and from where. + connections (MutableSequence[google.cloud.securitycenter_v1.types.Connection]): + Contains information about the IP connection + associated with the finding. + mute_initiator (str): + Records additional information about the mute operation, for + example, the `mute + configuration `__ + that muted the finding and the user who muted the finding. + mute_info (google.cloud.securitycenter_v1.types.Finding.MuteInfo): + Output only. The mute information regarding + this finding. + processes (MutableSequence[google.cloud.securitycenter_v1.types.Process]): + Represents operating system processes + associated with the Finding. + contacts (MutableMapping[str, google.cloud.securitycenter_v1.types.ContactDetails]): + Output only. Map containing the points of contact for the + given finding. The key represents the type of contact, while + the value contains a list of all the contacts that pertain. + Please refer to: + https://cloud.google.com/resource-manager/docs/managing-notification-contacts#notification-categories + + :: + + { + "security": { + "contacts": [ + { + "email": "person1@company.com" + }, + { + "email": "person2@company.com" + } + ] + } + } + compliances (MutableSequence[google.cloud.securitycenter_v1.types.Compliance]): + Contains compliance information for security + standards associated to the finding. + parent_display_name (str): + Output only. The human readable display name + of the finding source such as "Event Threat + Detection" or "Security Health Analytics". + description (str): + Contains more details about the finding. + exfiltration (google.cloud.securitycenter_v1.types.Exfiltration): + Represents exfiltrations associated with the + finding. + iam_bindings (MutableSequence[google.cloud.securitycenter_v1.types.IamBinding]): + Represents IAM bindings associated with the + finding. + next_steps (str): + Steps to address the finding. + module_name (str): + Unique identifier of the module which + generated the finding. Example: + + folders/598186756061/securityHealthAnalyticsSettings/customModules/56799441161885 + containers (MutableSequence[google.cloud.securitycenter_v1.types.Container]): + Containers associated with the finding. This + field provides information for both Kubernetes + and non-Kubernetes containers. + kubernetes (google.cloud.securitycenter_v1.types.Kubernetes): + Kubernetes resources associated with the + finding. + database (google.cloud.securitycenter_v1.types.Database): + Database associated with the finding. + attack_exposure (google.cloud.securitycenter_v1.types.AttackExposure): + The results of an attack path simulation + relevant to this finding. + files (MutableSequence[google.cloud.securitycenter_v1.types.File]): + File associated with the finding. + cloud_dlp_inspection (google.cloud.securitycenter_v1.types.CloudDlpInspection): + Cloud Data Loss Prevention (Cloud DLP) + inspection results that are associated with the + finding. + cloud_dlp_data_profile (google.cloud.securitycenter_v1.types.CloudDlpDataProfile): + Cloud DLP data profile that is associated + with the finding. + kernel_rootkit (google.cloud.securitycenter_v1.types.KernelRootkit): + Signature of the kernel rootkit. + org_policies (MutableSequence[google.cloud.securitycenter_v1.types.OrgPolicy]): + Contains information about the org policies + associated with the finding. + application (google.cloud.securitycenter_v1.types.Application): + Represents an application associated with the + finding. + backup_disaster_recovery (google.cloud.securitycenter_v1.types.BackupDisasterRecovery): + Fields related to Backup and DR findings. + security_posture (google.cloud.securitycenter_v1.types.SecurityPosture): + The security posture associated with the + finding. + log_entries (MutableSequence[google.cloud.securitycenter_v1.types.LogEntry]): + Log entries that are relevant to the finding. + load_balancers (MutableSequence[google.cloud.securitycenter_v1.types.LoadBalancer]): + The load balancers associated with the + finding. + cloud_armor (google.cloud.securitycenter_v1.types.CloudArmor): + Fields related to Cloud Armor findings. + notebook (google.cloud.securitycenter_v1.types.Notebook): + Notebook associated with the finding. + toxic_combination (google.cloud.securitycenter_v1.types.ToxicCombination): + Contains details about a group of security + issues that, when the issues occur together, + represent a greater risk than when the issues + occur independently. A group of such issues is + referred to as a toxic combination. + This field cannot be updated. Its value is + ignored in all update requests. + group_memberships (MutableSequence[google.cloud.securitycenter_v1.types.GroupMembership]): + Contains details about groups of which this + finding is a member. A group is a collection of + findings that are related in some way. This + field cannot be updated. Its value is ignored in + all update requests. + """ + class State(proto.Enum): + r"""The state of the finding. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + ACTIVE (1): + The finding requires attention and has not + been addressed yet. + INACTIVE (2): + The finding has been fixed, triaged as a + non-issue or otherwise addressed and is no + longer active. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + class Severity(proto.Enum): + r"""The severity of the finding. + + Values: + SEVERITY_UNSPECIFIED (0): + This value is used for findings when a source + doesn't write a severity value. + CRITICAL (1): + Vulnerability: + + A critical vulnerability is easily discoverable + by an external actor, exploitable, and results + in the direct ability to execute arbitrary code, + exfiltrate data, and otherwise gain additional + access and privileges to cloud resources and + workloads. Examples include publicly accessible + unprotected user data and public SSH access with + weak or no passwords. + + Threat: + + Indicates a threat that is able to access, + modify, or delete data or execute unauthorized + code within existing resources. + HIGH (2): + Vulnerability: + + A high risk vulnerability can be easily + discovered and exploited in combination with + other vulnerabilities in order to gain direct + access and the ability to execute arbitrary + code, exfiltrate data, and otherwise gain + additional access and privileges to cloud + resources and workloads. An example is a + database with weak or no passwords that is only + accessible internally. This database could + easily be compromised by an actor that had + access to the internal network. + + Threat: + + Indicates a threat that is able to create new + computational resources in an environment but + not able to access data or execute code in + existing resources. + MEDIUM (3): + Vulnerability: + + A medium risk vulnerability could be used by an + actor to gain access to resources or privileges + that enable them to eventually (through multiple + steps or a complex exploit) gain access and the + ability to execute arbitrary code or exfiltrate + data. An example is a service account with + access to more projects than it should have. If + an actor gains access to the service account, + they could potentially use that access to + manipulate a project the service account was not + intended to. + + Threat: + + Indicates a threat that is able to cause + operational impact but may not access data or + execute unauthorized code. + LOW (4): + Vulnerability: + + A low risk vulnerability hampers a security + organization's ability to detect vulnerabilities + or active threats in their deployment, or + prevents the root cause investigation of + security issues. An example is monitoring and + logs being disabled for resource configurations + and access. + + Threat: + + Indicates a threat that has obtained minimal + access to an environment but is not able to + access data, execute code, or create resources. + """ + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + HIGH = 2 + MEDIUM = 3 + LOW = 4 + + class Mute(proto.Enum): + r"""Mute state a finding can be in. + + Values: + MUTE_UNSPECIFIED (0): + Unspecified. + MUTED (1): + Finding has been muted. + UNMUTED (2): + Finding has been unmuted. + UNDEFINED (4): + Finding has never been muted/unmuted. + """ + MUTE_UNSPECIFIED = 0 + MUTED = 1 + UNMUTED = 2 + UNDEFINED = 4 + + class FindingClass(proto.Enum): + r"""Represents what kind of Finding it is. + + Values: + FINDING_CLASS_UNSPECIFIED (0): + Unspecified finding class. + THREAT (1): + Describes unwanted or malicious activity. + VULNERABILITY (2): + Describes a potential weakness in software + that increases risk to Confidentiality & + Integrity & Availability. + MISCONFIGURATION (3): + Describes a potential weakness in cloud + resource/asset configuration that increases + risk. + OBSERVATION (4): + Describes a security observation that is for + informational purposes. + SCC_ERROR (5): + Describes an error that prevents some SCC + functionality. + POSTURE_VIOLATION (6): + Describes a potential security risk due to a + change in the security posture. + TOXIC_COMBINATION (7): + Describes a group of security issues that, + when the issues occur together, represent a + greater risk than when the issues occur + independently. A group of such issues is + referred to as a toxic combination. + """ + FINDING_CLASS_UNSPECIFIED = 0 + THREAT = 1 + VULNERABILITY = 2 + MISCONFIGURATION = 3 + OBSERVATION = 4 + SCC_ERROR = 5 + POSTURE_VIOLATION = 6 + TOXIC_COMBINATION = 7 + + class MuteInfo(proto.Message): + r"""Mute information about the finding, including whether the + finding has a static mute or any matching dynamic mute rules. + + Attributes: + static_mute (google.cloud.securitycenter_v1.types.Finding.MuteInfo.StaticMute): + If set, the static mute applied to this + finding. Static mutes override dynamic mutes. If + unset, there is no static mute. + dynamic_mute_records (MutableSequence[google.cloud.securitycenter_v1.types.Finding.MuteInfo.DynamicMuteRecord]): + The list of dynamic mute rules that currently + match the finding. + """ + + class StaticMute(proto.Message): + r"""Information about the static mute state. A static mute state + overrides any dynamic mute rules that apply to this finding. The + static mute state can be set by a static mute rule or by muting + the finding directly. + + Attributes: + state (google.cloud.securitycenter_v1.types.Finding.Mute): + The static mute state. If the value is ``MUTED`` or + ``UNMUTED``, then the finding's overall mute state will have + the same value. + apply_time (google.protobuf.timestamp_pb2.Timestamp): + When the static mute was applied. + """ + + state: 'Finding.Mute' = proto.Field( + proto.ENUM, + number=1, + enum='Finding.Mute', + ) + apply_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + class DynamicMuteRecord(proto.Message): + r"""The record of a dynamic mute rule that matches the finding. + + Attributes: + mute_config (str): + The relative resource name of the mute rule, represented by + a mute config, that created this record, for example + ``organizations/123/muteConfigs/mymuteconfig`` or + ``organizations/123/locations/global/muteConfigs/mymuteconfig``. + match_time (google.protobuf.timestamp_pb2.Timestamp): + When the dynamic mute rule first matched the + finding. + """ + + mute_config: str = proto.Field( + proto.STRING, + number=1, + ) + match_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + static_mute: 'Finding.MuteInfo.StaticMute' = proto.Field( + proto.MESSAGE, + number=1, + message='Finding.MuteInfo.StaticMute', + ) + dynamic_mute_records: MutableSequence['Finding.MuteInfo.DynamicMuteRecord'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Finding.MuteInfo.DynamicMuteRecord', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + resource_name: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + category: str = proto.Field( + proto.STRING, + number=5, + ) + external_uri: str = proto.Field( + proto.STRING, + number=6, + ) + source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=12, + enum=Severity, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=14, + ) + mute: Mute = proto.Field( + proto.ENUM, + number=15, + enum=Mute, + ) + finding_class: FindingClass = proto.Field( + proto.ENUM, + number=17, + enum=FindingClass, + ) + indicator: gcs_indicator.Indicator = proto.Field( + proto.MESSAGE, + number=18, + message=gcs_indicator.Indicator, + ) + vulnerability: gcs_vulnerability.Vulnerability = proto.Field( + proto.MESSAGE, + number=20, + message=gcs_vulnerability.Vulnerability, + ) + mute_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=21, + message=timestamp_pb2.Timestamp, + ) + external_systems: MutableMapping[str, external_system.ExternalSystem] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=22, + message=external_system.ExternalSystem, + ) + mitre_attack: gcs_mitre_attack.MitreAttack = proto.Field( + proto.MESSAGE, + number=25, + message=gcs_mitre_attack.MitreAttack, + ) + access: gcs_access.Access = proto.Field( + proto.MESSAGE, + number=26, + message=gcs_access.Access, + ) + connections: MutableSequence[connection.Connection] = proto.RepeatedField( + proto.MESSAGE, + number=31, + message=connection.Connection, + ) + mute_initiator: str = proto.Field( + proto.STRING, + number=28, + ) + mute_info: MuteInfo = proto.Field( + proto.MESSAGE, + number=61, + message=MuteInfo, + ) + processes: MutableSequence[process.Process] = proto.RepeatedField( + proto.MESSAGE, + number=30, + message=process.Process, + ) + contacts: MutableMapping[str, contact_details.ContactDetails] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=33, + message=contact_details.ContactDetails, + ) + compliances: MutableSequence[compliance.Compliance] = proto.RepeatedField( + proto.MESSAGE, + number=34, + message=compliance.Compliance, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=36, + ) + description: str = proto.Field( + proto.STRING, + number=37, + ) + exfiltration: gcs_exfiltration.Exfiltration = proto.Field( + proto.MESSAGE, + number=38, + message=gcs_exfiltration.Exfiltration, + ) + iam_bindings: MutableSequence[iam_binding.IamBinding] = proto.RepeatedField( + proto.MESSAGE, + number=39, + message=iam_binding.IamBinding, + ) + next_steps: str = proto.Field( + proto.STRING, + number=40, + ) + module_name: str = proto.Field( + proto.STRING, + number=41, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=42, + message=container.Container, + ) + kubernetes: gcs_kubernetes.Kubernetes = proto.Field( + proto.MESSAGE, + number=43, + message=gcs_kubernetes.Kubernetes, + ) + database: gcs_database.Database = proto.Field( + proto.MESSAGE, + number=44, + message=gcs_database.Database, + ) + attack_exposure: gcs_attack_exposure.AttackExposure = proto.Field( + proto.MESSAGE, + number=45, + message=gcs_attack_exposure.AttackExposure, + ) + files: MutableSequence[file.File] = proto.RepeatedField( + proto.MESSAGE, + number=46, + message=file.File, + ) + cloud_dlp_inspection: gcs_cloud_dlp_inspection.CloudDlpInspection = proto.Field( + proto.MESSAGE, + number=48, + message=gcs_cloud_dlp_inspection.CloudDlpInspection, + ) + cloud_dlp_data_profile: gcs_cloud_dlp_data_profile.CloudDlpDataProfile = proto.Field( + proto.MESSAGE, + number=49, + message=gcs_cloud_dlp_data_profile.CloudDlpDataProfile, + ) + kernel_rootkit: gcs_kernel_rootkit.KernelRootkit = proto.Field( + proto.MESSAGE, + number=50, + message=gcs_kernel_rootkit.KernelRootkit, + ) + org_policies: MutableSequence[org_policy.OrgPolicy] = proto.RepeatedField( + proto.MESSAGE, + number=51, + message=org_policy.OrgPolicy, + ) + application: gcs_application.Application = proto.Field( + proto.MESSAGE, + number=53, + message=gcs_application.Application, + ) + backup_disaster_recovery: gcs_backup_disaster_recovery.BackupDisasterRecovery = proto.Field( + proto.MESSAGE, + number=55, + message=gcs_backup_disaster_recovery.BackupDisasterRecovery, + ) + security_posture: gcs_security_posture.SecurityPosture = proto.Field( + proto.MESSAGE, + number=56, + message=gcs_security_posture.SecurityPosture, + ) + log_entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( + proto.MESSAGE, + number=57, + message=log_entry.LogEntry, + ) + load_balancers: MutableSequence[load_balancer.LoadBalancer] = proto.RepeatedField( + proto.MESSAGE, + number=58, + message=load_balancer.LoadBalancer, + ) + cloud_armor: gcs_cloud_armor.CloudArmor = proto.Field( + proto.MESSAGE, + number=59, + message=gcs_cloud_armor.CloudArmor, + ) + notebook: gcs_notebook.Notebook = proto.Field( + proto.MESSAGE, + number=63, + message=gcs_notebook.Notebook, + ) + toxic_combination: gcs_toxic_combination.ToxicCombination = proto.Field( + proto.MESSAGE, + number=64, + message=gcs_toxic_combination.ToxicCombination, + ) + group_memberships: MutableSequence[group_membership.GroupMembership] = proto.RepeatedField( + proto.MESSAGE, + number=65, + message=group_membership.GroupMembership, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.py new file mode 100644 index 000000000000..577452411641 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.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.securitycenter.v1', + manifest={ + 'Folder', + }, +) + + +class Folder(proto.Message): + r"""Message that contains the resource name and display name of a + folder resource. + + Attributes: + resource_folder (str): + Full resource name of this folder. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_folder_display_name (str): + The user defined display name for this + folder. + """ + + resource_folder: str = proto.Field( + proto.STRING, + number=1, + ) + resource_folder_display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.py new file mode 100644 index 000000000000..d95cb97ea0a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.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.cloud.securitycenter.v1', + manifest={ + 'GroupMembership', + }, +) + + +class GroupMembership(proto.Message): + r"""Contains details about groups of which this finding is a + member. A group is a collection of findings that are related in + some way. + + Attributes: + group_type (google.cloud.securitycenter_v1.types.GroupMembership.GroupType): + Type of group. + group_id (str): + ID of the group. + """ + class GroupType(proto.Enum): + r"""Possible types of groups. + + Values: + GROUP_TYPE_UNSPECIFIED (0): + Default value. + GROUP_TYPE_TOXIC_COMBINATION (1): + Group represents a toxic combination. + """ + GROUP_TYPE_UNSPECIFIED = 0 + GROUP_TYPE_TOXIC_COMBINATION = 1 + + group_type: GroupType = proto.Field( + proto.ENUM, + number=1, + enum=GroupType, + ) + group_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py new file mode 100644 index 000000000000..cab59d31ec7c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v1', + manifest={ + 'IamBinding', + }, +) + + +class IamBinding(proto.Message): + r"""Represents a particular IAM binding, which captures a + member's role addition, removal, or state. + + Attributes: + action (google.cloud.securitycenter_v1.types.IamBinding.Action): + The action that was performed on a Binding. + role (str): + Role that is assigned to "members". + For example, "roles/viewer", "roles/editor", or + "roles/owner". + member (str): + A single identity requesting access for a + Cloud Platform resource, for example, + "foo@google.com". + """ + class Action(proto.Enum): + r"""The type of action performed on a Binding in a policy. + + Values: + ACTION_UNSPECIFIED (0): + Unspecified. + ADD (1): + Addition of a Binding. + REMOVE (2): + Removal of a Binding. + """ + ACTION_UNSPECIFIED = 0 + ADD = 1 + REMOVE = 2 + + action: Action = proto.Field( + proto.ENUM, + number=1, + enum=Action, + ) + role: str = proto.Field( + proto.STRING, + number=2, + ) + member: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py new file mode 100644 index 000000000000..f75bd00701dd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v1', + manifest={ + 'Indicator', + }, +) + + +class Indicator(proto.Message): + r"""Represents what's commonly known as an *indicator of compromise* + (IoC) in computer forensics. This is an artifact observed on a + network or in an operating system that, with high confidence, + indicates a computer intrusion. For more information, see `Indicator + of + compromise `__. + + Attributes: + ip_addresses (MutableSequence[str]): + The list of IP addresses that are associated + with the finding. + domains (MutableSequence[str]): + List of domains associated to the Finding. + signatures (MutableSequence[google.cloud.securitycenter_v1.types.Indicator.ProcessSignature]): + The list of matched signatures indicating + that the given process is present in the + environment. + uris (MutableSequence[str]): + The list of URIs associated to the Findings. + """ + + class ProcessSignature(proto.Message): + r"""Indicates what signature matched this process. + + 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: + memory_hash_signature (google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.MemoryHashSignature): + Signature indicating that a binary family was + matched. + + This field is a member of `oneof`_ ``signature``. + yara_rule_signature (google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.YaraRuleSignature): + Signature indicating that a YARA rule was + matched. + + This field is a member of `oneof`_ ``signature``. + signature_type (google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.SignatureType): + Describes the type of resource associated + with the signature. + """ + class SignatureType(proto.Enum): + r"""Possible resource types to be associated with a signature. + + Values: + SIGNATURE_TYPE_UNSPECIFIED (0): + The default signature type. + SIGNATURE_TYPE_PROCESS (1): + Used for signatures concerning processes. + SIGNATURE_TYPE_FILE (2): + Used for signatures concerning disks. + """ + SIGNATURE_TYPE_UNSPECIFIED = 0 + SIGNATURE_TYPE_PROCESS = 1 + SIGNATURE_TYPE_FILE = 2 + + class MemoryHashSignature(proto.Message): + r"""A signature corresponding to memory page hashes. + + Attributes: + binary_family (str): + The binary family. + detections (MutableSequence[google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.MemoryHashSignature.Detection]): + The list of memory hash detections + contributing to the binary family match. + """ + + class Detection(proto.Message): + r"""Memory hash detection contributing to the binary family + match. + + Attributes: + binary (str): + The name of the binary associated with the + memory hash signature detection. + percent_pages_matched (float): + The percentage of memory page hashes in the + signature that were matched. + """ + + binary: str = proto.Field( + proto.STRING, + number=2, + ) + percent_pages_matched: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + binary_family: str = proto.Field( + proto.STRING, + number=1, + ) + detections: MutableSequence['Indicator.ProcessSignature.MemoryHashSignature.Detection'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Indicator.ProcessSignature.MemoryHashSignature.Detection', + ) + + class YaraRuleSignature(proto.Message): + r"""A signature corresponding to a YARA rule. + + Attributes: + yara_rule (str): + The name of the YARA rule. + """ + + yara_rule: str = proto.Field( + proto.STRING, + number=5, + ) + + memory_hash_signature: 'Indicator.ProcessSignature.MemoryHashSignature' = proto.Field( + proto.MESSAGE, + number=6, + oneof='signature', + message='Indicator.ProcessSignature.MemoryHashSignature', + ) + yara_rule_signature: 'Indicator.ProcessSignature.YaraRuleSignature' = proto.Field( + proto.MESSAGE, + number=7, + oneof='signature', + message='Indicator.ProcessSignature.YaraRuleSignature', + ) + signature_type: 'Indicator.ProcessSignature.SignatureType' = proto.Field( + proto.ENUM, + number=8, + enum='Indicator.ProcessSignature.SignatureType', + ) + + ip_addresses: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + domains: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + signatures: MutableSequence[ProcessSignature] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=ProcessSignature, + ) + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.py new file mode 100644 index 000000000000..d9c18edeec46 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'KernelRootkit', + }, +) + + +class KernelRootkit(proto.Message): + r"""Kernel mode rootkit signatures. + + Attributes: + name (str): + Rootkit name, when available. + unexpected_code_modification (bool): + True if unexpected modifications of kernel + code memory are present. + unexpected_read_only_data_modification (bool): + True if unexpected modifications of kernel + read-only data memory are present. + unexpected_ftrace_handler (bool): + True if ``ftrace`` points are present with callbacks + pointing to regions that are not in the expected kernel or + module code range. + unexpected_kprobe_handler (bool): + True if ``kprobe`` points are present with callbacks + pointing to regions that are not in the expected kernel or + module code range. + unexpected_kernel_code_pages (bool): + True if kernel code pages that are not in the + expected kernel or module code regions are + present. + unexpected_system_call_handler (bool): + True if system call handlers that are are not + in the expected kernel or module code regions + are present. + unexpected_interrupt_handler (bool): + True if interrupt handlers that are are not + in the expected kernel or module code regions + are present. + unexpected_processes_in_runqueue (bool): + True if unexpected processes in the scheduler + run queue are present. Such processes are in the + run queue, but not in the process task list. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + unexpected_code_modification: bool = proto.Field( + proto.BOOL, + number=2, + ) + unexpected_read_only_data_modification: bool = proto.Field( + proto.BOOL, + number=3, + ) + unexpected_ftrace_handler: bool = proto.Field( + proto.BOOL, + number=4, + ) + unexpected_kprobe_handler: bool = proto.Field( + proto.BOOL, + number=5, + ) + unexpected_kernel_code_pages: bool = proto.Field( + proto.BOOL, + number=6, + ) + unexpected_system_call_handler: bool = proto.Field( + proto.BOOL, + number=7, + ) + unexpected_interrupt_handler: bool = proto.Field( + proto.BOOL, + number=8, + ) + unexpected_processes_in_runqueue: bool = proto.Field( + proto.BOOL, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.py new file mode 100644 index 000000000000..b91973ac449b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v1.types import container +from google.cloud.securitycenter_v1.types import label + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Kubernetes', + }, +) + + +class Kubernetes(proto.Message): + r"""Kubernetes-related attributes. + + Attributes: + pods (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Pod]): + Kubernetes + `Pods `__ + associated with the finding. This field contains Pod records + for each container that is owned by a Pod. + nodes (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Node]): + Provides Kubernetes + `node `__ + information. + node_pools (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.NodePool]): + GKE `node + pools `__ + associated with the finding. This field contains node pool + information for each node, when it is available. + roles (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Role]): + Provides Kubernetes role information for findings that + involve `Roles or + ClusterRoles `__. + bindings (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Binding]): + Provides Kubernetes role binding information for findings + that involve `RoleBindings or + ClusterRoleBindings `__. + access_reviews (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.AccessReview]): + Provides information on any Kubernetes access + reviews (privilege checks) relevant to the + finding. + objects (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Object]): + Kubernetes objects related to the finding. + """ + + class Pod(proto.Message): + r"""A Kubernetes Pod. + + Attributes: + ns (str): + Kubernetes Pod namespace. + name (str): + Kubernetes Pod name. + labels (MutableSequence[google.cloud.securitycenter_v1.types.Label]): + Pod labels. For Kubernetes containers, these + are applied to the container. + containers (MutableSequence[google.cloud.securitycenter_v1.types.Container]): + Pod containers associated with this finding, + if any. + """ + + ns: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + labels: MutableSequence[label.Label] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=label.Label, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=container.Container, + ) + + class Node(proto.Message): + r"""Kubernetes nodes associated with the finding. + + Attributes: + name (str): + `Full resource + name `__ of + the Compute Engine VM running the cluster node. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + class NodePool(proto.Message): + r"""Provides GKE node pool information. + + Attributes: + name (str): + Kubernetes node pool name. + nodes (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Node]): + Nodes associated with the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + nodes: MutableSequence['Kubernetes.Node'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Kubernetes.Node', + ) + + class Role(proto.Message): + r"""Kubernetes Role or ClusterRole. + + Attributes: + kind (google.cloud.securitycenter_v1.types.Kubernetes.Role.Kind): + Role type. + ns (str): + Role namespace. + name (str): + Role name. + """ + class Kind(proto.Enum): + r"""Types of Kubernetes roles. + + Values: + KIND_UNSPECIFIED (0): + Role type is not specified. + ROLE (1): + Kubernetes Role. + CLUSTER_ROLE (2): + Kubernetes ClusterRole. + """ + KIND_UNSPECIFIED = 0 + ROLE = 1 + CLUSTER_ROLE = 2 + + kind: 'Kubernetes.Role.Kind' = proto.Field( + proto.ENUM, + number=1, + enum='Kubernetes.Role.Kind', + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class Binding(proto.Message): + r"""Represents a Kubernetes RoleBinding or ClusterRoleBinding. + + Attributes: + ns (str): + Namespace for the binding. + name (str): + Name for the binding. + role (google.cloud.securitycenter_v1.types.Kubernetes.Role): + The Role or ClusterRole referenced by the + binding. + subjects (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Subject]): + Represents one or more subjects that are + bound to the role. Not always available for + PATCH requests. + """ + + ns: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + role: 'Kubernetes.Role' = proto.Field( + proto.MESSAGE, + number=3, + message='Kubernetes.Role', + ) + subjects: MutableSequence['Kubernetes.Subject'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Kubernetes.Subject', + ) + + class Subject(proto.Message): + r"""Represents a Kubernetes subject. + + Attributes: + kind (google.cloud.securitycenter_v1.types.Kubernetes.Subject.AuthType): + Authentication type for the subject. + ns (str): + Namespace for the subject. + name (str): + Name for the subject. + """ + class AuthType(proto.Enum): + r"""Auth types that can be used for the subject's kind field. + + Values: + AUTH_TYPE_UNSPECIFIED (0): + Authentication is not specified. + USER (1): + User with valid certificate. + SERVICEACCOUNT (2): + Users managed by Kubernetes API with + credentials stored as secrets. + GROUP (3): + Collection of users. + """ + AUTH_TYPE_UNSPECIFIED = 0 + USER = 1 + SERVICEACCOUNT = 2 + GROUP = 3 + + kind: 'Kubernetes.Subject.AuthType' = proto.Field( + proto.ENUM, + number=1, + enum='Kubernetes.Subject.AuthType', + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class AccessReview(proto.Message): + r"""Conveys information about a Kubernetes access review (such as one + returned by a + ```kubectl auth can-i`` `__ + command) that was involved in a finding. + + Attributes: + group (str): + The API group of the resource. "*" means all. + ns (str): + Namespace of the action being requested. + Currently, there is no distinction between no + namespace and all namespaces. Both are + represented by "" (empty). + name (str): + The name of the resource being requested. + Empty means all. + resource (str): + The optional resource type requested. "*" means all. + subresource (str): + The optional subresource type. + verb (str): + A Kubernetes resource API verb, like get, list, watch, + create, update, delete, proxy. "*" means all. + version (str): + The API version of the resource. "*" means all. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + resource: str = proto.Field( + proto.STRING, + number=4, + ) + subresource: str = proto.Field( + proto.STRING, + number=5, + ) + verb: str = proto.Field( + proto.STRING, + number=6, + ) + version: str = proto.Field( + proto.STRING, + number=7, + ) + + class Object(proto.Message): + r"""Kubernetes object related to the finding, uniquely identified + by GKNN. Used if the object Kind is not one of Pod, Node, + NodePool, Binding, or AccessReview. + + Attributes: + group (str): + Kubernetes object group, such as + "policy.k8s.io/v1". + kind (str): + Kubernetes object kind, such as "Namespace". + ns (str): + Kubernetes object namespace. Must be a valid + DNS label. Named "ns" to avoid collision with + C++ namespace keyword. For details see + https://kubernetes.io/docs/tasks/administer-cluster/namespaces/. + name (str): + Kubernetes object name. For details see + https://kubernetes.io/docs/concepts/overview/working-with-objects/names/. + containers (MutableSequence[google.cloud.securitycenter_v1.types.Container]): + Pod containers associated with this finding, + if any. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + kind: str = proto.Field( + proto.STRING, + number=2, + ) + ns: str = proto.Field( + proto.STRING, + number=3, + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=container.Container, + ) + + pods: MutableSequence[Pod] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Pod, + ) + nodes: MutableSequence[Node] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Node, + ) + node_pools: MutableSequence[NodePool] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=NodePool, + ) + roles: MutableSequence[Role] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Role, + ) + bindings: MutableSequence[Binding] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Binding, + ) + access_reviews: MutableSequence[AccessReview] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=AccessReview, + ) + objects: MutableSequence[Object] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Object, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.py new file mode 100644 index 000000000000..8ece19d81c07 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.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.securitycenter.v1', + manifest={ + 'Label', + }, +) + + +class Label(proto.Message): + r"""Represents a generic name-value label. A label has separate name and + value fields to support filtering with the ``contains()`` function. + For more information, see `Filtering on array-type + fields `__. + + Attributes: + name (str): + Name of the label. + value (str): + Value that corresponds to the label's name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.py new file mode 100644 index 000000000000..050b3b0c6c9a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.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.cloud.securitycenter.v1', + manifest={ + 'LoadBalancer', + }, +) + + +class LoadBalancer(proto.Message): + r"""Contains information related to the load balancer associated + with the finding. + + Attributes: + name (str): + The name of the load balancer associated with + the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.py new file mode 100644 index 000000000000..6e4222745dd0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.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 __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.securitycenter.v1', + manifest={ + 'LogEntry', + 'CloudLoggingEntry', + }, +) + + +class LogEntry(proto.Message): + r"""An individual entry in a log. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_logging_entry (google.cloud.securitycenter_v1.types.CloudLoggingEntry): + An individual entry in a log stored in Cloud + Logging. + + This field is a member of `oneof`_ ``log_entry``. + """ + + cloud_logging_entry: 'CloudLoggingEntry' = proto.Field( + proto.MESSAGE, + number=1, + oneof='log_entry', + message='CloudLoggingEntry', + ) + + +class CloudLoggingEntry(proto.Message): + r"""Metadata taken from a `Cloud Logging + LogEntry `__ + + Attributes: + insert_id (str): + A unique identifier for the log entry. + log_id (str): + The type of the log (part of ``log_name``. ``log_name`` is + the resource name of the log to which this log entry + belongs). For example: + ``cloudresourcemanager.googleapis.com/activity``. Note that + this field is not URL-encoded, unlike the ``LOG_ID`` field + in ``LogEntry``. + resource_container (str): + The organization, folder, or project of the + monitored resource that produced this log entry. + timestamp (google.protobuf.timestamp_pb2.Timestamp): + The time the event described by the log entry + occurred. + """ + + insert_id: str = proto.Field( + proto.STRING, + number=1, + ) + log_id: str = proto.Field( + proto.STRING, + number=2, + ) + resource_container: str = proto.Field( + proto.STRING, + number=3, + ) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.py new file mode 100644 index 000000000000..1bdd822aa661 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'MitreAttack', + }, +) + + +class MitreAttack(proto.Message): + r"""MITRE ATT&CK tactics and techniques related to this finding. + See: https://attack.mitre.org + + Attributes: + primary_tactic (google.cloud.securitycenter_v1.types.MitreAttack.Tactic): + The MITRE ATT&CK tactic most closely + represented by this finding, if any. + primary_techniques (MutableSequence[google.cloud.securitycenter_v1.types.MitreAttack.Technique]): + The MITRE ATT&CK technique most closely represented by this + finding, if any. primary_techniques is a repeated field + because there are multiple levels of MITRE ATT&CK + techniques. If the technique most closely represented by + this finding is a sub-technique (e.g. + ``SCANNING_IP_BLOCKS``), both the sub-technique and its + parent technique(s) will be listed (e.g. + ``SCANNING_IP_BLOCKS``, ``ACTIVE_SCANNING``). + additional_tactics (MutableSequence[google.cloud.securitycenter_v1.types.MitreAttack.Tactic]): + Additional MITRE ATT&CK tactics related to + this finding, if any. + additional_techniques (MutableSequence[google.cloud.securitycenter_v1.types.MitreAttack.Technique]): + Additional MITRE ATT&CK techniques related to + this finding, if any, along with any of their + respective parent techniques. + version (str): + The MITRE ATT&CK version referenced by the + above fields. E.g. "8". + """ + class Tactic(proto.Enum): + r"""MITRE ATT&CK tactics that can be referenced by SCC findings. + See: https://attack.mitre.org/tactics/enterprise/ + + Values: + TACTIC_UNSPECIFIED (0): + Unspecified value. + RECONNAISSANCE (1): + TA0043 + RESOURCE_DEVELOPMENT (2): + TA0042 + INITIAL_ACCESS (5): + TA0001 + EXECUTION (3): + TA0002 + PERSISTENCE (6): + TA0003 + PRIVILEGE_ESCALATION (8): + TA0004 + DEFENSE_EVASION (7): + TA0005 + CREDENTIAL_ACCESS (9): + TA0006 + DISCOVERY (10): + TA0007 + LATERAL_MOVEMENT (11): + TA0008 + COLLECTION (12): + TA0009 + COMMAND_AND_CONTROL (4): + TA0011 + EXFILTRATION (13): + TA0010 + IMPACT (14): + TA0040 + """ + TACTIC_UNSPECIFIED = 0 + RECONNAISSANCE = 1 + RESOURCE_DEVELOPMENT = 2 + INITIAL_ACCESS = 5 + EXECUTION = 3 + PERSISTENCE = 6 + PRIVILEGE_ESCALATION = 8 + DEFENSE_EVASION = 7 + CREDENTIAL_ACCESS = 9 + DISCOVERY = 10 + LATERAL_MOVEMENT = 11 + COLLECTION = 12 + COMMAND_AND_CONTROL = 4 + EXFILTRATION = 13 + IMPACT = 14 + + class Technique(proto.Enum): + r"""MITRE ATT&CK techniques that can be referenced by SCC + findings. See: https://attack.mitre.org/techniques/enterprise/ + Next ID: 65 + + Values: + TECHNIQUE_UNSPECIFIED (0): + Unspecified value. + MASQUERADING (49): + T1036 + MATCH_LEGITIMATE_NAME_OR_LOCATION (50): + T1036.005 + BOOT_OR_LOGON_INITIALIZATION_SCRIPTS (37): + T1037 + STARTUP_ITEMS (38): + T1037.005 + NETWORK_SERVICE_DISCOVERY (32): + T1046 + PROCESS_DISCOVERY (56): + T1057 + COMMAND_AND_SCRIPTING_INTERPRETER (6): + T1059 + UNIX_SHELL (7): + T1059.004 + PYTHON (59): + T1059.006 + EXPLOITATION_FOR_PRIVILEGE_ESCALATION (63): + T1068 + PERMISSION_GROUPS_DISCOVERY (18): + T1069 + CLOUD_GROUPS (19): + T1069.003 + INDICATOR_REMOVAL_FILE_DELETION (64): + T1070.004 + APPLICATION_LAYER_PROTOCOL (45): + T1071 + DNS (46): + T1071.004 + SOFTWARE_DEPLOYMENT_TOOLS (47): + T1072 + VALID_ACCOUNTS (14): + T1078 + DEFAULT_ACCOUNTS (35): + T1078.001 + LOCAL_ACCOUNTS (15): + T1078.003 + CLOUD_ACCOUNTS (16): + T1078.004 + PROXY (9): + T1090 + EXTERNAL_PROXY (10): + T1090.002 + MULTI_HOP_PROXY (11): + T1090.003 + ACCOUNT_MANIPULATION (22): + T1098 + ADDITIONAL_CLOUD_CREDENTIALS (40): + T1098.001 + SSH_AUTHORIZED_KEYS (23): + T1098.004 + ADDITIONAL_CONTAINER_CLUSTER_ROLES (58): + T1098.006 + INGRESS_TOOL_TRANSFER (3): + T1105 + NATIVE_API (4): + T1106 + BRUTE_FORCE (44): + T1110 + SHARED_MODULES (5): + T1129 + ACCESS_TOKEN_MANIPULATION (33): + T1134 + TOKEN_IMPERSONATION_OR_THEFT (39): + T1134.001 + EXPLOIT_PUBLIC_FACING_APPLICATION (27): + T1190 + DOMAIN_POLICY_MODIFICATION (30): + T1484 + DATA_DESTRUCTION (29): + T1485 + SERVICE_STOP (52): + T1489 + INHIBIT_SYSTEM_RECOVERY (36): + T1490 + RESOURCE_HIJACKING (8): + T1496 + NETWORK_DENIAL_OF_SERVICE (17): + T1498 + CLOUD_SERVICE_DISCOVERY (48): + T1526 + STEAL_APPLICATION_ACCESS_TOKEN (42): + T1528 + ACCOUNT_ACCESS_REMOVAL (51): + T1531 + STEAL_WEB_SESSION_COOKIE (25): + T1539 + CREATE_OR_MODIFY_SYSTEM_PROCESS (24): + T1543 + ABUSE_ELEVATION_CONTROL_MECHANISM (34): + T1548 + UNSECURED_CREDENTIALS (13): + T1552 + MODIFY_AUTHENTICATION_PROCESS (28): + T1556 + IMPAIR_DEFENSES (31): + T1562 + DISABLE_OR_MODIFY_TOOLS (55): + T1562.001 + EXFILTRATION_OVER_WEB_SERVICE (20): + T1567 + EXFILTRATION_TO_CLOUD_STORAGE (21): + T1567.002 + DYNAMIC_RESOLUTION (12): + T1568 + LATERAL_TOOL_TRANSFER (41): + T1570 + MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE (26): + T1578 + CREATE_SNAPSHOT (54): + T1578.001 + CLOUD_INFRASTRUCTURE_DISCOVERY (53): + T1580 + OBTAIN_CAPABILITIES (43): + T1588 + ACTIVE_SCANNING (1): + T1595 + SCANNING_IP_BLOCKS (2): + T1595.001 + CONTAINER_ADMINISTRATION_COMMAND (60): + T1609 + ESCAPE_TO_HOST (61): + T1611 + CONTAINER_AND_RESOURCE_DISCOVERY (57): + T1613 + STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES (62): + T1649 + """ + TECHNIQUE_UNSPECIFIED = 0 + MASQUERADING = 49 + MATCH_LEGITIMATE_NAME_OR_LOCATION = 50 + BOOT_OR_LOGON_INITIALIZATION_SCRIPTS = 37 + STARTUP_ITEMS = 38 + NETWORK_SERVICE_DISCOVERY = 32 + PROCESS_DISCOVERY = 56 + COMMAND_AND_SCRIPTING_INTERPRETER = 6 + UNIX_SHELL = 7 + PYTHON = 59 + EXPLOITATION_FOR_PRIVILEGE_ESCALATION = 63 + PERMISSION_GROUPS_DISCOVERY = 18 + CLOUD_GROUPS = 19 + INDICATOR_REMOVAL_FILE_DELETION = 64 + APPLICATION_LAYER_PROTOCOL = 45 + DNS = 46 + SOFTWARE_DEPLOYMENT_TOOLS = 47 + VALID_ACCOUNTS = 14 + DEFAULT_ACCOUNTS = 35 + LOCAL_ACCOUNTS = 15 + CLOUD_ACCOUNTS = 16 + PROXY = 9 + EXTERNAL_PROXY = 10 + MULTI_HOP_PROXY = 11 + ACCOUNT_MANIPULATION = 22 + ADDITIONAL_CLOUD_CREDENTIALS = 40 + SSH_AUTHORIZED_KEYS = 23 + ADDITIONAL_CONTAINER_CLUSTER_ROLES = 58 + INGRESS_TOOL_TRANSFER = 3 + NATIVE_API = 4 + BRUTE_FORCE = 44 + SHARED_MODULES = 5 + ACCESS_TOKEN_MANIPULATION = 33 + TOKEN_IMPERSONATION_OR_THEFT = 39 + EXPLOIT_PUBLIC_FACING_APPLICATION = 27 + DOMAIN_POLICY_MODIFICATION = 30 + DATA_DESTRUCTION = 29 + SERVICE_STOP = 52 + INHIBIT_SYSTEM_RECOVERY = 36 + RESOURCE_HIJACKING = 8 + NETWORK_DENIAL_OF_SERVICE = 17 + CLOUD_SERVICE_DISCOVERY = 48 + STEAL_APPLICATION_ACCESS_TOKEN = 42 + ACCOUNT_ACCESS_REMOVAL = 51 + STEAL_WEB_SESSION_COOKIE = 25 + CREATE_OR_MODIFY_SYSTEM_PROCESS = 24 + ABUSE_ELEVATION_CONTROL_MECHANISM = 34 + UNSECURED_CREDENTIALS = 13 + MODIFY_AUTHENTICATION_PROCESS = 28 + IMPAIR_DEFENSES = 31 + DISABLE_OR_MODIFY_TOOLS = 55 + EXFILTRATION_OVER_WEB_SERVICE = 20 + EXFILTRATION_TO_CLOUD_STORAGE = 21 + DYNAMIC_RESOLUTION = 12 + LATERAL_TOOL_TRANSFER = 41 + MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE = 26 + CREATE_SNAPSHOT = 54 + CLOUD_INFRASTRUCTURE_DISCOVERY = 53 + OBTAIN_CAPABILITIES = 43 + ACTIVE_SCANNING = 1 + SCANNING_IP_BLOCKS = 2 + CONTAINER_ADMINISTRATION_COMMAND = 60 + ESCAPE_TO_HOST = 61 + CONTAINER_AND_RESOURCE_DISCOVERY = 57 + STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES = 62 + + primary_tactic: Tactic = proto.Field( + proto.ENUM, + number=1, + enum=Tactic, + ) + primary_techniques: MutableSequence[Technique] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=Technique, + ) + additional_tactics: MutableSequence[Tactic] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=Tactic, + ) + additional_techniques: MutableSequence[Technique] = proto.RepeatedField( + proto.ENUM, + number=4, + enum=Technique, + ) + version: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py new file mode 100644 index 000000000000..f6be11e40d9c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py @@ -0,0 +1,171 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'MuteConfig', + }, +) + + +class MuteConfig(proto.Message): + r"""A mute config is a Cloud SCC resource that contains the + configuration to mute create/update events of findings. + + Attributes: + name (str): + This field will be ignored if provided on config creation. + Format + ``organizations/{organization}/muteConfigs/{mute_config}`` + ``folders/{folder}/muteConfigs/{mute_config}`` + ``projects/{project}/muteConfigs/{mute_config}`` + ``organizations/{organization}/locations/global/muteConfigs/{mute_config}`` + ``folders/{folder}/locations/global/muteConfigs/{mute_config}`` + ``projects/{project}/locations/global/muteConfigs/{mute_config}`` + display_name (str): + The human readable name to be displayed for + the mute config. + description (str): + A description of the mute config. + filter (str): + Required. An expression that defines the filter to apply + across create/update events of findings. While creating a + filter string, be mindful of the scope in which the mute + configuration is being created. E.g., If a filter contains + project = X but is created under the project = Y scope, it + might not match any findings. + + The following field and operator combinations are supported: + + - severity: ``=``, ``:`` + - category: ``=``, ``:`` + - resource.name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.folders.resource_folder: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + - finding_class: ``=``, ``:`` + - indicator.ip_addresses: ``=``, ``:`` + - indicator.domains: ``=``, ``:`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the mute + config was created. This field is set by the + server and will be ignored if provided on config + creation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time at which + the mute config was updated. This field is set + by the server and will be ignored if provided on + config creation or update. + most_recent_editor (str): + Output only. Email address of the user who + last edited the mute config. This field is set + by the server and will be ignored if provided on + config creation or update. + type_ (google.cloud.securitycenter_v1.types.MuteConfig.MuteConfigType): + Optional. The type of the mute config, which + determines what type of mute state the config + affects. The static mute state takes precedence + over the dynamic mute state. Immutable after + creation. STATIC by default if not set during + creation. + expiry_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The expiry of the mute config. Only + applicable for dynamic configs. If the expiry is + set, when the config expires, it is removed from + all findings. + """ + class MuteConfigType(proto.Enum): + r"""The type of MuteConfig. + + Values: + MUTE_CONFIG_TYPE_UNSPECIFIED (0): + Unused. + STATIC (1): + A static mute config, which sets the static + mute state of future matching findings to muted. + Once the static mute state has been set, finding + or config modifications will not affect the + state. + DYNAMIC (2): + A dynamic mute config, which is applied to + existing and future matching findings, setting + their dynamic mute state to "muted". If the + config is updated or deleted, or a matching + finding is updated, such that the finding + doesn't match the config, the config will be + removed from the finding, and the finding's + dynamic mute state may become "unmuted" (unless + other configs still match). + """ + MUTE_CONFIG_TYPE_UNSPECIFIED = 0 + STATIC = 1 + DYNAMIC = 2 + + 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, + ) + filter: 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, + ) + most_recent_editor: str = proto.Field( + proto.STRING, + number=7, + ) + type_: MuteConfigType = proto.Field( + proto.ENUM, + number=8, + enum=MuteConfigType, + ) + expiry_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py new file mode 100644 index 000000000000..564197159f0c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v1', + manifest={ + 'Notebook', + }, +) + + +class Notebook(proto.Message): + r"""Represents a Jupyter notebook IPYNB file, such as a `Colab + Enterprise + notebook `__ file, + that is associated with a finding. + + Attributes: + name (str): + The name of the notebook. + service (str): + The source notebook service, for example, + "Colab Enterprise". + last_author (str): + The user ID of the latest author to modify + the notebook. + notebook_update_time (google.protobuf.timestamp_pb2.Timestamp): + The most recent time the notebook was + updated. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + service: str = proto.Field( + proto.STRING, + number=2, + ) + last_author: str = proto.Field( + proto.STRING, + number=3, + ) + notebook_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.py new file mode 100644 index 000000000000..d26990314b74 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'NotificationConfig', + }, +) + + +class NotificationConfig(proto.Message): + r"""Cloud Security Command Center (Cloud SCC) notification + configs. + A notification config is a Cloud SCC resource that contains the + configuration to send notifications for create/update events of + findings, assets and etc. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The relative resource name of this notification config. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/notificationConfigs/notify_public_bucket", + "folders/{folder_id}/notificationConfigs/notify_public_bucket", + or + "projects/{project_id}/notificationConfigs/notify_public_bucket". + description (str): + The description of the notification config + (max of 1024 characters). + pubsub_topic (str): + The Pub/Sub topic to send notifications to. Its format is + "projects/[project_id]/topics/[topic]". + service_account (str): + Output only. The service account that needs + "pubsub.topics.publish" permission to publish to + the Pub/Sub topic. + streaming_config (google.cloud.securitycenter_v1.types.NotificationConfig.StreamingConfig): + The config for triggering streaming-based + notifications. + + This field is a member of `oneof`_ ``notify_config``. + """ + + class StreamingConfig(proto.Message): + r"""The config for streaming-based notifications, which send each + event as soon as it is detected. + + Attributes: + filter (str): + Expression that defines the filter to apply across + create/update events of assets or findings as specified by + the event type. The expression is a list of zero or more + restrictions combined via logical operators ``AND`` and + ``OR``. Parentheses are supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + """ + + filter: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + pubsub_topic: str = proto.Field( + proto.STRING, + number=3, + ) + service_account: str = proto.Field( + proto.STRING, + number=4, + ) + streaming_config: StreamingConfig = proto.Field( + proto.MESSAGE, + number=5, + oneof='notify_config', + message=StreamingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.py new file mode 100644 index 000000000000..f979d5f7a0ec --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import resource as gcs_resource + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'NotificationMessage', + }, +) + + +class NotificationMessage(proto.Message): + r"""Cloud SCC's Notification + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + notification_config_name (str): + Name of the notification config that + generated current notification. + finding (google.cloud.securitycenter_v1.types.Finding): + If it's a Finding based notification config, + this field will be populated. + + This field is a member of `oneof`_ ``event``. + resource (google.cloud.securitycenter_v1.types.Resource): + The Cloud resource tied to this + notification's Finding. + """ + + notification_config_name: str = proto.Field( + proto.STRING, + number=1, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=2, + oneof='event', + message=gcs_finding.Finding, + ) + resource: gcs_resource.Resource = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_resource.Resource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.py new file mode 100644 index 000000000000..ebd7ac4b0424 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.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.cloud.securitycenter.v1', + manifest={ + 'OrgPolicy', + }, +) + + +class OrgPolicy(proto.Message): + r"""Contains information about the org policies associated with + the finding. + + Attributes: + name (str): + The resource name of the org policy. Example: + "organizations/{organization_id}/policies/{constraint_name}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.py new file mode 100644 index 000000000000..81c2816a1e66 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'OrganizationSettings', + }, +) + + +class OrganizationSettings(proto.Message): + r"""User specified settings that are attached to the Security + Command Center organization. + + Attributes: + name (str): + The relative resource name of the settings. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/organizationSettings". + enable_asset_discovery (bool): + A flag that indicates if Asset Discovery should be enabled. + If the flag is set to ``true``, then discovery of assets + will occur. If it is set to ``false``, all historical assets + will remain, but discovery of future assets will not occur. + asset_discovery_config (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig): + The configuration used for Asset Discovery + runs. + """ + + class AssetDiscoveryConfig(proto.Message): + r"""The configuration used for Asset Discovery runs. + + Attributes: + project_ids (MutableSequence[str]): + The project ids to use for filtering asset + discovery. + inclusion_mode (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + The mode to use for filtering asset + discovery. + folder_ids (MutableSequence[str]): + The folder ids to use for filtering asset + discovery. It consists of only digits, e.g., + 756619654966. + """ + class InclusionMode(proto.Enum): + r"""The mode of inclusion when running Asset Discovery. Asset discovery + can be limited by explicitly identifying projects to be included or + excluded. If INCLUDE_ONLY is set, then only those projects within + the organization and their children are discovered during asset + discovery. If EXCLUDE is set, then projects that don't match those + projects are discovered during asset discovery. If neither are set, + then all projects within the organization are discovered during + asset discovery. + + Values: + INCLUSION_MODE_UNSPECIFIED (0): + Unspecified. Setting the mode with this value + will disable inclusion/exclusion filtering for + Asset Discovery. + INCLUDE_ONLY (1): + Asset Discovery will capture only the + resources within the projects specified. All + other resources will be ignored. + EXCLUDE (2): + Asset Discovery will ignore all resources + under the projects specified. All other + resources will be retrieved. + """ + INCLUSION_MODE_UNSPECIFIED = 0 + INCLUDE_ONLY = 1 + EXCLUDE = 2 + + project_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + inclusion_mode: 'OrganizationSettings.AssetDiscoveryConfig.InclusionMode' = proto.Field( + proto.ENUM, + number=2, + enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', + ) + folder_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + enable_asset_discovery: bool = proto.Field( + proto.BOOL, + number=2, + ) + asset_discovery_config: AssetDiscoveryConfig = proto.Field( + proto.MESSAGE, + number=3, + message=AssetDiscoveryConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py new file mode 100644 index 000000000000..881b8df6dfa1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1.types import file + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Process', + 'EnvironmentVariable', + }, +) + + +class Process(proto.Message): + r"""Represents an operating system process. + + Attributes: + name (str): + The process name, as displayed in utilities like ``top`` and + ``ps``. This name can be accessed through + ``/proc/[pid]/comm`` and changed with + ``prctl(PR_SET_NAME)``. + binary (google.cloud.securitycenter_v1.types.File): + File information for the process executable. + libraries (MutableSequence[google.cloud.securitycenter_v1.types.File]): + File information for libraries loaded by the + process. + script (google.cloud.securitycenter_v1.types.File): + When the process represents the invocation of a script, + ``binary`` provides information about the interpreter, while + ``script`` provides information about the script file + provided to the interpreter. + args (MutableSequence[str]): + Process arguments as JSON encoded strings. + arguments_truncated (bool): + True if ``args`` is incomplete. + env_variables (MutableSequence[google.cloud.securitycenter_v1.types.EnvironmentVariable]): + Process environment variables. + env_variables_truncated (bool): + True if ``env_variables`` is incomplete. + pid (int): + The process ID. + parent_pid (int): + The parent process ID. + """ + + name: str = proto.Field( + proto.STRING, + number=12, + ) + binary: file.File = proto.Field( + proto.MESSAGE, + number=3, + message=file.File, + ) + libraries: MutableSequence[file.File] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=file.File, + ) + script: file.File = proto.Field( + proto.MESSAGE, + number=5, + message=file.File, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + arguments_truncated: bool = proto.Field( + proto.BOOL, + number=7, + ) + env_variables: MutableSequence['EnvironmentVariable'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='EnvironmentVariable', + ) + env_variables_truncated: bool = proto.Field( + proto.BOOL, + number=9, + ) + pid: int = proto.Field( + proto.INT64, + number=10, + ) + parent_pid: int = proto.Field( + proto.INT64, + number=11, + ) + + +class EnvironmentVariable(proto.Message): + r"""A name-value pair representing an environment variable used + in an operating system process. + + Attributes: + name (str): + Environment variable name as a JSON encoded + string. + val (str): + Environment variable value as a JSON encoded + string. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + val: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py new file mode 100644 index 000000000000..f66c0ab5f06d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py @@ -0,0 +1,474 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1.types import folder + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'CloudProvider', + 'Resource', + 'AwsMetadata', + 'AzureMetadata', + 'ResourcePath', + }, +) + + +class CloudProvider(proto.Enum): + r"""Enumeration representing the various cloud providers a + finding's resource could reside in. + + Values: + CLOUD_PROVIDER_UNSPECIFIED (0): + The cloud provider is unspecified. + GOOGLE_CLOUD_PLATFORM (1): + The cloud provider is Google Cloud Platform. + AMAZON_WEB_SERVICES (2): + The cloud provider is Amazon Web Services. + MICROSOFT_AZURE (3): + The cloud provider is Microsoft Azure. + """ + CLOUD_PROVIDER_UNSPECIFIED = 0 + GOOGLE_CLOUD_PLATFORM = 1 + AMAZON_WEB_SERVICES = 2 + MICROSOFT_AZURE = 3 + + +class Resource(proto.Message): + r"""Information related to the Google Cloud 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): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + display_name (str): + The human readable name of the resource. + type_ (str): + The full resource type of the resource. + project (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The project ID that the resource belongs to. + parent (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (MutableSequence[google.cloud.securitycenter_v1.types.Folder]): + Output only. Contains a Folder message for + each folder in the assets ancestry. The first + folder is the deepest nested folder, and the + last folder is the folder directly under the + Organization. + cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): + Indicates which cloud provider the resource + resides in. + organization (str): + Indicates which organization or tenant in the + cloud provider the finding applies to. + service (str): + The parent service or product from which the + resource is provided, for example, GKE or SNS. + location (str): + The region or location of the service (if + applicable). + aws_metadata (google.cloud.securitycenter_v1.types.AwsMetadata): + The AWS metadata associated with the finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + azure_metadata (google.cloud.securitycenter_v1.types.AzureMetadata): + The Azure metadata associated with the + finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + resource_path (google.cloud.securitycenter_v1.types.ResourcePath): + Provides the path to the resource within the + resource hierarchy. + resource_path_string (str): + A string representation of the resource path. For Google + Cloud, it has the format of + ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` + where there can be any number of folders. For AWS, it has + the format of + ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` + where there can be any number of organizational units. For + Azure, it has the format of + ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` + where there can be any number of management groups. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=8, + ) + type_: str = proto.Field( + proto.STRING, + number=6, + ) + project: str = proto.Field( + proto.STRING, + number=2, + ) + project_display_name: str = proto.Field( + proto.STRING, + number=3, + ) + parent: str = proto.Field( + proto.STRING, + number=4, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=5, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=folder.Folder, + ) + cloud_provider: 'CloudProvider' = proto.Field( + proto.ENUM, + number=9, + enum='CloudProvider', + ) + organization: str = proto.Field( + proto.STRING, + number=10, + ) + service: str = proto.Field( + proto.STRING, + number=11, + ) + location: str = proto.Field( + proto.STRING, + number=12, + ) + aws_metadata: 'AwsMetadata' = proto.Field( + proto.MESSAGE, + number=16, + oneof='cloud_provider_metadata', + message='AwsMetadata', + ) + azure_metadata: 'AzureMetadata' = proto.Field( + proto.MESSAGE, + number=17, + oneof='cloud_provider_metadata', + message='AzureMetadata', + ) + resource_path: 'ResourcePath' = proto.Field( + proto.MESSAGE, + number=18, + message='ResourcePath', + ) + resource_path_string: str = proto.Field( + proto.STRING, + number=19, + ) + + +class AwsMetadata(proto.Message): + r"""AWS metadata associated with the resource, only applicable if + the finding's cloud provider is Amazon Web Services. + + Attributes: + organization (google.cloud.securitycenter_v1.types.AwsMetadata.AwsOrganization): + The AWS organization associated with the + resource. + organizational_units (MutableSequence[google.cloud.securitycenter_v1.types.AwsMetadata.AwsOrganizationalUnit]): + A list of AWS organizational units associated + with the resource, ordered from lowest level + (closest to the account) to highest level. + account (google.cloud.securitycenter_v1.types.AwsMetadata.AwsAccount): + The AWS account associated with the resource. + """ + + class AwsOrganization(proto.Message): + r"""An organization is a collection of accounts that are + centrally managed together using consolidated billing, organized + hierarchically with organizational units (OUs), and controlled + with policies. + + Attributes: + id (str): + The unique identifier (ID) for the + organization. The regex pattern for an + organization ID string requires "o-" followed by + from 10 to 32 lowercase letters or digits. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + + class AwsOrganizationalUnit(proto.Message): + r"""An Organizational Unit (OU) is a container of AWS accounts + within a root of an organization. Policies that are attached to + an OU apply to all accounts contained in that OU and in any + child OUs. + + Attributes: + id (str): + The unique identifier (ID) associated with + this OU. The regex pattern for an organizational + unit ID string requires "ou-" followed by from 4 + to 32 lowercase letters or digits (the ID of the + root that contains the OU). This string is + followed by a second "-" dash and from 8 to 32 + additional lowercase letters or digits. For + example, "ou-ab12-cd34ef56". + name (str): + The friendly name of the OU. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + + class AwsAccount(proto.Message): + r"""An AWS account that is a member of an organization. + + Attributes: + id (str): + The unique identifier (ID) of the account, + containing exactly 12 digits. + name (str): + The friendly name of this account. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + + organization: AwsOrganization = proto.Field( + proto.MESSAGE, + number=2, + message=AwsOrganization, + ) + organizational_units: MutableSequence[AwsOrganizationalUnit] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=AwsOrganizationalUnit, + ) + account: AwsAccount = proto.Field( + proto.MESSAGE, + number=4, + message=AwsAccount, + ) + + +class AzureMetadata(proto.Message): + r"""Azure metadata associated with the resource, only applicable + if the finding's cloud provider is Microsoft Azure. + + Attributes: + management_groups (MutableSequence[google.cloud.securitycenter_v1.types.AzureMetadata.AzureManagementGroup]): + A list of Azure management groups associated + with the resource, ordered from lowest level + (closest to the subscription) to highest level. + subscription (google.cloud.securitycenter_v1.types.AzureMetadata.AzureSubscription): + The Azure subscription associated with the + resource. + resource_group (google.cloud.securitycenter_v1.types.AzureMetadata.AzureResourceGroup): + The Azure resource group associated with the + resource. + """ + + class AzureManagementGroup(proto.Message): + r"""Represents an Azure management group. + + Attributes: + id (str): + The UUID of the Azure management group, for example, + ``20000000-0001-0000-0000-000000000000``. + display_name (str): + The display name of the Azure management + group. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + class AzureSubscription(proto.Message): + r"""Represents an Azure subscription. + + Attributes: + id (str): + The UUID of the Azure subscription, for example, + ``291bba3f-e0a5-47bc-a099-3bdcb2a50a05``. + display_name (str): + The display name of the Azure subscription. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + class AzureResourceGroup(proto.Message): + r"""Represents an Azure resource group. + + Attributes: + name (str): + The name of the Azure resource group. This is + not a UUID. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + management_groups: MutableSequence[AzureManagementGroup] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=AzureManagementGroup, + ) + subscription: AzureSubscription = proto.Field( + proto.MESSAGE, + number=5, + message=AzureSubscription, + ) + resource_group: AzureResourceGroup = proto.Field( + proto.MESSAGE, + number=6, + message=AzureResourceGroup, + ) + + +class ResourcePath(proto.Message): + r"""Represents the path of resources leading up to the resource + this finding is about. + + Attributes: + nodes (MutableSequence[google.cloud.securitycenter_v1.types.ResourcePath.ResourcePathNode]): + The list of nodes that make the up resource + path, ordered from lowest level to highest + level. + """ + class ResourcePathNodeType(proto.Enum): + r"""The type of resource the node represents. + + Values: + RESOURCE_PATH_NODE_TYPE_UNSPECIFIED (0): + Node type is unspecified. + GCP_ORGANIZATION (1): + The node represents a Google Cloud + organization. + GCP_FOLDER (2): + The node represents a Google Cloud folder. + GCP_PROJECT (3): + The node represents a Google Cloud project. + AWS_ORGANIZATION (4): + The node represents an AWS organization. + AWS_ORGANIZATIONAL_UNIT (5): + The node represents an AWS organizational + unit. + AWS_ACCOUNT (6): + The node represents an AWS account. + AZURE_MANAGEMENT_GROUP (7): + The node represents an Azure management + group. + AZURE_SUBSCRIPTION (8): + The node represents an Azure subscription. + AZURE_RESOURCE_GROUP (9): + The node represents an Azure resource group. + """ + RESOURCE_PATH_NODE_TYPE_UNSPECIFIED = 0 + GCP_ORGANIZATION = 1 + GCP_FOLDER = 2 + GCP_PROJECT = 3 + AWS_ORGANIZATION = 4 + AWS_ORGANIZATIONAL_UNIT = 5 + AWS_ACCOUNT = 6 + AZURE_MANAGEMENT_GROUP = 7 + AZURE_SUBSCRIPTION = 8 + AZURE_RESOURCE_GROUP = 9 + + class ResourcePathNode(proto.Message): + r"""A node within the resource path. Each node represents a + resource within the resource hierarchy. + + Attributes: + node_type (google.cloud.securitycenter_v1.types.ResourcePath.ResourcePathNodeType): + The type of resource this node represents. + id (str): + The ID of the resource this node represents. + display_name (str): + The display name of the resource this node + represents. + """ + + node_type: 'ResourcePath.ResourcePathNodeType' = proto.Field( + proto.ENUM, + number=1, + enum='ResourcePath.ResourcePathNodeType', + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + + nodes: MutableSequence[ResourcePathNode] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ResourcePathNode, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py new file mode 100644 index 000000000000..f88354103169 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1.types import resource +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'ResourceValue', + 'ResourceValueConfig', + }, +) + + +class ResourceValue(proto.Enum): + r"""Value enum to map to a resource + + Values: + RESOURCE_VALUE_UNSPECIFIED (0): + Unspecific value + HIGH (1): + High resource value + MEDIUM (2): + Medium resource value + LOW (3): + Low resource value + NONE (4): + No resource value, e.g. ignore these + resources + """ + RESOURCE_VALUE_UNSPECIFIED = 0 + HIGH = 1 + MEDIUM = 2 + LOW = 3 + NONE = 4 + + +class ResourceValueConfig(proto.Message): + r"""A resource value configuration (RVC) is a mapping + configuration of user's resources to resource values. Used in + Attack path simulations. + + Attributes: + name (str): + Name for the resource value configuration + resource_value (google.cloud.securitycenter_v1.types.ResourceValue): + Required. Resource value level this + expression represents + tag_values (MutableSequence[str]): + Required. Tag values combined with ``AND`` to check against. + Values in the form "tagValues/123" Example: + ``[ "tagValues/123", "tagValues/456", "tagValues/789" ]`` + https://cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing + resource_type (str): + Apply resource_value only to resources that match + resource_type. resource_type will be checked with ``AND`` of + other resources. For example, + "storage.googleapis.com/Bucket" with resource_value "HIGH" + will apply "HIGH" value only to + "storage.googleapis.com/Bucket" resources. + scope (str): + Project or folder to scope this configuration to. For + example, "project/456" would apply this configuration only + to resources in "project/456" scope will be checked with + ``AND`` of other resources. + resource_labels_selector (MutableMapping[str, str]): + List of resource labels to search for, evaluated with + ``AND``. For example, + ``"resource_labels_selector": {"key": "value", "env": "prod"}`` + will match resources with labels "key": "value" ``AND`` + "env": "prod" + https://cloud.google.com/resource-manager/docs/creating-managing-labels + description (str): + Description of the resource value + configuration. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp this resource value + configuration was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp this resource value + configuration was last updated. + cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): + Cloud provider this configuration applies to + sensitive_data_protection_mapping (google.cloud.securitycenter_v1.types.ResourceValueConfig.SensitiveDataProtectionMapping): + A mapping of the sensitivity on Sensitive Data Protection + finding to resource values. This mapping can only be used in + combination with a resource_type that is related to + BigQuery, e.g. "bigquery.googleapis.com/Dataset". + """ + + class SensitiveDataProtectionMapping(proto.Message): + r"""Resource value mapping for Sensitive Data Protection findings. If + any of these mappings have a resource value that is not unspecified, + the resource_value field will be ignored when reading this + configuration. + + Attributes: + high_sensitivity_mapping (google.cloud.securitycenter_v1.types.ResourceValue): + Resource value mapping for high-sensitivity + Sensitive Data Protection findings + medium_sensitivity_mapping (google.cloud.securitycenter_v1.types.ResourceValue): + Resource value mapping for medium-sensitivity + Sensitive Data Protection findings + """ + + high_sensitivity_mapping: 'ResourceValue' = proto.Field( + proto.ENUM, + number=1, + enum='ResourceValue', + ) + medium_sensitivity_mapping: 'ResourceValue' = proto.Field( + proto.ENUM, + number=2, + enum='ResourceValue', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_value: 'ResourceValue' = proto.Field( + proto.ENUM, + number=2, + enum='ResourceValue', + ) + tag_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + resource_type: str = proto.Field( + proto.STRING, + number=4, + ) + scope: str = proto.Field( + proto.STRING, + number=5, + ) + resource_labels_selector: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + description: str = proto.Field( + proto.STRING, + number=7, + ) + 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, + ) + cloud_provider: resource.CloudProvider = proto.Field( + proto.ENUM, + number=10, + enum=resource.CloudProvider, + ) + sensitive_data_protection_mapping: SensitiveDataProtectionMapping = proto.Field( + proto.MESSAGE, + number=11, + message=SensitiveDataProtectionMapping, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py new file mode 100644 index 000000000000..e6ccc16862c3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.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 + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'RunAssetDiscoveryResponse', + }, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + + Attributes: + state (google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (google.protobuf.duration_pb2.Duration): + The duration between asset discovery run + start and end + """ + class State(proto.Enum): + r"""The state of an asset discovery run. + + Values: + STATE_UNSPECIFIED (0): + Asset discovery run state was unspecified. + COMPLETED (1): + Asset discovery run completed successfully. + SUPERSEDED (2): + Asset discovery run was cancelled with tasks + still pending, as another run for the same + organization was started with a higher priority. + TERMINATED (3): + Asset discovery run was killed and + terminated. + """ + STATE_UNSPECIFIED = 0 + COMPLETED = 1 + SUPERSEDED = 2 + TERMINATED = 3 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py new file mode 100644 index 000000000000..bb412145607c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py @@ -0,0 +1,173 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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 expr_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'CustomConfig', + }, +) + + +class CustomConfig(proto.Message): + r"""Defines the properties in a custom module configuration for + Security Health Analytics. Use the custom module configuration + to create custom detectors that generate custom findings for + resources that you specify. + + Attributes: + predicate (google.type.expr_pb2.Expr): + The CEL expression to evaluate to produce + findings. When the expression evaluates to true + against a resource, a finding is generated. + custom_output (google.cloud.securitycenter_v1.types.CustomConfig.CustomOutputSpec): + Custom output properties. + resource_selector (google.cloud.securitycenter_v1.types.CustomConfig.ResourceSelector): + The resource types that the custom module + operates on. Each custom module can specify up + to 5 resource types. + severity (google.cloud.securitycenter_v1.types.CustomConfig.Severity): + The severity to assign to findings generated + by the module. + description (str): + Text that describes the vulnerability or + misconfiguration that the custom module detects. + This explanation is returned with each finding + instance to help investigators understand the + detected issue. The text must be enclosed in + quotation marks. + recommendation (str): + An explanation of the recommended steps that security teams + can take to resolve the detected issue. This explanation is + returned with each finding generated by this module in the + ``nextSteps`` property of the finding JSON. + """ + class Severity(proto.Enum): + r"""Defines the valid value options for the severity of a + finding. + + Values: + SEVERITY_UNSPECIFIED (0): + Unspecified severity. + 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 + + class CustomOutputSpec(proto.Message): + r"""A set of optional name-value pairs that define custom source + properties to return with each finding that is generated by the + custom module. The custom source properties that are defined here + are included in the finding JSON under ``sourceProperties``. + + Attributes: + properties (MutableSequence[google.cloud.securitycenter_v1.types.CustomConfig.CustomOutputSpec.Property]): + A list of custom output properties to add to + the finding. + """ + + class Property(proto.Message): + r"""An individual name-value pair that defines a custom source + property. + + Attributes: + name (str): + Name of the property for the custom output. + value_expression (google.type.expr_pb2.Expr): + The CEL expression for the custom output. A + resource property can be specified to return the + value of the property or a text string enclosed + in quotation marks. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value_expression: expr_pb2.Expr = proto.Field( + proto.MESSAGE, + number=2, + message=expr_pb2.Expr, + ) + + properties: MutableSequence['CustomConfig.CustomOutputSpec.Property'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='CustomConfig.CustomOutputSpec.Property', + ) + + class ResourceSelector(proto.Message): + r"""Resource for selecting resource type. + + Attributes: + resource_types (MutableSequence[str]): + The resource types to run the detector on. + """ + + resource_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + predicate: expr_pb2.Expr = proto.Field( + proto.MESSAGE, + number=1, + message=expr_pb2.Expr, + ) + custom_output: CustomOutputSpec = proto.Field( + proto.MESSAGE, + number=2, + message=CustomOutputSpec, + ) + resource_selector: ResourceSelector = proto.Field( + proto.MESSAGE, + number=3, + message=ResourceSelector, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=4, + enum=Severity, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + recommendation: str = proto.Field( + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.py new file mode 100644 index 000000000000..654cd7d75826 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'SecurityHealthAnalyticsCustomModule', + }, +) + + +class SecurityHealthAnalyticsCustomModule(proto.Message): + r"""Represents an instance of a Security Health Analytics custom + module, including its full module name, display name, enablement + state, and last updated time. You can create a custom module at + the organization, folder, or project level. Custom modules that + you create at the organization or folder level are inherited by + the child folders and projects. + + Attributes: + name (str): + Immutable. The resource name of the custom + module. Its format is + "organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}", + or + "folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}", + or + "projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}" + + The id {customModule} is server-generated and is + not user settable. It will be a numeric id + containing 1-20 digits. + display_name (str): + The display name of the Security Health + Analytics custom module. This display name + becomes the finding category for all findings + that are returned by this custom module. The + display name must be between 1 and 128 + characters, start with a lowercase letter, and + contain alphanumeric characters or underscores + only. + enablement_state (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule.EnablementState): + The enablement state of the custom module. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the custom + module was last updated. + last_editor (str): + Output only. The editor that last updated the + custom module. + ancestor_module (str): + Output only. If empty, indicates that the custom module was + created in the organization, folder, or project in which you + are viewing the custom module. Otherwise, + ``ancestor_module`` specifies the organization or folder + from which the custom module is inherited. + custom_config (google.cloud.securitycenter_v1.types.CustomConfig): + The user specified custom configuration for + the module. + """ + class EnablementState(proto.Enum): + r"""Possible enablement states of a custom module. + + Values: + ENABLEMENT_STATE_UNSPECIFIED (0): + Unspecified enablement state. + ENABLED (1): + The module is enabled at the given CRM + resource. + DISABLED (2): + The module is disabled at the given CRM + resource. + INHERITED (3): + State is inherited from an ancestor module. + The module will either be effectively ENABLED or + DISABLED based on its closest non-inherited + ancestor module in the CRM hierarchy. + """ + ENABLEMENT_STATE_UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + INHERITED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + enablement_state: EnablementState = proto.Field( + proto.ENUM, + number=4, + enum=EnablementState, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + last_editor: str = proto.Field( + proto.STRING, + number=6, + ) + ancestor_module: str = proto.Field( + proto.STRING, + number=7, + ) + custom_config: security_health_analytics_custom_config.CustomConfig = proto.Field( + proto.MESSAGE, + number=8, + message=security_health_analytics_custom_config.CustomConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.py new file mode 100644 index 000000000000..4c141c1aa108 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'SecurityMarks', + }, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". + marks (MutableMapping[str, str]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + canonical_name (str): + The canonical name of the marks. Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "folders/{folder_id}/assets/{asset_id}/securityMarks" + "projects/{project_number}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + marks: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.py new file mode 100644 index 000000000000..c929af3ef59a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'SecurityPosture', + }, +) + + +class SecurityPosture(proto.Message): + r"""Represents a posture that is deployed on Google Cloud by the + Security Command Center Posture Management service. A posture + contains one or more policy sets. A policy set is a group of + policies that enforce a set of security rules on Google Cloud. + + Attributes: + name (str): + Name of the posture, for example, ``CIS-Posture``. + revision_id (str): + The version of the posture, for example, ``c7cfa2a8``. + posture_deployment_resource (str): + The project, folder, or organization on which the posture is + deployed, for example, ``projects/{project_number}``. + posture_deployment (str): + The name of the posture deployment, for example, + ``organizations/{org_id}/posturedeployments/{posture_deployment_id}``. + changed_policy (str): + The name of the updated policy, for example, + ``projects/{project_id}/policies/{constraint_name}``. + policy_set (str): + The name of the updated policyset, for example, + ``cis-policyset``. + policy (str): + The ID of the updated policy, for example, + ``compute-policy-1``. + policy_drift_details (MutableSequence[google.cloud.securitycenter_v1.types.SecurityPosture.PolicyDriftDetails]): + The details about a change in an updated + policy that violates the deployed posture. + """ + + class PolicyDriftDetails(proto.Message): + r"""The policy field that violates the deployed posture and its + expected and detected values. + + Attributes: + field (str): + The name of the updated field, for example + constraint.implementation.policy_rules[0].enforce + expected_value (str): + The value of this field that was configured in a posture, + for example, ``true`` or + ``allowed_values={"projects/29831892"}``. + detected_value (str): + The detected value that violates the deployed posture, for + example, ``false`` or + ``allowed_values={"projects/22831892"}``. + """ + + field: str = proto.Field( + proto.STRING, + number=1, + ) + expected_value: str = proto.Field( + proto.STRING, + number=2, + ) + detected_value: str = proto.Field( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + ) + posture_deployment_resource: str = proto.Field( + proto.STRING, + number=3, + ) + posture_deployment: str = proto.Field( + proto.STRING, + number=4, + ) + changed_policy: str = proto.Field( + proto.STRING, + number=5, + ) + policy_set: str = proto.Field( + proto.STRING, + number=6, + ) + policy: str = proto.Field( + proto.STRING, + number=7, + ) + policy_drift_details: MutableSequence[PolicyDriftDetails] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=PolicyDriftDetails, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py new file mode 100644 index 000000000000..f249dad54176 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py @@ -0,0 +1,3519 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1.types import asset as gcs_asset +from google.cloud.securitycenter_v1.types import attack_path +from google.cloud.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import folder +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import resource as gcs_resource +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import valued_resource +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'BulkMuteFindingsRequest', + 'BulkMuteFindingsResponse', + 'CreateFindingRequest', + 'CreateMuteConfigRequest', + 'CreateResourceValueConfigRequest', + 'BatchCreateResourceValueConfigsRequest', + 'BatchCreateResourceValueConfigsResponse', + 'DeleteResourceValueConfigRequest', + 'GetResourceValueConfigRequest', + 'ListResourceValueConfigsRequest', + 'ListResourceValueConfigsResponse', + 'UpdateResourceValueConfigRequest', + 'CreateNotificationConfigRequest', + 'CreateSecurityHealthAnalyticsCustomModuleRequest', + 'CreateSourceRequest', + 'DeleteMuteConfigRequest', + 'DeleteNotificationConfigRequest', + 'DeleteSecurityHealthAnalyticsCustomModuleRequest', + 'GetBigQueryExportRequest', + 'GetMuteConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', + 'GetSecurityHealthAnalyticsCustomModuleRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', + 'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', + 'ListValuedResourcesRequest', + 'ListValuedResourcesResponse', + 'ListAttackPathsRequest', + 'ListAttackPathsResponse', + 'GetSimulationRequest', + 'GetValuedResourceRequest', + 'ListMuteConfigsRequest', + 'ListMuteConfigsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', + 'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', + 'ListSecurityHealthAnalyticsCustomModulesRequest', + 'ListSecurityHealthAnalyticsCustomModulesResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'SetFindingStateRequest', + 'SetMuteRequest', + 'RunAssetDiscoveryRequest', + 'SimulateSecurityHealthAnalyticsCustomModuleRequest', + 'SimulateSecurityHealthAnalyticsCustomModuleResponse', + 'UpdateExternalSystemRequest', + 'UpdateFindingRequest', + 'UpdateMuteConfigRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityHealthAnalyticsCustomModuleRequest', + 'UpdateSourceRequest', + 'UpdateSecurityMarksRequest', + 'CreateBigQueryExportRequest', + 'UpdateBigQueryExportRequest', + 'ListBigQueryExportsRequest', + 'ListBigQueryExportsResponse', + 'DeleteBigQueryExportRequest', + 'CreateEventThreatDetectionCustomModuleRequest', + 'ValidateEventThreatDetectionCustomModuleRequest', + 'ValidateEventThreatDetectionCustomModuleResponse', + 'DeleteEventThreatDetectionCustomModuleRequest', + 'GetEventThreatDetectionCustomModuleRequest', + 'ListDescendantEventThreatDetectionCustomModulesRequest', + 'ListDescendantEventThreatDetectionCustomModulesResponse', + 'ListEventThreatDetectionCustomModulesRequest', + 'ListEventThreatDetectionCustomModulesResponse', + 'UpdateEventThreatDetectionCustomModuleRequest', + 'GetEffectiveEventThreatDetectionCustomModuleRequest', + 'ListEffectiveEventThreatDetectionCustomModulesRequest', + 'ListEffectiveEventThreatDetectionCustomModulesResponse', + }, +) + + +class BulkMuteFindingsRequest(proto.Message): + r"""Request message for bulk findings update. + + Note: + + 1. If multiple bulk update requests match the same resource, the + order in which they get executed is not defined. + 2. Once a bulk operation is started, there is no way to stop it. + + Attributes: + parent (str): + Required. The parent, at which bulk action needs to be + applied. Its format is ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + filter (str): + Expression that identifies findings that should be updated. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + mute_annotation (str): + This can be a mute configuration name or any + identifier for mute/unmute of findings based on + the filter. + mute_state (google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest.MuteState): + Optional. All findings matching the given filter will have + their mute state set to this value. The default value is + ``MUTED``. Setting this to ``UNDEFINED`` will clear the mute + state on all matching findings. + """ + class MuteState(proto.Enum): + r"""The mute state. + + Values: + MUTE_STATE_UNSPECIFIED (0): + Unused. + MUTED (1): + Matching findings will be muted (default). + UNDEFINED (2): + Matching findings will have their mute state + cleared. + """ + MUTE_STATE_UNSPECIFIED = 0 + MUTED = 1 + UNDEFINED = 2 + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + mute_annotation: str = proto.Field( + proto.STRING, + number=3, + ) + mute_state: MuteState = proto.Field( + proto.ENUM, + number=4, + enum=MuteState, + ) + + +class BulkMuteFindingsResponse(proto.Message): + r"""The response to a BulkMute request. Contains the LRO + information. + + """ + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + + Attributes: + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + ``organizations/[organization_id]/sources/[source_id]``. + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + alphanumeric and less than or equal to 32 + characters and greater than 0 characters in + length. + finding (google.cloud.securitycenter_v1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + finding_id: str = proto.Field( + proto.STRING, + number=2, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_finding.Finding, + ) + + +class CreateMuteConfigRequest(proto.Message): + r"""Request message for creating a mute config. + + Attributes: + parent (str): + Required. Resource name of the new mute configs's parent. + Its format is ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + mute_config (google.cloud.securitycenter_v1.types.MuteConfig): + Required. The mute config being created. + mute_config_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must consist + of only lowercase letters, numbers, and hyphens, + must start with a letter, must end with either a + letter or a number, and must be 63 characters or + less. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + mute_config: gcs_mute_config.MuteConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_mute_config.MuteConfig, + ) + mute_config_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateResourceValueConfigRequest(proto.Message): + r"""Request message to create single resource value config + + Attributes: + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. + resource_value_config (google.cloud.securitycenter_v1.types.ResourceValueConfig): + Required. The resource value config being + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_resource_value_config.ResourceValueConfig, + ) + + +class BatchCreateResourceValueConfigsRequest(proto.Message): + r"""Request message to create multiple resource value configs + + Attributes: + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. The parent field + in the CreateResourceValueConfigRequest messages + must either be empty or match this field. + requests (MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]): + Required. The resource value configs to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence['CreateResourceValueConfigRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='CreateResourceValueConfigRequest', + ) + + +class BatchCreateResourceValueConfigsResponse(proto.Message): + r"""Response message for BatchCreateResourceValueConfigs + + Attributes: + resource_value_configs (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfig]): + The resource value configs created + """ + + resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + + +class DeleteResourceValueConfigRequest(proto.Message): + r"""Request message to delete resource value config + + Attributes: + name (str): + Required. Name of the ResourceValueConfig to + delete + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetResourceValueConfigRequest(proto.Message): + r"""Request message to get resource value config + + Attributes: + name (str): + Required. Name of the resource value config to retrieve. Its + format is + ``organizations/{organization}/resourceValueConfigs/{config_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListResourceValueConfigsRequest(proto.Message): + r"""Request message to list resource value configs of a parent + + Attributes: + parent (str): + Required. The parent, which owns the collection of resource + value configs. Its format is + ``organizations/[organization_id]`` + page_size (int): + The number of results to return. The service + may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous + ``ListResourceValueConfigs`` call. Provide this to retrieve + the subsequent page. + + When paginating, all other parameters provided to + ``ListResourceValueConfigs`` must match the call that + provided the page token. + + page_size can be specified, and the new page_size 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, + ) + + +class ListResourceValueConfigsResponse(proto.Message): + r"""Response message to list resource value configs + + Attributes: + resource_value_configs (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfig]): + The resource value configs from the specified + parent. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is empty, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateResourceValueConfigRequest(proto.Message): + r"""Request message to update resource value config + + Attributes: + resource_value_config (google.cloud.securitycenter_v1.types.ResourceValueConfig): + Required. The resource value config being + updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class CreateNotificationConfigRequest(proto.Message): + r"""Request message for creating a notification config. + + Attributes: + parent (str): + Required. Resource name of the new notification config's + parent. Its format is ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + config_id (str): + Required. + Unique identifier provided by the client within + the parent scope. It must be between 1 and 128 + characters and contain alphanumeric characters, + underscores, or hyphens only. + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): + Required. The notification config being + created. The name and the service account will + be ignored as they are both output only fields + on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + config_id: str = proto.Field( + proto.STRING, + number=2, + ) + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_notification_config.NotificationConfig, + ) + + +class CreateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): + r"""Request message for creating Security Health Analytics custom + modules. + + Attributes: + parent (str): + Required. Resource name of the new custom module's parent. + Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): + Required. SecurityHealthAnalytics custom + module to create. The provided name is ignored + and reset with provided parent information and + server-generated ID. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + security_health_analytics_custom_module: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be ``organizations/[organization_id]``. + source (google.cloud.securitycenter_v1.types.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_source.Source, + ) + + +class DeleteMuteConfigRequest(proto.Message): + r"""Request message for deleting a mute config. + + Attributes: + name (str): + Required. Name of the mute config to delete. Its format is + ``organizations/{organization}/muteConfigs/{config_id}``, + ``folders/{folder}/muteConfigs/{config_id}``, + ``projects/{project}/muteConfigs/{config_id}``, + ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, + ``folders/{folder}/locations/global/muteConfigs/{config_id}``, + or + ``projects/{project}/locations/global/muteConfigs/{config_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteNotificationConfigRequest(proto.Message): + r"""Request message for deleting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to delete. Its + format is + ``organizations/[organization_id]/notificationConfigs/[config_id]``, + ``folders/[folder_id]/notificationConfigs/[config_id]``, or + ``projects/[project_id]/notificationConfigs/[config_id]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteSecurityHealthAnalyticsCustomModuleRequest(proto.Message): + r"""Request message for deleting Security Health Analytics custom + modules. + + Attributes: + name (str): + Required. Name of the custom module to delete. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetBigQueryExportRequest(proto.Message): + r"""Request message for retrieving a BigQuery export. + + Attributes: + name (str): + Required. Name of the BigQuery export to retrieve. Its + format is + ``organizations/{organization}/bigQueryExports/{export_id}``, + ``folders/{folder}/bigQueryExports/{export_id}``, or + ``projects/{project}/bigQueryExports/{export_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetMuteConfigRequest(proto.Message): + r"""Request message for retrieving a mute config. + + Attributes: + name (str): + Required. Name of the mute config to retrieve. Its format is + ``organizations/{organization}/muteConfigs/{config_id}``, + ``folders/{folder}/muteConfigs/{config_id}``, + ``projects/{project}/muteConfigs/{config_id}``, + ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, + ``folders/{folder}/locations/global/muteConfigs/{config_id}``, + or + ``projects/{project}/locations/global/muteConfigs/{config_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetNotificationConfigRequest(proto.Message): + r"""Request message for getting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to get. Its format + is + ``organizations/[organization_id]/notificationConfigs/[config_id]``, + ``folders/[folder_id]/notificationConfigs/[config_id]``, or + ``projects/[project_id]/notificationConfigs/[config_id]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetOrganizationSettingsRequest(proto.Message): + r"""Request message for getting organization settings. + + Attributes: + name (str): + Required. Name of the organization to get organization + settings for. Its format is + ``organizations/[organization_id]/organizationSettings``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(proto.Message): + r"""Request message for getting effective Security Health + Analytics custom modules. + + Attributes: + name (str): + Required. Name of the effective custom module to get. Its + format is + ``organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSecurityHealthAnalyticsCustomModuleRequest(proto.Message): + r"""Request message for getting Security Health Analytics custom + modules. + + Attributes: + name (str): + Required. Name of the custom module to get. Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, + ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, + or + ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is ``organizations/[organization_id]/source/[source_id]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GroupAssetsRequest(proto.Message): + r"""Request message for grouping by assets. + + Attributes: + parent (str): + Required. The name of the parent to group the assets by. Its + format is ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, + ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is + not set: + + - security_center_properties.resource_project + - security_center_properties.resource_project_display_name + - security_center_properties.resource_type + - security_center_properties.resource_parent + - security_center_properties.resource_parent_display_name + + The following fields are supported when compare_duration is + set: + + - security_center_properties.resource_type + - security_center_properties.resource_project_display_name + - security_center_properties.resource_parent_display_name + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the GroupResult's + "state_change" property is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at + reference_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and reference_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupAssetsResponse``; + indicates that this is a continuation of a prior + ``GroupAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupAssetsResponse(proto.Message): + r"""Response message for grouping by assets. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + + Attributes: + parent (str): + Required. Name of the source to groupBy. Its format is + ``organizations/[organization_id]/sources/[source_id]``, + ``folders/[folder_id]/sources/[source_id]``, or + ``projects/[project_id]/sources/[source_id]``. To groupBy + across all sources provide a source_id of ``-``. For + example: + ``organizations/{organization_id}/sources/-, folders/{folder_id}/sources/-``, + or ``projects/{project_id}/sources/-`` + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - severity: ``=``, ``:`` + + - workflow_state: ``=``, ``:`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based + on a property existing: + ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + + - resource: + + - resource.name: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping (including ``state_change``). The string value + should follow SQL syntax: comma separated list of fields. + For example: "parent,resource_name". + + The following fields are supported when compare_duration is + set: + + - state_change + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the GroupResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=struct_pb2.Value, + ) + count: int = proto.Field( + proto.INT64, + number=2, + ) + + +class ListDescendantSecurityHealthAnalyticsCustomModulesRequest(proto.Message): + r"""Request message for listing descendant Security Health + Analytics custom modules. + + Attributes: + parent (str): + Required. Name of parent to list descendant custom modules. + Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + page_token (str): + The value returned by the last call + indicating a continuation + """ + + 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 ListDescendantSecurityHealthAnalyticsCustomModulesResponse(proto.Message): + r"""Response message for listing descendant Security Health + Analytics custom modules. + + Attributes: + security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule]): + Custom modules belonging to the requested + parent and its descendants. + next_page_token (str): + If not empty, indicates that there may be + more custom modules to be returned. + """ + + @property + def raw_page(self): + return self + + security_health_analytics_custom_modules: MutableSequence[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListValuedResourcesRequest(proto.Message): + r"""Request message for listing the valued resources for a given + simulation. + + Attributes: + parent (str): + Required. Name of parent to list valued resources. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + filter (str): + The filter expression that filters the valued resources in + the response. Supported fields: + + - ``resource_value`` supports = + - ``resource_type`` supports = + page_token (str): + The value returned by the last + ``ListValuedResourcesResponse``; indicates that this is a + continuation of a prior ``ListValuedResources`` call, and + that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + order_by (str): + Optional. The fields by which to order the valued resources + response. + + Supported fields: + + - ``exposed_score`` + + - ``resource_value`` + + - ``resource_type`` + + - ``resource`` + + - ``display_name`` + + Values should be a comma separated list of fields. For + example: ``exposed_score,resource_value``. + + The default sorting order is descending. To specify + ascending or descending order for a field, append a ``ASC`` + or a ``DESC`` suffix, respectively; for example: + ``exposed_score DESC``. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListValuedResourcesResponse(proto.Message): + r"""Response message for listing the valued resources for a given + simulation. + + Attributes: + valued_resources (MutableSequence[google.cloud.securitycenter_v1.types.ValuedResource]): + The valued resources that the attack path + simulation identified. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The estimated total number of results + matching the query. + """ + + @property + def raw_page(self): + return self + + valued_resources: MutableSequence[valued_resource.ValuedResource] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=valued_resource.ValuedResource, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListAttackPathsRequest(proto.Message): + r"""Request message for listing the attack paths for a given + simulation or valued resource. + + Attributes: + parent (str): + Required. Name of parent to list attack paths. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + filter (str): + The filter expression that filters the attack path in the + response. Supported fields: + + - ``valued_resources`` supports = + page_token (str): + The value returned by the last ``ListAttackPathsResponse``; + indicates that this is a continuation of a prior + ``ListAttackPaths`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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 ListAttackPathsResponse(proto.Message): + r"""Response message for listing the attack paths for a given + simulation or valued resource. + + Attributes: + attack_paths (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath]): + The attack paths that the attack path + simulation identified. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + attack_paths: MutableSequence[attack_path.AttackPath] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=attack_path.AttackPath, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetSimulationRequest(proto.Message): + r"""Request message for getting simulation. + Simulation name can include "latest" to retrieve the latest + simulation For example, "organizations/123/simulations/latest" + + Attributes: + name (str): + Required. The organization name or simulation name of this + simulation + + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetValuedResourceRequest(proto.Message): + r"""Request message for getting a valued resource. + + Attributes: + name (str): + Required. The name of this valued resource + + Valid format: + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListMuteConfigsRequest(proto.Message): + r"""Request message for listing mute configs at a given scope + e.g. organization, folder or project. + + Attributes: + parent (str): + Required. The parent, which owns the collection of mute + configs. Its format is ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + page_size (int): + The maximum number of configs to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListMuteConfigs`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListMuteConfigs`` 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 ListMuteConfigsResponse(proto.Message): + r"""Response message for listing mute configs. + + Attributes: + mute_configs (MutableSequence[google.cloud.securitycenter_v1.types.MuteConfig]): + The mute configs from the specified parent. + 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 + + mute_configs: MutableSequence[gcs_mute_config.MuteConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_mute_config.MuteConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListNotificationConfigsRequest(proto.Message): + r"""Request message for listing notification configs. + + Attributes: + parent (str): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]", "folders/[folder_id]", or + "projects/[project_id]". + page_token (str): + The value returned by the last + ``ListNotificationConfigsResponse``; indicates that this is + a continuation of a prior ``ListNotificationConfigs`` call, + and that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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 ListNotificationConfigsResponse(proto.Message): + r"""Response message for listing notification configs. + + Attributes: + notification_configs (MutableSequence[google.cloud.securitycenter_v1.types.NotificationConfig]): + Notification configs belonging to the + requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + notification_configs: MutableSequence[gcs_notification_config.NotificationConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(proto.Message): + r"""Request message for listing effective Security Health + Analytics custom modules. + + Attributes: + parent (str): + Required. Name of parent to list effective custom modules. + Its format is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + page_token (str): + The value returned by the last call + indicating a continuation + """ + + 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 ListEffectiveSecurityHealthAnalyticsCustomModulesResponse(proto.Message): + r"""Response message for listing effective Security Health + Analytics custom modules. + + Attributes: + effective_security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule]): + Effective custom modules belonging to the + requested parent. + next_page_token (str): + If not empty, indicates that there may be + more effective custom modules to be returned. + """ + + @property + def raw_page(self): + return self + + effective_security_health_analytics_custom_modules: MutableSequence[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSecurityHealthAnalyticsCustomModulesRequest(proto.Message): + r"""Request message for listing Security Health Analytics custom + modules. + + Attributes: + parent (str): + Required. Name of parent to list custom modules. Its format + is + ``organizations/{organization}/securityHealthAnalyticsSettings``, + ``folders/{folder}/securityHealthAnalyticsSettings``, or + ``projects/{project}/securityHealthAnalyticsSettings`` + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + page_token (str): + The value returned by the last call + indicating a continuation + """ + + 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 ListSecurityHealthAnalyticsCustomModulesResponse(proto.Message): + r"""Response message for listing Security Health Analytics custom + modules. + + Attributes: + security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule]): + Custom modules belonging to the requested + parent. + next_page_token (str): + If not empty, indicates that there may be + more custom modules to be returned. + """ + + @property + def raw_page(self): + return self + + security_health_analytics_custom_modules: MutableSequence[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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=7, + ) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v1.types.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAssetsRequest(proto.Message): + r"""Request message for listing assets. + + Attributes: + parent (str): + Required. The name of the parent resource that contains the + assets. The value that you can specify on parent depends on + the method in which you specify parent. You can specify one + of the following values: + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following are the allowed field and operator + combinations: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, + ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,resource_properties.a_property". + Redundant space characters in the syntax are insignificant. + "name desc,resource_properties.a_property" and " name desc , + resource_properties.a_property " are equivalent. + + The following fields are supported: name update_time + resource_properties security_marks.marks + security_center_properties.resource_name + security_center_properties.resource_display_name + security_center_properties.resource_parent + security_center_properties.resource_parent_display_name + security_center_properties.resource_project + security_center_properties.resource_project_display_name + security_center_properties.resource_type + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListAssetsResult's + "state_change" attribute is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at read_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at read_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the ListAssetsResult + fields to be listed in the response. + An empty field mask will list all fields. + page_token (str): + The value returned by the last ``ListAssetsResponse``; + indicates that this is a continuation of a prior + ``ListAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=9, + ) + + +class ListAssetsResponse(proto.Message): + r"""Response message for listing assets. + + Attributes: + list_assets_results (MutableSequence[google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of assets matching the + query. + """ + + class ListAssetsResult(proto.Message): + r"""Result containing the Asset and its State. + + Attributes: + asset (google.cloud.securitycenter_v1.types.Asset): + Asset matching the search request. + state_change (google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult.StateChange): + State change of the asset between the points + in time. + """ + class StateChange(proto.Enum): + r"""The change in state of the asset. + + When querying across two points in time this describes the change + between the two points: ADDED, REMOVED, or ACTIVE. If there was no + compare_duration supplied in the request the state change will be: + UNUSED + + Values: + UNUSED (0): + State change is unused, this is the canonical + default for this enum. + ADDED (1): + Asset was added between the points in time. + REMOVED (2): + Asset was removed between the points in time. + ACTIVE (3): + Asset was present at both point(s) in time. + """ + UNUSED = 0 + ADDED = 1 + REMOVED = 2 + ACTIVE = 3 + + asset: gcs_asset.Asset = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_asset.Asset, + ) + state_change: 'ListAssetsResponse.ListAssetsResult.StateChange' = proto.Field( + proto.ENUM, + number=2, + enum='ListAssetsResponse.ListAssetsResult.StateChange', + ) + + @property + def raw_page(self): + return self + + list_assets_results: MutableSequence[ListAssetsResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListAssetsResult, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + + Attributes: + parent (str): + Required. Name of the source the findings belong to. Its + format is + ``organizations/[organization_id]/sources/[source_id]``, + ``folders/[folder_id]/sources/[source_id]``, or + ``projects/[project_id]/sources/[source_id]``. To list + across all sources provide a source_id of ``-``. For + example: ``organizations/{organization_id}/sources/-``, + ``folders/{folder_id}/sources/-`` or + ``projects/{projects_id}/sources/-`` + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - severity: ``=``, ``:`` + + - workflow_state: ``=``, ``:`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based + on a property existing: + ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + + - resource: + + - resource.name: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + - resource.folders.resource_folder: ``=``, ``:`` + - resource.display_name: ``=``, ``:`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,source_properties.a_property". Redundant + space characters in the syntax are insignificant. "name + desc,source_properties.a_property" and " name desc , + source_properties.a_property " are equivalent. + + The following fields are supported: name parent state + category resource_name event_time source_properties + security_marks.marks + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListFindingsResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added in any state during + the compare_duration period of time that precedes the + read_time. This is the time between (read_time - + compare_duration) and read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the Finding fields to + be listed in the response. An empty field mask + will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=9, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + + Attributes: + list_findings_results (MutableSequence[google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult]): + Findings matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + class ListFindingsResult(proto.Message): + r"""Result containing the Finding and its StateChange. + + Attributes: + finding (google.cloud.securitycenter_v1.types.Finding): + Finding matching the search request. + state_change (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.StateChange): + State change of the finding between the + points in time. + resource (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.Resource): + Output only. Resource that is associated with + this finding. + """ + class StateChange(proto.Enum): + r"""The change in state of the finding. + + When querying across two points in time this describes the change in + the finding between the two points: CHANGED, UNCHANGED, ADDED, or + REMOVED. Findings can not be deleted, so REMOVED implies that the + finding at timestamp does not match the filter specified, but it did + at timestamp - compare_duration. If there was no compare_duration + supplied in the request the state change will be: UNUSED + + Values: + UNUSED (0): + State change is unused, this is the canonical + default for this enum. + CHANGED (1): + The finding has changed state in some way + between the points in time and existed at both + points. + UNCHANGED (2): + The finding has not changed state between the + points in time and existed at both points. + ADDED (3): + The finding was created between the points in + time. + REMOVED (4): + The finding at timestamp does not match the filter + specified, but it did at timestamp - compare_duration. + """ + UNUSED = 0 + CHANGED = 1 + UNCHANGED = 2 + ADDED = 3 + REMOVED = 4 + + class Resource(proto.Message): + r"""Information related to the Google Cloud resource that is + associated with this finding. + + 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): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + display_name (str): + The human readable name of the resource. + type_ (str): + The full resource type of the resource. + project_name (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The project ID that the resource belongs to. + parent_name (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (MutableSequence[google.cloud.securitycenter_v1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. + cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): + Indicates which cloud provider the finding is + from. + organization (str): + Indicates which organization / tenant the + finding is for. + service (str): + The service or resource provider associated + with the resource. + location (str): + The region or location of the service (if + applicable). + aws_metadata (google.cloud.securitycenter_v1.types.AwsMetadata): + The AWS metadata associated with the finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + azure_metadata (google.cloud.securitycenter_v1.types.AzureMetadata): + The Azure metadata associated with the + finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + resource_path (google.cloud.securitycenter_v1.types.ResourcePath): + Provides the path to the resource within the + resource hierarchy. + resource_path_string (str): + A string representation of the resource path. For Google + Cloud, it has the format of + ``org/{organization_id}/folder/{folder_id}/folder/{folder_id}/project/{project_id}`` + where there can be any number of folders. For AWS, it has + the format of + ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` + where there can be any number of organizational units. For + Azure, it has the format of + ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` + where there can be any number of management groups. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=8, + ) + type_: str = proto.Field( + proto.STRING, + number=6, + ) + project_name: str = proto.Field( + proto.STRING, + number=2, + ) + project_display_name: str = proto.Field( + proto.STRING, + number=3, + ) + parent_name: str = proto.Field( + proto.STRING, + number=4, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=5, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=folder.Folder, + ) + cloud_provider: gcs_resource.CloudProvider = proto.Field( + proto.ENUM, + number=9, + enum=gcs_resource.CloudProvider, + ) + organization: str = proto.Field( + proto.STRING, + number=10, + ) + service: str = proto.Field( + proto.STRING, + number=11, + ) + location: str = proto.Field( + proto.STRING, + number=12, + ) + aws_metadata: gcs_resource.AwsMetadata = proto.Field( + proto.MESSAGE, + number=16, + oneof='cloud_provider_metadata', + message=gcs_resource.AwsMetadata, + ) + azure_metadata: gcs_resource.AzureMetadata = proto.Field( + proto.MESSAGE, + number=17, + oneof='cloud_provider_metadata', + message=gcs_resource.AzureMetadata, + ) + resource_path: gcs_resource.ResourcePath = proto.Field( + proto.MESSAGE, + number=18, + message=gcs_resource.ResourcePath, + ) + resource_path_string: str = proto.Field( + proto.STRING, + number=19, + ) + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + state_change: 'ListFindingsResponse.ListFindingsResult.StateChange' = proto.Field( + proto.ENUM, + number=2, + enum='ListFindingsResponse.ListFindingsResult.StateChange', + ) + resource: 'ListFindingsResponse.ListFindingsResult.Resource' = proto.Field( + proto.MESSAGE, + number=3, + message='ListFindingsResponse.ListFindingsResult.Resource', + ) + + @property + def raw_page(self): + return self + + list_findings_results: MutableSequence[ListFindingsResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListFindingsResult, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + + Attributes: + name (str): + Required. The `relative resource + name `__ + of the finding. Example: + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, + ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. + state (google.cloud.securitycenter_v1.types.Finding.State): + Required. The desired State of the finding. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the updated state + takes effect. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: gcs_finding.Finding.State = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.State, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class SetMuteRequest(proto.Message): + r"""Request message for updating a finding's mute status. + + Attributes: + name (str): + Required. The `relative resource + name `__ + of the finding. Example: + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, + ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. + mute (google.cloud.securitycenter_v1.types.Finding.Mute): + Required. The desired state of the Mute. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + mute: gcs_finding.Finding.Mute = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.Mute, + ) + + +class RunAssetDiscoveryRequest(proto.Message): + r"""Request message for running asset discovery for an + organization. + + Attributes: + parent (str): + Required. Name of the organization to run asset discovery + for. Its format is ``organizations/[organization_id]``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class SimulateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): + r"""Request message to simulate a CustomConfig against a given + test resource. Maximum size of the request is 4 MB by default. + + Attributes: + parent (str): + Required. The relative resource name of the organization, + project, or folder. For more information about relative + resource names, see `Relative Resource + Name `__ + Example: ``organizations/{organization_id}`` + custom_config (google.cloud.securitycenter_v1.types.CustomConfig): + Required. The custom configuration that you + need to test. + resource (google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource): + Required. Resource data to simulate custom + module against. + """ + + class SimulatedResource(proto.Message): + r"""Manually constructed resource name. If the custom module evaluates + against only the resource data, you can omit the ``iam_policy_data`` + field. If it evaluates only the ``iam_policy_data`` field, you can + omit the resource data. + + Attributes: + resource_type (str): + Required. The type of the resource, for example, + ``compute.googleapis.com/Disk``. + resource_data (google.protobuf.struct_pb2.Struct): + Optional. A representation of the Google + Cloud resource. Should match the Google Cloud + resource JSON format. + iam_policy_data (google.iam.v1.policy_pb2.Policy): + Optional. A representation of the IAM policy. + """ + + resource_type: str = proto.Field( + proto.STRING, + number=1, + ) + resource_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + iam_policy_data: policy_pb2.Policy = proto.Field( + proto.MESSAGE, + number=3, + message=policy_pb2.Policy, + ) + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + custom_config: security_health_analytics_custom_config.CustomConfig = proto.Field( + proto.MESSAGE, + number=2, + message=security_health_analytics_custom_config.CustomConfig, + ) + resource: SimulatedResource = proto.Field( + proto.MESSAGE, + number=3, + message=SimulatedResource, + ) + + +class SimulateSecurityHealthAnalyticsCustomModuleResponse(proto.Message): + r"""Response message for simulating a + ``SecurityHealthAnalyticsCustomModule`` against a given resource. + + Attributes: + result (google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse.SimulatedResult): + Result for test case in the corresponding + request. + """ + + class SimulatedResult(proto.Message): + r"""Possible test 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: + finding (google.cloud.securitycenter_v1.types.Finding): + Finding that would be published for the test + case, if a violation is detected. + + This field is a member of `oneof`_ ``result``. + no_violation (google.protobuf.empty_pb2.Empty): + Indicates that the test case does not trigger + any violation. + + This field is a member of `oneof`_ ``result``. + error (google.rpc.status_pb2.Status): + Error encountered during the test. + + This field is a member of `oneof`_ ``result``. + """ + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + oneof='result', + message=gcs_finding.Finding, + ) + no_violation: empty_pb2.Empty = proto.Field( + proto.MESSAGE, + number=2, + oneof='result', + message=empty_pb2.Empty, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + oneof='result', + message=status_pb2.Status, + ) + + result: SimulatedResult = proto.Field( + proto.MESSAGE, + number=1, + message=SimulatedResult, + ) + + +class UpdateExternalSystemRequest(proto.Message): + r"""Request message for updating a ExternalSystem resource. + + Attributes: + external_system (google.cloud.securitycenter_v1.types.ExternalSystem): + Required. The external system resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + external system resource. + If empty all mutable fields will be updated. + """ + + external_system: gcs_external_system.ExternalSystem = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_external_system.ExternalSystem, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + + Attributes: + finding (google.cloud.securitycenter_v1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must be alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing source_properties. + Individual source_properties can be added/updated by using + "source_properties." in the field mask. + """ + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateMuteConfigRequest(proto.Message): + r"""Request message for updating a mute config. + + Attributes: + mute_config (google.cloud.securitycenter_v1.types.MuteConfig): + Required. The mute config being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + mute_config: gcs_mute_config.MuteConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_mute_config.MuteConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateNotificationConfigRequest(proto.Message): + r"""Request message for updating a notification config. + + Attributes: + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): + Required. The notification config to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + notification config. + If empty all mutable fields will be updated. + """ + + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + + Attributes: + organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + settings resource. + If empty all mutable fields will be updated. + """ + + organization_settings: gcs_organization_settings.OrganizationSettings = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_organization_settings.OrganizationSettings, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): + r"""Request message for updating Security Health Analytics custom + modules. + + Attributes: + security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): + Required. The SecurityHealthAnalytics custom + module to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. The only fields that can + be updated are ``enablement_state`` and ``custom_config``. + If empty or set to the wildcard value ``*``, both + ``enablement_state`` and ``custom_config`` are updated. + """ + + security_health_analytics_custom_module: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (google.cloud.securitycenter_v1.types.Source): + Required. The source resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the source + resource. + If empty all mutable fields will be updated. + """ + + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): + Required. The security marks resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If empty + or set to "marks", all marks will be replaced. Individual + marks can be updated using "marks.". + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the updated SecurityMarks + take effect. If not set uses current server + time. Updates will be applied to the + SecurityMarks that are active immediately + preceding this time. Must be earlier or equal to + the server time. + """ + + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_marks.SecurityMarks, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class CreateBigQueryExportRequest(proto.Message): + r"""Request message for creating a BigQuery export. + + Attributes: + parent (str): + Required. The name of the parent resource of the new + BigQuery export. Its format is + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): + Required. The BigQuery export being created. + big_query_export_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must consist + of only lowercase letters, numbers, and hyphens, + must start with a letter, must end with either a + letter or a number, and must be 63 characters or + less. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + big_query_export: bigquery_export.BigQueryExport = proto.Field( + proto.MESSAGE, + number=2, + message=bigquery_export.BigQueryExport, + ) + big_query_export_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateBigQueryExportRequest(proto.Message): + r"""Request message for updating a BigQuery export. + + Attributes: + big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): + Required. The BigQuery export being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + big_query_export: bigquery_export.BigQueryExport = proto.Field( + proto.MESSAGE, + number=1, + message=bigquery_export.BigQueryExport, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListBigQueryExportsRequest(proto.Message): + r"""Request message for listing BigQuery exports at a given scope + e.g. organization, folder or project. + + Attributes: + parent (str): + Required. The parent, which owns the collection of BigQuery + exports. Its format is ``organizations/[organization_id]``, + ``folders/[folder_id]``, ``projects/[project_id]``. + page_size (int): + The maximum number of configs to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous + ``ListBigQueryExports`` call. Provide this to retrieve the + subsequent page. When paginating, all other parameters + provided to ``ListBigQueryExports`` 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 ListBigQueryExportsResponse(proto.Message): + r"""Response message for listing BigQuery exports. + + Attributes: + big_query_exports (MutableSequence[google.cloud.securitycenter_v1.types.BigQueryExport]): + The BigQuery exports from the specified + parent. + 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 + + big_query_exports: MutableSequence[bigquery_export.BigQueryExport] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=bigquery_export.BigQueryExport, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteBigQueryExportRequest(proto.Message): + r"""Request message for deleting a BigQuery export. + + Attributes: + name (str): + Required. The name of the BigQuery export to delete. Its + format is + ``organizations/{organization}/bigQueryExports/{export_id}``, + ``folders/{folder}/bigQueryExports/{export_id}``, or + ``projects/{project}/bigQueryExports/{export_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEventThreatDetectionCustomModuleRequest(proto.Message): + r"""Request to create an Event Threat Detection custom module. + + Attributes: + parent (str): + Required. The new custom module's parent. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): + Required. The module to create. The + event_threat_detection_custom_module.name will be ignored + and server generated. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + event_threat_detection_custom_module: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, + ) + + +class ValidateEventThreatDetectionCustomModuleRequest(proto.Message): + r"""Request to validate an Event Threat Detection custom module. + + Attributes: + parent (str): + Required. Resource name of the parent to validate the Custom + Module under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + raw_text (str): + Required. The raw text of the module's + contents. Used to generate error messages. + type_ (str): + Required. The type of the module (e.g. CONFIGURABLE_BAD_IP). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + raw_text: str = proto.Field( + proto.STRING, + number=2, + ) + type_: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ValidateEventThreatDetectionCustomModuleResponse(proto.Message): + r"""Response to validating an Event Threat Detection custom + module. + + Attributes: + errors (google.cloud.securitycenter_v1.types.CustomModuleValidationErrors): + A list of errors returned by the validator. + If the list is empty, there were no errors. + """ + + errors: event_threat_detection_custom_module_validation_errors.CustomModuleValidationErrors = proto.Field( + proto.MESSAGE, + number=2, + message=event_threat_detection_custom_module_validation_errors.CustomModuleValidationErrors, + ) + + +class DeleteEventThreatDetectionCustomModuleRequest(proto.Message): + r"""Request to delete an Event Threat Detection custom module. + + Attributes: + name (str): + Required. Name of the custom module to delete. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEventThreatDetectionCustomModuleRequest(proto.Message): + r"""Request to get an Event Threat Detection custom module. + + Attributes: + name (str): + Required. Name of the custom module to get. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDescendantEventThreatDetectionCustomModulesRequest(proto.Message): + r"""Request to list current and descendant resident Event Threat + Detection custom modules. + + Attributes: + parent (str): + Required. Name of the parent to list custom modules under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + page_token (str): + A page token, received from a previous + ``ListDescendantEventThreatDetectionCustomModules`` call. + Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListDescendantEventThreatDetectionCustomModules`` must + match the call that provided the page token. + page_size (int): + The maximum number of modules to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + """ + + 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 ListDescendantEventThreatDetectionCustomModulesResponse(proto.Message): + r"""Response for listing current and descendant resident + Event Threat Detection custom modules. + + Attributes: + event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule]): + Custom modules belonging to the requested + parent. + 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 + + event_threat_detection_custom_modules: MutableSequence[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListEventThreatDetectionCustomModulesRequest(proto.Message): + r"""Request to list Event Threat Detection custom modules. + + Attributes: + parent (str): + Required. Name of the parent to list custom modules under. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + page_token (str): + A page token, received from a previous + ``ListEventThreatDetectionCustomModules`` call. Provide this + to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListEventThreatDetectionCustomModules`` must match the + call that provided the page token. + page_size (int): + The maximum number of modules to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + """ + + 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 ListEventThreatDetectionCustomModulesResponse(proto.Message): + r"""Response for listing Event Threat Detection custom modules. + + Attributes: + event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule]): + Custom modules belonging to the requested + parent. + 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 + + event_threat_detection_custom_modules: MutableSequence[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateEventThreatDetectionCustomModuleRequest(proto.Message): + r"""Request to update an Event Threat Detection custom module. + + Attributes: + event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): + Required. The module being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + event_threat_detection_custom_module: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetEffectiveEventThreatDetectionCustomModuleRequest(proto.Message): + r"""Request to get an EffectiveEventThreatDetectionCustomModule. + + Attributes: + name (str): + Required. The resource name of the effective Event Threat + Detection custom module. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEffectiveEventThreatDetectionCustomModulesRequest(proto.Message): + r"""Request to list effective Event Threat Detection custom + modules. + + Attributes: + parent (str): + Required. Name of the parent to list custom modules for. + + Its format is: + + - ``organizations/{organization}/eventThreatDetectionSettings``. + - ``folders/{folder}/eventThreatDetectionSettings``. + - ``projects/{project}/eventThreatDetectionSettings``. + page_token (str): + A page token, received from a previous + ``ListEffectiveEventThreatDetectionCustomModules`` call. + Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListEffectiveEventThreatDetectionCustomModules`` must + match the call that provided the page token. + page_size (int): + The maximum number of modules to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + """ + + 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 ListEffectiveEventThreatDetectionCustomModulesResponse(proto.Message): + r"""Response for listing + EffectiveEventThreatDetectionCustomModules. + + Attributes: + effective_event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule]): + Effective custom modules belonging to the + requested parent. + 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 + + effective_event_threat_detection_custom_modules: MutableSequence[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py new file mode 100644 index 000000000000..941b7452d7e0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1.types import resource +from google.cloud.securitycenter_v1.types import valued_resource +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Simulation', + }, +) + + +class Simulation(proto.Message): + r"""Attack path simulation + + Attributes: + name (str): + Full resource name of the Simulation: + ``organizations/123/simulations/456`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time simulation was created + resource_value_configs_metadata (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfigMetadata]): + Resource value configurations' metadata used + in this simulation. Maximum of 100. + cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): + Indicates which cloud provider was used in + this simulation. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + resource_value_configs_metadata: MutableSequence[valued_resource.ResourceValueConfigMetadata] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=valued_resource.ResourceValueConfigMetadata, + ) + cloud_provider: resource.CloudProvider = proto.Field( + proto.ENUM, + number=4, + enum=resource.CloudProvider, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.py new file mode 100644 index 000000000000..e1c53a7c05a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Source', + }, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, and other tools. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and outdated or + insecure libraries.". + canonical_name (str): + The canonical name of the finding source. It's either + "organizations/{organization_id}/sources/{source_id}", + "folders/{folder_id}/sources/{source_id}", or + "projects/{project_number}/sources/{source_id}", depending + on the closest CRM ancestor of the resource associated with + the finding. + """ + + 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, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=14, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.py new file mode 100644 index 000000000000..77f790f8d5f6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'ToxicCombination', + }, +) + + +class ToxicCombination(proto.Message): + r"""Contains details about a group of security issues that, when + the issues occur together, represent a greater risk than when + the issues occur independently. A group of such issues is + referred to as a toxic combination. + + Attributes: + attack_exposure_score (float): + The `Attack exposure + score `__ + of this toxic combination. The score is a measure of how + much this toxic combination exposes one or more high-value + resources to potential attack. + related_findings (MutableSequence[str]): + List of resource names of findings associated with this + toxic combination. For example, + ``organizations/123/sources/456/findings/789``. + """ + + attack_exposure_score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + related_findings: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.py new file mode 100644 index 000000000000..5d48f6fabfa1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'ValuedResource', + 'ResourceValueConfigMetadata', + }, +) + + +class ValuedResource(proto.Message): + r"""A resource that is determined to have value to a user's + system + + Attributes: + name (str): + Valued resource name, for example, e.g.: + ``organizations/123/simulations/456/valuedResources/789`` + resource (str): + The `full resource + name `__ + of the valued resource. + resource_type (str): + The `resource + type `__ + of the valued resource. + display_name (str): + Human-readable name of the valued resource. + resource_value (google.cloud.securitycenter_v1.types.ValuedResource.ResourceValue): + How valuable this resource is. + exposed_score (float): + Exposed score for this valued resource. A + value of 0 means no exposure was detected + exposure. + resource_value_configs_used (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfigMetadata]): + List of resource value configurations' + metadata used to determine the value of this + resource. Maximum of 100. + """ + class ResourceValue(proto.Enum): + r"""How valuable the resource is. + + Values: + RESOURCE_VALUE_UNSPECIFIED (0): + The resource value isn't specified. + RESOURCE_VALUE_LOW (1): + This is a low-value resource. + RESOURCE_VALUE_MEDIUM (2): + This is a medium-value resource. + RESOURCE_VALUE_HIGH (3): + This is a high-value resource. + """ + RESOURCE_VALUE_UNSPECIFIED = 0 + RESOURCE_VALUE_LOW = 1 + RESOURCE_VALUE_MEDIUM = 2 + RESOURCE_VALUE_HIGH = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource: str = proto.Field( + proto.STRING, + number=2, + ) + resource_type: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + resource_value: ResourceValue = proto.Field( + proto.ENUM, + number=5, + enum=ResourceValue, + ) + exposed_score: float = proto.Field( + proto.DOUBLE, + number=6, + ) + resource_value_configs_used: MutableSequence['ResourceValueConfigMetadata'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='ResourceValueConfigMetadata', + ) + + +class ResourceValueConfigMetadata(proto.Message): + r"""Metadata about a ResourceValueConfig. For example, id and + name. + + Attributes: + name (str): + Resource value config name + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py new file mode 100644 index 000000000000..bfe2bd588b69 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.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. +# +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.securitycenter.v1', + manifest={ + 'Vulnerability', + 'Cve', + 'Reference', + 'Cvssv3', + 'Package', + 'SecurityBulletin', + }, +) + + +class Vulnerability(proto.Message): + r"""Refers to common vulnerability fields e.g. cve, cvss, cwe + etc. + + Attributes: + cve (google.cloud.securitycenter_v1.types.Cve): + CVE stands for Common Vulnerabilities and + Exposures (https://cve.mitre.org/about/) + offending_package (google.cloud.securitycenter_v1.types.Package): + The offending package is relevant to the + finding. + fixed_package (google.cloud.securitycenter_v1.types.Package): + The fixed package is relevant to the finding. + security_bulletin (google.cloud.securitycenter_v1.types.SecurityBulletin): + The security bulletin is relevant to this + finding. + """ + + cve: 'Cve' = proto.Field( + proto.MESSAGE, + number=1, + message='Cve', + ) + offending_package: 'Package' = proto.Field( + proto.MESSAGE, + number=2, + message='Package', + ) + fixed_package: 'Package' = proto.Field( + proto.MESSAGE, + number=3, + message='Package', + ) + security_bulletin: 'SecurityBulletin' = proto.Field( + proto.MESSAGE, + number=4, + message='SecurityBulletin', + ) + + +class Cve(proto.Message): + r"""CVE stands for Common Vulnerabilities and Exposures. Information + from the `CVE + record `__ that + describes this vulnerability. + + Attributes: + id (str): + The unique identifier for the vulnerability. + e.g. CVE-2021-34527 + references (MutableSequence[google.cloud.securitycenter_v1.types.Reference]): + Additional information about the CVE. + e.g. + https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527 + cvssv3 (google.cloud.securitycenter_v1.types.Cvssv3): + Describe Common Vulnerability Scoring System + specified at + https://www.first.org/cvss/v3.1/specification-document + upstream_fix_available (bool): + Whether upstream fix is available for the + CVE. + impact (google.cloud.securitycenter_v1.types.Cve.RiskRating): + The potential impact of the vulnerability if + it was to be exploited. + exploitation_activity (google.cloud.securitycenter_v1.types.Cve.ExploitationActivity): + The exploitation activity of the + vulnerability in the wild. + observed_in_the_wild (bool): + Whether or not the vulnerability has been + observed in the wild. + zero_day (bool): + Whether or not the vulnerability was zero day + when the finding was published. + exploit_release_date (google.protobuf.timestamp_pb2.Timestamp): + Date the first publicly available exploit or + PoC was released. + """ + class RiskRating(proto.Enum): + r"""The possible values of impact of the vulnerability if it was + to be exploited. + + Values: + RISK_RATING_UNSPECIFIED (0): + Invalid or empty value. + LOW (1): + Exploitation would have little to no security + impact. + MEDIUM (2): + Exploitation would enable attackers to + perform activities, or could allow attackers to + have a direct impact, but would require + additional steps. + HIGH (3): + Exploitation would enable attackers to have a + notable direct impact without needing to + overcome any major mitigating factors. + CRITICAL (4): + Exploitation would fundamentally undermine + the security of affected systems, enable actors + to perform significant attacks with minimal + effort, with little to no mitigating factors to + overcome. + """ + RISK_RATING_UNSPECIFIED = 0 + LOW = 1 + MEDIUM = 2 + HIGH = 3 + CRITICAL = 4 + + class ExploitationActivity(proto.Enum): + r"""The possible values of exploitation activity of the + vulnerability in the wild. + + Values: + EXPLOITATION_ACTIVITY_UNSPECIFIED (0): + Invalid or empty value. + WIDE (1): + Exploitation has been reported or confirmed + to widely occur. + CONFIRMED (2): + Limited reported or confirmed exploitation + activities. + AVAILABLE (3): + Exploit is publicly available. + ANTICIPATED (4): + No known exploitation activity, but has a + high potential for exploitation. + NO_KNOWN (5): + No known exploitation activity. + """ + EXPLOITATION_ACTIVITY_UNSPECIFIED = 0 + WIDE = 1 + CONFIRMED = 2 + AVAILABLE = 3 + ANTICIPATED = 4 + NO_KNOWN = 5 + + id: str = proto.Field( + proto.STRING, + number=1, + ) + references: MutableSequence['Reference'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Reference', + ) + cvssv3: 'Cvssv3' = proto.Field( + proto.MESSAGE, + number=3, + message='Cvssv3', + ) + upstream_fix_available: bool = proto.Field( + proto.BOOL, + number=4, + ) + impact: RiskRating = proto.Field( + proto.ENUM, + number=5, + enum=RiskRating, + ) + exploitation_activity: ExploitationActivity = proto.Field( + proto.ENUM, + number=6, + enum=ExploitationActivity, + ) + observed_in_the_wild: bool = proto.Field( + proto.BOOL, + number=7, + ) + zero_day: bool = proto.Field( + proto.BOOL, + number=8, + ) + exploit_release_date: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + + +class Reference(proto.Message): + r"""Additional Links + + Attributes: + source (str): + Source of the reference e.g. NVD + uri (str): + Uri for the mentioned source e.g. + https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527. + """ + + source: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Cvssv3(proto.Message): + r"""Common Vulnerability Scoring System version 3. + + Attributes: + base_score (float): + The base score is a function of the base + metric scores. + attack_vector (google.cloud.securitycenter_v1.types.Cvssv3.AttackVector): + Base Metrics + Represents the intrinsic characteristics of a + vulnerability that are constant over time and + across user environments. This metric reflects + the context by which vulnerability exploitation + is possible. + attack_complexity (google.cloud.securitycenter_v1.types.Cvssv3.AttackComplexity): + This metric describes the conditions beyond + the attacker's control that must exist in order + to exploit the vulnerability. + privileges_required (google.cloud.securitycenter_v1.types.Cvssv3.PrivilegesRequired): + This metric describes the level of privileges + an attacker must possess before successfully + exploiting the vulnerability. + user_interaction (google.cloud.securitycenter_v1.types.Cvssv3.UserInteraction): + This metric captures the requirement for a + human user, other than the attacker, to + participate in the successful compromise of the + vulnerable component. + scope (google.cloud.securitycenter_v1.types.Cvssv3.Scope): + The Scope metric captures whether a + vulnerability in one vulnerable component + impacts resources in components beyond its + security scope. + confidentiality_impact (google.cloud.securitycenter_v1.types.Cvssv3.Impact): + This metric measures the impact to the + confidentiality of the information resources + managed by a software component due to a + successfully exploited vulnerability. + integrity_impact (google.cloud.securitycenter_v1.types.Cvssv3.Impact): + This metric measures the impact to integrity + of a successfully exploited vulnerability. + availability_impact (google.cloud.securitycenter_v1.types.Cvssv3.Impact): + This metric measures the impact to the + availability of the impacted component resulting + from a successfully exploited vulnerability. + """ + class AttackVector(proto.Enum): + r"""This metric reflects the context by which vulnerability + exploitation is possible. + + Values: + ATTACK_VECTOR_UNSPECIFIED (0): + Invalid value. + ATTACK_VECTOR_NETWORK (1): + The vulnerable component is bound to the + network stack and the set of possible attackers + extends beyond the other options listed below, + up to and including the entire Internet. + ATTACK_VECTOR_ADJACENT (2): + The vulnerable component is bound to the + network stack, but the attack is limited at the + protocol level to a logically adjacent topology. + ATTACK_VECTOR_LOCAL (3): + The vulnerable component is not bound to the + network stack and the attacker's path is via + read/write/execute capabilities. + ATTACK_VECTOR_PHYSICAL (4): + The attack requires the attacker to + physically touch or manipulate the vulnerable + component. + """ + ATTACK_VECTOR_UNSPECIFIED = 0 + ATTACK_VECTOR_NETWORK = 1 + ATTACK_VECTOR_ADJACENT = 2 + ATTACK_VECTOR_LOCAL = 3 + ATTACK_VECTOR_PHYSICAL = 4 + + class AttackComplexity(proto.Enum): + r"""This metric describes the conditions beyond the attacker's + control that must exist in order to exploit the vulnerability. + + Values: + ATTACK_COMPLEXITY_UNSPECIFIED (0): + Invalid value. + ATTACK_COMPLEXITY_LOW (1): + Specialized access conditions or extenuating + circumstances do not exist. An attacker can + expect repeatable success when attacking the + vulnerable component. + ATTACK_COMPLEXITY_HIGH (2): + A successful attack depends on conditions + beyond the attacker's control. That is, a + successful attack cannot be accomplished at + will, but requires the attacker to invest in + some measurable amount of effort in preparation + or execution against the vulnerable component + before a successful attack can be expected. + """ + ATTACK_COMPLEXITY_UNSPECIFIED = 0 + ATTACK_COMPLEXITY_LOW = 1 + ATTACK_COMPLEXITY_HIGH = 2 + + class PrivilegesRequired(proto.Enum): + r"""This metric describes the level of privileges an attacker + must possess before successfully exploiting the vulnerability. + + Values: + PRIVILEGES_REQUIRED_UNSPECIFIED (0): + Invalid value. + PRIVILEGES_REQUIRED_NONE (1): + The attacker is unauthorized prior to attack, + and therefore does not require any access to + settings or files of the vulnerable system to + carry out an attack. + PRIVILEGES_REQUIRED_LOW (2): + The attacker requires privileges that provide + basic user capabilities that could normally + affect only settings and files owned by a user. + Alternatively, an attacker with Low privileges + has the ability to access only non-sensitive + resources. + PRIVILEGES_REQUIRED_HIGH (3): + The attacker requires privileges that provide + significant (e.g., administrative) control over + the vulnerable component allowing access to + component-wide settings and files. + """ + PRIVILEGES_REQUIRED_UNSPECIFIED = 0 + PRIVILEGES_REQUIRED_NONE = 1 + PRIVILEGES_REQUIRED_LOW = 2 + PRIVILEGES_REQUIRED_HIGH = 3 + + class UserInteraction(proto.Enum): + r"""This metric captures the requirement for a human user, other + than the attacker, to participate in the successful compromise + of the vulnerable component. + + Values: + USER_INTERACTION_UNSPECIFIED (0): + Invalid value. + USER_INTERACTION_NONE (1): + The vulnerable system can be exploited + without interaction from any user. + USER_INTERACTION_REQUIRED (2): + Successful exploitation of this vulnerability + requires a user to take some action before the + vulnerability can be exploited. + """ + USER_INTERACTION_UNSPECIFIED = 0 + USER_INTERACTION_NONE = 1 + USER_INTERACTION_REQUIRED = 2 + + class Scope(proto.Enum): + r"""The Scope metric captures whether a vulnerability in one + vulnerable component impacts resources in components beyond its + security scope. + + Values: + SCOPE_UNSPECIFIED (0): + Invalid value. + SCOPE_UNCHANGED (1): + An exploited vulnerability can only affect + resources managed by the same security + authority. + SCOPE_CHANGED (2): + An exploited vulnerability can affect + resources beyond the security scope managed by + the security authority of the vulnerable + component. + """ + SCOPE_UNSPECIFIED = 0 + SCOPE_UNCHANGED = 1 + SCOPE_CHANGED = 2 + + class Impact(proto.Enum): + r"""The Impact metrics capture the effects of a successfully + exploited vulnerability on the component that suffers the worst + outcome that is most directly and predictably associated with + the attack. + + Values: + IMPACT_UNSPECIFIED (0): + Invalid value. + IMPACT_HIGH (1): + High impact. + IMPACT_LOW (2): + Low impact. + IMPACT_NONE (3): + No impact. + """ + IMPACT_UNSPECIFIED = 0 + IMPACT_HIGH = 1 + IMPACT_LOW = 2 + IMPACT_NONE = 3 + + base_score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + attack_vector: AttackVector = proto.Field( + proto.ENUM, + number=5, + enum=AttackVector, + ) + attack_complexity: AttackComplexity = proto.Field( + proto.ENUM, + number=6, + enum=AttackComplexity, + ) + privileges_required: PrivilegesRequired = proto.Field( + proto.ENUM, + number=7, + enum=PrivilegesRequired, + ) + user_interaction: UserInteraction = proto.Field( + proto.ENUM, + number=8, + enum=UserInteraction, + ) + scope: Scope = proto.Field( + proto.ENUM, + number=9, + enum=Scope, + ) + confidentiality_impact: Impact = proto.Field( + proto.ENUM, + number=10, + enum=Impact, + ) + integrity_impact: Impact = proto.Field( + proto.ENUM, + number=11, + enum=Impact, + ) + availability_impact: Impact = proto.Field( + proto.ENUM, + number=12, + enum=Impact, + ) + + +class Package(proto.Message): + r"""Package is a generic definition of a package. + + Attributes: + package_name (str): + The name of the package where the + vulnerability was detected. + cpe_uri (str): + The CPE URI where the vulnerability was + detected. + package_type (str): + Type of package, for example, os, maven, or + go. + package_version (str): + The version of the package. + """ + + package_name: str = proto.Field( + proto.STRING, + number=1, + ) + cpe_uri: str = proto.Field( + proto.STRING, + number=2, + ) + package_type: str = proto.Field( + proto.STRING, + number=3, + ) + package_version: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SecurityBulletin(proto.Message): + r"""SecurityBulletin are notifications of vulnerabilities of + Google products. + + Attributes: + bulletin_id (str): + ID of the bulletin corresponding to the + vulnerability. + submission_time (google.protobuf.timestamp_pb2.Timestamp): + Submission time of this Security Bulletin. + suggested_upgrade_version (str): + This represents a version that the cluster + receiving this notification should be upgraded + to, based on its current version. For example, + 1.15.0 + """ + + bulletin_id: str = proto.Field( + proto.STRING, + number=1, + ) + submission_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + suggested_upgrade_version: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v1/noxfile.py new file mode 100644 index 000000000000..c30f405f3ad8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-securitycenter' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +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"): + 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/securitycenter_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"): + 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", + "grpcio", + "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/securitycenter_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( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): + # Ignore release of mypy 1.11.0 which may have a regression + 'mypy!=1.11.0', + '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-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py new file mode 100644 index 000000000000..e404756019e2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + requests = securitycenter_v1.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + requests.resource_value_config.resource_value = "NONE" + requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py new file mode 100644 index 000000000000..3723f44be2cb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + requests = securitycenter_v1.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + requests.resource_value_config.resource_value = "NONE" + requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_async.py new file mode 100644 index 000000000000..c0d550405cbd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_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 BulkMuteFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py new file mode 100644 index 000000000000..39611042828f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_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 BulkMuteFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_async.py new file mode 100644 index 000000000000..6f27ee2174b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_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 CreateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = await client.create_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_sync.py new file mode 100644 index 000000000000..48ddbf103dea --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_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 CreateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = client.create_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py new file mode 100644 index 000000000000..196255a15a29 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_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 CreateEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py new file mode 100644 index 000000000000..2544f1d14706 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_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 CreateEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_async.py new file mode 100644 index 000000000000..84c10d4bf3f8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_sync.py new file mode 100644 index 000000000000..3c594dcc28cb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_async.py new file mode 100644 index 000000000000..aa47e9565150 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_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 CreateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = await client.create_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_sync.py new file mode 100644 index 000000000000..aa64e4c92f71 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_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 CreateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = client.create_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_async.py new file mode 100644 index 000000000000..c1e37d27979b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_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 CreateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_sync.py new file mode 100644 index 000000000000..f313379f2bda --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_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 CreateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py new file mode 100644 index 000000000000..20431387d14e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_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 CreateSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py new file mode 100644 index 000000000000..cc70b8c77485 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_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 CreateSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_async.py new file mode 100644 index 000000000000..5a9938f4f606 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_create_source(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_sync.py new file mode 100644 index 000000000000..d79924fc941f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_CreateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_create_source(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_async.py new file mode 100644 index 000000000000..990cd91d3f2f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + await client.delete_big_query_export(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_sync.py new file mode 100644 index 000000000000..7b8a0710a6b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + client.delete_big_query_export(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py new file mode 100644 index 000000000000..6fd5fad55d83 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_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 DeleteEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_delete_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + await client.delete_event_threat_detection_custom_module(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py new file mode 100644 index 000000000000..4126fb7da0d3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_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 DeleteEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_delete_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + client.delete_event_threat_detection_custom_module(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_async.py new file mode 100644 index 000000000000..c4f1c8484a6e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_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 DeleteMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_delete_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_mute_config(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_sync.py new file mode 100644 index 000000000000..04a1241d4610 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_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 DeleteMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_delete_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_mute_config(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_async.py new file mode 100644 index 000000000000..a2ea5ed9a93d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_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 DeleteNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_sync.py new file mode 100644 index 000000000000..bb408a4637e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_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 DeleteNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_async.py new file mode 100644 index 000000000000..42d63c083d6a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_resource_value_config(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py new file mode 100644 index 000000000000..a84b69405090 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_resource_value_config(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py new file mode 100644 index 000000000000..9e2c550b018b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_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 DeleteSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_delete_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + await client.delete_security_health_analytics_custom_module(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py new file mode 100644 index 000000000000..44d1b7765a20 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_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 DeleteSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_delete_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + client.delete_security_health_analytics_custom_module(request=request) + + +# [END securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_async.py new file mode 100644 index 000000000000..2d3a4e11966a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_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 GetBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_sync.py new file mode 100644 index 000000000000..f3754570b866 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_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 GetBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = client.get_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py new file mode 100644 index 000000000000..fe81fc63fb30 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_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 GetEffectiveEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_effective_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_effective_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py new file mode 100644 index 000000000000..1d4d49fff5bd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_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 GetEffectiveEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_effective_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_effective_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py new file mode 100644 index 000000000000..fe87fa09b31f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_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 GetEffectiveSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_effective_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_effective_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py new file mode 100644 index 000000000000..bfa2f6f00642 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_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 GetEffectiveSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_effective_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_effective_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py new file mode 100644 index 000000000000..62c809c57f6f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_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 GetEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py new file mode 100644 index 000000000000..cbde7132fb16 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_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 GetEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_async.py new file mode 100644 index 000000000000..3884cd78982e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_sync.py new file mode 100644 index 000000000000..04461d2bd874 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_async.py new file mode 100644 index 000000000000..cd5077ce53bb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_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 GetMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_sync.py new file mode 100644 index 000000000000..0794d6d0a981 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_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 GetMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_async.py new file mode 100644 index 000000000000..4ca94a312da4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_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 GetNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_sync.py new file mode 100644 index 000000000000..a9fdde5359f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_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 GetNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_async.py new file mode 100644 index 000000000000..5cf5ce3a26d2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_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 GetOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_sync.py new file mode 100644 index 000000000000..fb45a62aeafa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_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 GetOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_async.py new file mode 100644 index 000000000000..30fb9d9c366b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_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 GetResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_sync.py new file mode 100644 index 000000000000..0b453f060803 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_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 GetResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py new file mode 100644 index 000000000000..4f3caf3a11bd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_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 GetSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py new file mode 100644 index 000000000000..55bae4951d45 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_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 GetSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( + name="name_value", + ) + + # Make the request + response = client.get_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_async.py new file mode 100644 index 000000000000..1b99150b7442 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_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 GetSimulation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetSimulation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_simulation(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_simulation(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetSimulation_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_sync.py new file mode 100644 index 000000000000..083acba19009 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_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 GetSimulation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetSimulation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_simulation(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = client.get_simulation(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetSimulation_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_async.py new file mode 100644 index 000000000000..3b09eb27dfef --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_source(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_sync.py new file mode 100644 index 000000000000..ae5d605951c4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_source(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_async.py new file mode 100644 index 000000000000..ba715be17d9c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_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 GetValuedResource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetValuedResource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_get_valued_resource(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_valued_resource(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetValuedResource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_sync.py new file mode 100644 index 000000000000..b3aa5036453d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_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 GetValuedResource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GetValuedResource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_get_valued_resource(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_valued_resource(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GetValuedResource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_async.py new file mode 100644 index 000000000000..972ab2a30dc1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_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 GroupAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GroupAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_group_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GroupAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_sync.py new file mode 100644 index 000000000000..85fa08c63683 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_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 GroupAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GroupAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_group_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GroupAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_async.py new file mode 100644 index 000000000000..8277a2723cc7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GroupFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_group_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_sync.py new file mode 100644 index 000000000000..501397bb2a26 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_GroupFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_group_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_async.py new file mode 100644 index 000000000000..d7eb57f6976c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_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 ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_sync.py new file mode 100644 index 000000000000..129d168899aa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_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 ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_assets(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_async.py new file mode 100644 index 000000000000..1fd2c65f76c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_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 ListAttackPaths +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListAttackPaths_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_attack_paths(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListAttackPaths_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_sync.py new file mode 100644 index 000000000000..ceea93417e1d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_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 ListAttackPaths +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListAttackPaths_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_attack_paths(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListAttackPaths_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_async.py new file mode 100644 index 000000000000..438df71d9c0c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_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 ListBigQueryExports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_sync.py new file mode 100644 index 000000000000..b967f0a3cc2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_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 ListBigQueryExports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py new file mode 100644 index 000000000000..7b214a5e3786 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_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 ListDescendantEventThreatDetectionCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_descendant_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py new file mode 100644 index 000000000000..764f1cbe9905 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_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 ListDescendantEventThreatDetectionCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_descendant_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py new file mode 100644 index 000000000000..4f577cf8f0e1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_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 ListDescendantSecurityHealthAnalyticsCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_descendant_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py new file mode 100644 index 000000000000..44aacf778aaa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_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 ListDescendantSecurityHealthAnalyticsCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_descendant_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py new file mode 100644 index 000000000000..40ac4b1fae7f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_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 ListEffectiveEventThreatDetectionCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_effective_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_event_threat_detection_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py new file mode 100644 index 000000000000..d339fb184b9f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_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 ListEffectiveEventThreatDetectionCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_effective_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_event_threat_detection_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py new file mode 100644 index 000000000000..2ddb1fdf50a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_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 ListEffectiveSecurityHealthAnalyticsCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_effective_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_security_health_analytics_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py new file mode 100644 index 000000000000..a6d1e35fe7a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_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 ListEffectiveSecurityHealthAnalyticsCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_effective_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_effective_security_health_analytics_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py new file mode 100644 index 000000000000..053e3047b38a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_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 ListEventThreatDetectionCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_event_threat_detection_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py new file mode 100644 index 000000000000..8216523320e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_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 ListEventThreatDetectionCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_event_threat_detection_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_event_threat_detection_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_async.py new file mode 100644 index 000000000000..f2fc2cc4e0e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_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 securitycenter_v1 + + +async def sample_list_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_sync.py new file mode 100644 index 000000000000..574c0709c259 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_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 securitycenter_v1 + + +def sample_list_findings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_async.py new file mode 100644 index 000000000000..b4984b693810 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_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 ListMuteConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_mute_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_sync.py new file mode 100644 index 000000000000..451cf050e43b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_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 ListMuteConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_mute_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_async.py new file mode 100644 index 000000000000..9b8132cda94b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_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 ListNotificationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_sync.py new file mode 100644 index 000000000000..27e3721c377d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_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 ListNotificationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_async.py new file mode 100644 index 000000000000..6d2ebd0e1a1e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_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 ListResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py new file mode 100644 index 000000000000..a34c9520517f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_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 ListResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py new file mode 100644 index 000000000000..b6d94d40eb3e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_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 ListSecurityHealthAnalyticsCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_health_analytics_custom_modules(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py new file mode 100644 index 000000000000..d352446e7eed --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_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 ListSecurityHealthAnalyticsCustomModules +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_security_health_analytics_custom_modules(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_health_analytics_custom_modules(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_async.py new file mode 100644 index 000000000000..6e653789098a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListSources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_sources(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_sync.py new file mode 100644 index 000000000000..3d73c443003d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListSources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_sources(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_async.py new file mode 100644 index 000000000000..09db5a4658e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_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 ListValuedResources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListValuedResources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_list_valued_resources(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListValuedResources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_sync.py new file mode 100644 index 000000000000..0c4289dd7f65 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_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 ListValuedResources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ListValuedResources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_list_valued_resources(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ListValuedResources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_async.py new file mode 100644 index 000000000000..3e126713c3e2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_sync.py new file mode 100644 index 000000000000..de045eb9e950 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_async.py new file mode 100644 index 000000000000..83c439f5e761 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SetFindingState_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_set_finding_state(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_sync.py new file mode 100644 index 000000000000..b6c47c7d5405 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SetFindingState_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_set_finding_state(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_async.py new file mode 100644 index 000000000000..d0828598e4ea --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_sync.py new file mode 100644 index 000000000000..9592707e3a59 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_async.py new file mode 100644 index 000000000000..1d2631a20453 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_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 SetMute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SetMute_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_set_mute(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = await client.set_mute(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SetMute_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_sync.py new file mode 100644 index 000000000000..10b240d03f92 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_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 SetMute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SetMute_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_set_mute(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = client.set_mute(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SetMute_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py new file mode 100644 index 000000000000..8f323db2f936 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_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 SimulateSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_simulate_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + resource = securitycenter_v1.SimulatedResource() + resource.resource_type = "resource_type_value" + + request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + resource=resource, + ) + + # Make the request + response = await client.simulate_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py new file mode 100644 index 000000000000..81d436d78385 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_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 SimulateSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_simulate_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + resource = securitycenter_v1.SimulatedResource() + resource.resource_type = "resource_type_value" + + request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( + parent="parent_value", + resource=resource, + ) + + # Make the request + response = client.simulate_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_async.py new file mode 100644 index 000000000000..479364cbe039 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_sync.py new file mode 100644 index 000000000000..d39b8072621c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_async.py new file mode 100644 index 000000000000..e07c6c16bb47 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_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 UpdateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateBigQueryExportRequest( + ) + + # Make the request + response = await client.update_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_sync.py new file mode 100644 index 000000000000..0569a012c3bc --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_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 UpdateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_big_query_export(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateBigQueryExportRequest( + ) + + # Make the request + response = client.update_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py new file mode 100644 index 000000000000..fd503424dd75 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_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 UpdateEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( + ) + + # Make the request + response = await client.update_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py new file mode 100644 index 000000000000..05ca8e32603f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_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 UpdateEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( + ) + + # Make the request + response = client.update_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_async.py new file mode 100644 index 000000000000..dd917f4ac903 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_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 UpdateExternalSystem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_external_system(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateExternalSystemRequest( + ) + + # Make the request + response = await client.update_external_system(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_sync.py new file mode 100644 index 000000000000..fc184d7026aa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_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 UpdateExternalSystem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_external_system(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateExternalSystemRequest( + ) + + # Make the request + response = client.update_external_system(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_async.py new file mode 100644 index 000000000000..fb05f8e20bdf --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_sync.py new file mode 100644 index 000000000000..3c4fe5bc7ec5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_finding(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_async.py new file mode 100644 index 000000000000..39d5f038be44 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_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 UpdateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = await client.update_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_sync.py new file mode 100644 index 000000000000..245f3c802a09 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_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 UpdateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_mute_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v1.MuteConfig() + mute_config.filter = "filter_value" + + request = securitycenter_v1.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = client.update_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_async.py new file mode 100644 index 000000000000..6dfffbef6f93 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_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 UpdateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_sync.py new file mode 100644 index 000000000000..a8ca94d09985 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_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 UpdateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_notification_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_async.py new file mode 100644 index 000000000000..b88b1aa0af5e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = await client.update_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_sync.py new file mode 100644 index 000000000000..c897ad8cdba4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = client.update_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_async.py new file mode 100644 index 000000000000..2b7526207b34 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_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 UpdateResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + resource_value_config = securitycenter_v1.ResourceValueConfig() + resource_value_config.resource_value = "NONE" + resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.UpdateResourceValueConfigRequest( + resource_value_config=resource_value_config, + ) + + # Make the request + response = await client.update_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_sync.py new file mode 100644 index 000000000000..fe7fb7c93f87 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_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 UpdateResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + resource_value_config = securitycenter_v1.ResourceValueConfig() + resource_value_config.resource_value = "NONE" + resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v1.UpdateResourceValueConfigRequest( + resource_value_config=resource_value_config, + ) + + # Make the request + response = client.update_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py new file mode 100644 index 000000000000..66f5cd744979 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_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 UpdateSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( + ) + + # Make the request + response = await client.update_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py new file mode 100644 index 000000000000..ed56eba54e03 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_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 UpdateSecurityHealthAnalyticsCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_security_health_analytics_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( + ) + + # Make the request + response = client.update_security_health_analytics_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_async.py new file mode 100644 index 000000000000..1b69e29a2d37 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_security_marks(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_sync.py new file mode 100644 index 000000000000..b0c6a29d705b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_security_marks(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_async.py new file mode 100644 index 000000000000..659495e1c73f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_update_source(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_sync.py new file mode 100644 index 000000000000..80ac8afaabd7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_UpdateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_update_source(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py new file mode 100644 index 000000000000..38c6309258a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_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 ValidateEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +async def sample_validate_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + raw_text="raw_text_value", + type_="type__value", + ) + + # Make the request + response = await client.validate_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py new file mode 100644 index 000000000000..dbcc6d5f0f5c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_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 ValidateEventThreatDetectionCustomModule +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1 + + +def sample_validate_event_threat_detection_custom_module(): + # Create a client + client = securitycenter_v1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( + parent="parent_value", + raw_text="raw_text_value", + type_="type__value", + ) + + # Make the request + response = client.validate_event_threat_detection_custom_module(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json new file mode 100644 index 000000000000..176395462f39 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json @@ -0,0 +1,10298 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.securitycenter.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-securitycenter", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.batch_create_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BatchCreateResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BatchCreateResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse", + "shortName": "batch_create_resource_value_configs" + }, + "description": "Sample for BatchCreateResourceValueConfigs", + "file": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.batch_create_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BatchCreateResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BatchCreateResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse", + "shortName": "batch_create_resource_value_configs" + }, + "description": "Sample for BatchCreateResourceValueConfigs", + "file": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.bulk_mute_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BulkMuteFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BulkMuteFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "bulk_mute_findings" + }, + "description": "Sample for BulkMuteFindings", + "file": "securitycenter_v1_generated_security_center_bulk_mute_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v1_generated_security_center_bulk_mute_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.bulk_mute_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BulkMuteFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BulkMuteFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "bulk_mute_findings" + }, + "description": "Sample for BulkMuteFindings", + "file": "securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v1.types.BigQueryExport" + }, + { + "name": "big_query_export_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.BigQueryExport", + "shortName": "create_big_query_export" + }, + "description": "Sample for CreateBigQueryExport", + "file": "securitycenter_v1_generated_security_center_create_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v1_generated_security_center_create_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v1.types.BigQueryExport" + }, + { + "name": "big_query_export_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.BigQueryExport", + "shortName": "create_big_query_export" + }, + "description": "Sample for CreateBigQueryExport", + "file": "securitycenter_v1_generated_security_center_create_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v1_generated_security_center_create_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "event_threat_detection_custom_module", + "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule", + "shortName": "create_event_threat_detection_custom_module" + }, + "description": "Sample for CreateEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "event_threat_detection_custom_module", + "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule", + "shortName": "create_event_threat_detection_custom_module" + }, + "description": "Sample for CreateEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v1_generated_security_center_create_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1_generated_security_center_create_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v1_generated_security_center_create_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1_generated_security_center_create_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateMuteConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v1.types.MuteConfig" + }, + { + "name": "mute_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.cloud.securitycenter_v1.types.MuteConfig", + "shortName": "create_mute_config" + }, + "description": "Sample for CreateMuteConfig", + "file": "securitycenter_v1_generated_security_center_create_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v1_generated_security_center_create_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateMuteConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v1.types.MuteConfig" + }, + { + "name": "mute_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.cloud.securitycenter_v1.types.MuteConfig", + "shortName": "create_mute_config" + }, + "description": "Sample for CreateMuteConfig", + "file": "securitycenter_v1_generated_security_center_create_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v1_generated_security_center_create_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "config_id", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1.types.NotificationConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v1_generated_security_center_create_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1_generated_security_center_create_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "config_id", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1.types.NotificationConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v1_generated_security_center_create_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1_generated_security_center_create_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "security_health_analytics_custom_module", + "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", + "shortName": "create_security_health_analytics_custom_module" + }, + "description": "Sample for CreateSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "security_health_analytics_custom_module", + "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", + "shortName": "create_security_health_analytics_custom_module" + }, + "description": "Sample for CreateSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v1_generated_security_center_create_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_create_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v1_generated_security_center_create_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_create_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest" + }, + { + "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_big_query_export" + }, + "description": "Sample for DeleteBigQueryExport", + "file": "securitycenter_v1_generated_security_center_delete_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v1_generated_security_center_delete_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest" + }, + { + "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_big_query_export" + }, + "description": "Sample for DeleteBigQueryExport", + "file": "securitycenter_v1_generated_security_center_delete_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v1_generated_security_center_delete_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest" + }, + { + "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_event_threat_detection_custom_module" + }, + "description": "Sample for DeleteEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest" + }, + { + "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_event_threat_detection_custom_module" + }, + "description": "Sample for DeleteEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest" + }, + { + "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_mute_config" + }, + "description": "Sample for DeleteMuteConfig", + "file": "securitycenter_v1_generated_security_center_delete_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v1_generated_security_center_delete_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest" + }, + { + "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_mute_config" + }, + "description": "Sample for DeleteMuteConfig", + "file": "securitycenter_v1_generated_security_center_delete_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v1_generated_security_center_delete_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest" + }, + { + "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_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v1_generated_security_center_delete_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1_generated_security_center_delete_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest" + }, + { + "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_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v1_generated_security_center_delete_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1_generated_security_center_delete_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest" + }, + { + "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_resource_value_config" + }, + "description": "Sample for DeleteResourceValueConfig", + "file": "securitycenter_v1_generated_security_center_delete_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v1_generated_security_center_delete_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest" + }, + { + "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_resource_value_config" + }, + "description": "Sample for DeleteResourceValueConfig", + "file": "securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "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_security_health_analytics_custom_module" + }, + "description": "Sample for DeleteSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "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_security_health_analytics_custom_module" + }, + "description": "Sample for DeleteSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetBigQueryExportRequest" + }, + { + "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.securitycenter_v1.types.BigQueryExport", + "shortName": "get_big_query_export" + }, + "description": "Sample for GetBigQueryExport", + "file": "securitycenter_v1_generated_security_center_get_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetBigQueryExportRequest" + }, + { + "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.securitycenter_v1.types.BigQueryExport", + "shortName": "get_big_query_export" + }, + "description": "Sample for GetBigQueryExport", + "file": "securitycenter_v1_generated_security_center_get_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_effective_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetEffectiveEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule", + "shortName": "get_effective_event_threat_detection_custom_module" + }, + "description": "Sample for GetEffectiveEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_effective_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetEffectiveEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule", + "shortName": "get_effective_event_threat_detection_custom_module" + }, + "description": "Sample for GetEffectiveEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_effective_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetEffectiveSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule", + "shortName": "get_effective_security_health_analytics_custom_module" + }, + "description": "Sample for GetEffectiveSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_effective_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetEffectiveSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule", + "shortName": "get_effective_security_health_analytics_custom_module" + }, + "description": "Sample for GetEffectiveSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.EventThreatDetectionCustomModule", + "shortName": "get_event_threat_detection_custom_module" + }, + "description": "Sample for GetEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.EventThreatDetectionCustomModule", + "shortName": "get_event_threat_detection_custom_module" + }, + "description": "Sample for GetEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v1_generated_security_center_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v1_generated_security_center_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetMuteConfigRequest" + }, + { + "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.securitycenter_v1.types.MuteConfig", + "shortName": "get_mute_config" + }, + "description": "Sample for GetMuteConfig", + "file": "securitycenter_v1_generated_security_center_get_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetMuteConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetMuteConfigRequest" + }, + { + "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.securitycenter_v1.types.MuteConfig", + "shortName": "get_mute_config" + }, + "description": "Sample for GetMuteConfig", + "file": "securitycenter_v1_generated_security_center_get_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetMuteConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v1.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v1_generated_security_center_get_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v1.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v1_generated_security_center_get_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest" + }, + { + "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.securitycenter_v1.types.OrganizationSettings", + "shortName": "get_organization_settings" + }, + "description": "Sample for GetOrganizationSettings", + "file": "securitycenter_v1_generated_security_center_get_organization_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_organization_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest" + }, + { + "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.securitycenter_v1.types.OrganizationSettings", + "shortName": "get_organization_settings" + }, + "description": "Sample for GetOrganizationSettings", + "file": "securitycenter_v1_generated_security_center_get_organization_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_organization_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest" + }, + { + "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.securitycenter_v1.types.ResourceValueConfig", + "shortName": "get_resource_value_config" + }, + "description": "Sample for GetResourceValueConfig", + "file": "securitycenter_v1_generated_security_center_get_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest" + }, + { + "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.securitycenter_v1.types.ResourceValueConfig", + "shortName": "get_resource_value_config" + }, + "description": "Sample for GetResourceValueConfig", + "file": "securitycenter_v1_generated_security_center_get_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", + "shortName": "get_security_health_analytics_custom_module" + }, + "description": "Sample for GetSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", + "shortName": "get_security_health_analytics_custom_module" + }, + "description": "Sample for GetSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_simulation", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSimulation", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSimulation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetSimulationRequest" + }, + { + "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.securitycenter_v1.types.Simulation", + "shortName": "get_simulation" + }, + "description": "Sample for GetSimulation", + "file": "securitycenter_v1_generated_security_center_get_simulation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSimulation_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_simulation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_simulation", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSimulation", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSimulation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetSimulationRequest" + }, + { + "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.securitycenter_v1.types.Simulation", + "shortName": "get_simulation" + }, + "description": "Sample for GetSimulation", + "file": "securitycenter_v1_generated_security_center_get_simulation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSimulation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_simulation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetSourceRequest" + }, + { + "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.securitycenter_v1.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v1_generated_security_center_get_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetSourceRequest" + }, + { + "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.securitycenter_v1.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v1_generated_security_center_get_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_valued_resource", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetValuedResource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetValuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetValuedResourceRequest" + }, + { + "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.securitycenter_v1.types.ValuedResource", + "shortName": "get_valued_resource" + }, + "description": "Sample for GetValuedResource", + "file": "securitycenter_v1_generated_security_center_get_valued_resource_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetValuedResource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_valued_resource_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_valued_resource", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetValuedResource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetValuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GetValuedResourceRequest" + }, + { + "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.securitycenter_v1.types.ValuedResource", + "shortName": "get_valued_resource" + }, + "description": "Sample for GetValuedResource", + "file": "securitycenter_v1_generated_security_center_get_valued_resource_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GetValuedResource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_get_valued_resource_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.group_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GroupAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsAsyncPager", + "shortName": "group_assets" + }, + "description": "Sample for GroupAssets", + "file": "securitycenter_v1_generated_security_center_group_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1_generated_security_center_group_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.group_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GroupAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsPager", + "shortName": "group_assets" + }, + "description": "Sample for GroupAssets", + "file": "securitycenter_v1_generated_security_center_group_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1_generated_security_center_group_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsAsyncPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v1_generated_security_center_group_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1_generated_security_center_group_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v1_generated_security_center_group_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1_generated_security_center_group_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsAsyncPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "securitycenter_v1_generated_security_center_list_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1_generated_security_center_list_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "securitycenter_v1_generated_security_center_list_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1_generated_security_center_list_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_attack_paths", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAttackPaths", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAttackPaths" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListAttackPathsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListAttackPathsAsyncPager", + "shortName": "list_attack_paths" + }, + "description": "Sample for ListAttackPaths", + "file": "securitycenter_v1_generated_security_center_list_attack_paths_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v1_generated_security_center_list_attack_paths_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_attack_paths", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAttackPaths", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAttackPaths" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListAttackPathsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListAttackPathsPager", + "shortName": "list_attack_paths" + }, + "description": "Sample for ListAttackPaths", + "file": "securitycenter_v1_generated_security_center_list_attack_paths_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v1_generated_security_center_list_attack_paths_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_big_query_exports", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListBigQueryExports", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListBigQueryExports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsAsyncPager", + "shortName": "list_big_query_exports" + }, + "description": "Sample for ListBigQueryExports", + "file": "securitycenter_v1_generated_security_center_list_big_query_exports_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v1_generated_security_center_list_big_query_exports_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_big_query_exports", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListBigQueryExports", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListBigQueryExports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsPager", + "shortName": "list_big_query_exports" + }, + "description": "Sample for ListBigQueryExports", + "file": "securitycenter_v1_generated_security_center_list_big_query_exports_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v1_generated_security_center_list_big_query_exports_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_descendant_event_threat_detection_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantEventThreatDetectionCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListDescendantEventThreatDetectionCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager", + "shortName": "list_descendant_event_threat_detection_custom_modules" + }, + "description": "Sample for ListDescendantEventThreatDetectionCustomModules", + "file": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_descendant_event_threat_detection_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantEventThreatDetectionCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListDescendantEventThreatDetectionCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesPager", + "shortName": "list_descendant_event_threat_detection_custom_modules" + }, + "description": "Sample for ListDescendantEventThreatDetectionCustomModules", + "file": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_descendant_security_health_analytics_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantSecurityHealthAnalyticsCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListDescendantSecurityHealthAnalyticsCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager", + "shortName": "list_descendant_security_health_analytics_custom_modules" + }, + "description": "Sample for ListDescendantSecurityHealthAnalyticsCustomModules", + "file": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_descendant_security_health_analytics_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantSecurityHealthAnalyticsCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListDescendantSecurityHealthAnalyticsCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager", + "shortName": "list_descendant_security_health_analytics_custom_modules" + }, + "description": "Sample for ListDescendantSecurityHealthAnalyticsCustomModules", + "file": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_effective_event_threat_detection_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveEventThreatDetectionCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListEffectiveEventThreatDetectionCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesAsyncPager", + "shortName": "list_effective_event_threat_detection_custom_modules" + }, + "description": "Sample for ListEffectiveEventThreatDetectionCustomModules", + "file": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_effective_event_threat_detection_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveEventThreatDetectionCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListEffectiveEventThreatDetectionCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesPager", + "shortName": "list_effective_event_threat_detection_custom_modules" + }, + "description": "Sample for ListEffectiveEventThreatDetectionCustomModules", + "file": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_effective_security_health_analytics_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveSecurityHealthAnalyticsCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListEffectiveSecurityHealthAnalyticsCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager", + "shortName": "list_effective_security_health_analytics_custom_modules" + }, + "description": "Sample for ListEffectiveSecurityHealthAnalyticsCustomModules", + "file": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_effective_security_health_analytics_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveSecurityHealthAnalyticsCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListEffectiveSecurityHealthAnalyticsCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager", + "shortName": "list_effective_security_health_analytics_custom_modules" + }, + "description": "Sample for ListEffectiveSecurityHealthAnalyticsCustomModules", + "file": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_event_threat_detection_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEventThreatDetectionCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListEventThreatDetectionCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesAsyncPager", + "shortName": "list_event_threat_detection_custom_modules" + }, + "description": "Sample for ListEventThreatDetectionCustomModules", + "file": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_event_threat_detection_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEventThreatDetectionCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListEventThreatDetectionCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesPager", + "shortName": "list_event_threat_detection_custom_modules" + }, + "description": "Sample for ListEventThreatDetectionCustomModules", + "file": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_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.securitycenter_v1.services.security_center.pagers.ListFindingsAsyncPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v1_generated_security_center_list_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1_generated_security_center_list_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_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.securitycenter_v1.services.security_center.pagers.ListFindingsPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v1_generated_security_center_list_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1_generated_security_center_list_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_mute_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListMuteConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListMuteConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListMuteConfigsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsAsyncPager", + "shortName": "list_mute_configs" + }, + "description": "Sample for ListMuteConfigs", + "file": "securitycenter_v1_generated_security_center_list_mute_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v1_generated_security_center_list_mute_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_mute_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListMuteConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListMuteConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListMuteConfigsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsPager", + "shortName": "list_mute_configs" + }, + "description": "Sample for ListMuteConfigs", + "file": "securitycenter_v1_generated_security_center_list_mute_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v1_generated_security_center_list_mute_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsAsyncPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v1_generated_security_center_list_notification_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1_generated_security_center_list_notification_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v1_generated_security_center_list_notification_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1_generated_security_center_list_notification_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsAsyncPager", + "shortName": "list_resource_value_configs" + }, + "description": "Sample for ListResourceValueConfigs", + "file": "securitycenter_v1_generated_security_center_list_resource_value_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v1_generated_security_center_list_resource_value_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsPager", + "shortName": "list_resource_value_configs" + }, + "description": "Sample for ListResourceValueConfigs", + "file": "securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_security_health_analytics_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSecurityHealthAnalyticsCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSecurityHealthAnalyticsCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager", + "shortName": "list_security_health_analytics_custom_modules" + }, + "description": "Sample for ListSecurityHealthAnalyticsCustomModules", + "file": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_security_health_analytics_custom_modules", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSecurityHealthAnalyticsCustomModules", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSecurityHealthAnalyticsCustomModules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesPager", + "shortName": "list_security_health_analytics_custom_modules" + }, + "description": "Sample for ListSecurityHealthAnalyticsCustomModules", + "file": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListSourcesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListSourcesAsyncPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v1_generated_security_center_list_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSources_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": "securitycenter_v1_generated_security_center_list_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListSourcesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListSourcesPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v1_generated_security_center_list_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSources_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": "securitycenter_v1_generated_security_center_list_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_valued_resources", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListValuedResources", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListValuedResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListValuedResourcesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesAsyncPager", + "shortName": "list_valued_resources" + }, + "description": "Sample for ListValuedResources", + "file": "securitycenter_v1_generated_security_center_list_valued_resources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v1_generated_security_center_list_valued_resources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_valued_resources", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListValuedResources", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListValuedResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ListValuedResourcesRequest" + }, + { + "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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesPager", + "shortName": "list_valued_resources" + }, + "description": "Sample for ListValuedResources", + "file": "securitycenter_v1_generated_security_center_list_valued_resources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v1_generated_security_center_list_valued_resources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.run_asset_discovery", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.RunAssetDiscovery", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "RunAssetDiscovery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "run_asset_discovery" + }, + "description": "Sample for RunAssetDiscovery", + "file": "securitycenter_v1_generated_security_center_run_asset_discovery_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1_generated_security_center_run_asset_discovery_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.run_asset_discovery", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.RunAssetDiscovery", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "RunAssetDiscovery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "run_asset_discovery" + }, + "description": "Sample for RunAssetDiscovery", + "file": "securitycenter_v1_generated_security_center_run_asset_discovery_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1_generated_security_center_run_asset_discovery_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v1.types.Finding.State" + }, + { + "name": "start_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v1_generated_security_center_set_finding_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1_generated_security_center_set_finding_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v1.types.Finding.State" + }, + { + "name": "start_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v1_generated_security_center_set_finding_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1_generated_security_center_set_finding_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v1_generated_security_center_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v1_generated_security_center_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.set_mute", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetMute", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetMute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.SetMuteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "mute", + "type": "google.cloud.securitycenter_v1.types.Finding.Mute" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "set_mute" + }, + "description": "Sample for SetMute", + "file": "securitycenter_v1_generated_security_center_set_mute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SetMute_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": "securitycenter_v1_generated_security_center_set_mute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.set_mute", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetMute", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetMute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.SetMuteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "mute", + "type": "google.cloud.securitycenter_v1.types.Finding.Mute" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "set_mute" + }, + "description": "Sample for SetMute", + "file": "securitycenter_v1_generated_security_center_set_mute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SetMute_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": "securitycenter_v1_generated_security_center_set_mute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.simulate_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SimulateSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SimulateSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "custom_config", + "type": "google.cloud.securitycenter_v1.types.CustomConfig" + }, + { + "name": "resource", + "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse", + "shortName": "simulate_security_health_analytics_custom_module" + }, + "description": "Sample for SimulateSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.simulate_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SimulateSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SimulateSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "custom_config", + "type": "google.cloud.securitycenter_v1.types.CustomConfig" + }, + { + "name": "resource", + "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse", + "shortName": "simulate_security_health_analytics_custom_module" + }, + "description": "Sample for SimulateSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v1_generated_security_center_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v1_generated_security_center_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v1.types.BigQueryExport" + }, + { + "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.securitycenter_v1.types.BigQueryExport", + "shortName": "update_big_query_export" + }, + "description": "Sample for UpdateBigQueryExport", + "file": "securitycenter_v1_generated_security_center_update_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v1_generated_security_center_update_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v1.types.BigQueryExport" + }, + { + "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.securitycenter_v1.types.BigQueryExport", + "shortName": "update_big_query_export" + }, + "description": "Sample for UpdateBigQueryExport", + "file": "securitycenter_v1_generated_security_center_update_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v1_generated_security_center_update_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest" + }, + { + "name": "event_threat_detection_custom_module", + "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" + }, + { + "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.securitycenter_v1.types.EventThreatDetectionCustomModule", + "shortName": "update_event_threat_detection_custom_module" + }, + "description": "Sample for UpdateEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest" + }, + { + "name": "event_threat_detection_custom_module", + "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" + }, + { + "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.securitycenter_v1.types.EventThreatDetectionCustomModule", + "shortName": "update_event_threat_detection_custom_module" + }, + "description": "Sample for UpdateEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_external_system", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateExternalSystem", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateExternalSystem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest" + }, + { + "name": "external_system", + "type": "google.cloud.securitycenter_v1.types.ExternalSystem" + }, + { + "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.securitycenter_v1.types.ExternalSystem", + "shortName": "update_external_system" + }, + "description": "Sample for UpdateExternalSystem", + "file": "securitycenter_v1_generated_security_center_update_external_system_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v1_generated_security_center_update_external_system_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_external_system", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateExternalSystem", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateExternalSystem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest" + }, + { + "name": "external_system", + "type": "google.cloud.securitycenter_v1.types.ExternalSystem" + }, + { + "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.securitycenter_v1.types.ExternalSystem", + "shortName": "update_external_system" + }, + "description": "Sample for UpdateExternalSystem", + "file": "securitycenter_v1_generated_security_center_update_external_system_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v1_generated_security_center_update_external_system_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v1_generated_security_center_update_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1_generated_security_center_update_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v1_generated_security_center_update_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1_generated_security_center_update_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v1.types.MuteConfig" + }, + { + "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.securitycenter_v1.types.MuteConfig", + "shortName": "update_mute_config" + }, + "description": "Sample for UpdateMuteConfig", + "file": "securitycenter_v1_generated_security_center_update_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v1_generated_security_center_update_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v1.types.MuteConfig" + }, + { + "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.securitycenter_v1.types.MuteConfig", + "shortName": "update_mute_config" + }, + "description": "Sample for UpdateMuteConfig", + "file": "securitycenter_v1_generated_security_center_update_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v1_generated_security_center_update_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1.types.NotificationConfig" + }, + { + "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.securitycenter_v1.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v1_generated_security_center_update_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1_generated_security_center_update_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1.types.NotificationConfig" + }, + { + "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.securitycenter_v1.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v1_generated_security_center_update_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1_generated_security_center_update_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest" + }, + { + "name": "organization_settings", + "type": "google.cloud.securitycenter_v1.types.OrganizationSettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.OrganizationSettings", + "shortName": "update_organization_settings" + }, + "description": "Sample for UpdateOrganizationSettings", + "file": "securitycenter_v1_generated_security_center_update_organization_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1_generated_security_center_update_organization_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest" + }, + { + "name": "organization_settings", + "type": "google.cloud.securitycenter_v1.types.OrganizationSettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.OrganizationSettings", + "shortName": "update_organization_settings" + }, + "description": "Sample for UpdateOrganizationSettings", + "file": "securitycenter_v1_generated_security_center_update_organization_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1_generated_security_center_update_organization_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest" + }, + { + "name": "resource_value_config", + "type": "google.cloud.securitycenter_v1.types.ResourceValueConfig" + }, + { + "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.securitycenter_v1.types.ResourceValueConfig", + "shortName": "update_resource_value_config" + }, + "description": "Sample for UpdateResourceValueConfig", + "file": "securitycenter_v1_generated_security_center_update_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v1_generated_security_center_update_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest" + }, + { + "name": "resource_value_config", + "type": "google.cloud.securitycenter_v1.types.ResourceValueConfig" + }, + { + "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.securitycenter_v1.types.ResourceValueConfig", + "shortName": "update_resource_value_config" + }, + "description": "Sample for UpdateResourceValueConfig", + "file": "securitycenter_v1_generated_security_center_update_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v1_generated_security_center_update_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "name": "security_health_analytics_custom_module", + "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" + }, + { + "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", + "shortName": "update_security_health_analytics_custom_module" + }, + "description": "Sample for UpdateSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_security_health_analytics_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityHealthAnalyticsCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityHealthAnalyticsCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest" + }, + { + "name": "security_health_analytics_custom_module", + "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" + }, + { + "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", + "shortName": "update_security_health_analytics_custom_module" + }, + "description": "Sample for UpdateSecurityHealthAnalyticsCustomModule", + "file": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v1.types.SecurityMarks" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v1_generated_security_center_update_security_marks_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1_generated_security_center_update_security_marks_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v1.types.SecurityMarks" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v1_generated_security_center_update_security_marks_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1_generated_security_center_update_security_marks_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v1_generated_security_center_update_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1_generated_security_center_update_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v1_generated_security_center_update_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1_generated_security_center_update_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.validate_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ValidateEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ValidateEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse", + "shortName": "validate_event_threat_detection_custom_module" + }, + "description": "Sample for ValidateEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.validate_event_threat_detection_custom_module", + "method": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ValidateEventThreatDetectionCustomModule", + "service": { + "fullName": "google.cloud.securitycenter.v1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ValidateEventThreatDetectionCustomModule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse", + "shortName": "validate_event_threat_detection_custom_module" + }, + "description": "Sample for ValidateEventThreatDetectionCustomModule", + "file": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py new file mode 100644 index 000000000000..077baab9f5d2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py @@ -0,0 +1,238 @@ +#! /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 securitycenterCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_create_resource_value_configs': ('parent', 'requests', ), + 'bulk_mute_findings': ('parent', 'filter', 'mute_annotation', 'mute_state', ), + 'create_big_query_export': ('parent', 'big_query_export', 'big_query_export_id', ), + 'create_event_threat_detection_custom_module': ('parent', 'event_threat_detection_custom_module', ), + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_mute_config': ('parent', 'mute_config', 'mute_config_id', ), + 'create_notification_config': ('parent', 'config_id', 'notification_config', ), + 'create_security_health_analytics_custom_module': ('parent', 'security_health_analytics_custom_module', ), + 'create_source': ('parent', 'source', ), + 'delete_big_query_export': ('name', ), + 'delete_event_threat_detection_custom_module': ('name', ), + 'delete_mute_config': ('name', ), + 'delete_notification_config': ('name', ), + 'delete_resource_value_config': ('name', ), + 'delete_security_health_analytics_custom_module': ('name', ), + 'get_big_query_export': ('name', ), + 'get_effective_event_threat_detection_custom_module': ('name', ), + 'get_effective_security_health_analytics_custom_module': ('name', ), + 'get_event_threat_detection_custom_module': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_mute_config': ('name', ), + 'get_notification_config': ('name', ), + 'get_organization_settings': ('name', ), + 'get_resource_value_config': ('name', ), + 'get_security_health_analytics_custom_module': ('name', ), + 'get_simulation': ('name', ), + 'get_source': ('name', ), + 'get_valued_resource': ('name', ), + 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), + 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), + 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_attack_paths': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_big_query_exports': ('parent', 'page_size', 'page_token', ), + 'list_descendant_event_threat_detection_custom_modules': ('parent', 'page_token', 'page_size', ), + 'list_descendant_security_health_analytics_custom_modules': ('parent', 'page_size', 'page_token', ), + 'list_effective_event_threat_detection_custom_modules': ('parent', 'page_token', 'page_size', ), + 'list_effective_security_health_analytics_custom_modules': ('parent', 'page_size', 'page_token', ), + 'list_event_threat_detection_custom_modules': ('parent', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_mute_configs': ('parent', 'page_size', 'page_token', ), + 'list_notification_configs': ('parent', 'page_token', 'page_size', ), + 'list_resource_value_configs': ('parent', 'page_size', 'page_token', ), + 'list_security_health_analytics_custom_modules': ('parent', 'page_size', 'page_token', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'list_valued_resources': ('parent', 'filter', 'page_token', 'page_size', 'order_by', ), + 'run_asset_discovery': ('parent', ), + 'set_finding_state': ('name', 'state', 'start_time', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'set_mute': ('name', 'mute', ), + 'simulate_security_health_analytics_custom_module': ('parent', 'custom_config', 'resource', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_big_query_export': ('big_query_export', 'update_mask', ), + 'update_event_threat_detection_custom_module': ('event_threat_detection_custom_module', 'update_mask', ), + 'update_external_system': ('external_system', 'update_mask', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_mute_config': ('mute_config', 'update_mask', ), + 'update_notification_config': ('notification_config', 'update_mask', ), + 'update_organization_settings': ('organization_settings', 'update_mask', ), + 'update_resource_value_config': ('resource_value_config', 'update_mask', ), + 'update_security_health_analytics_custom_module': ('security_health_analytics_custom_module', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), + 'update_source': ('source', 'update_mask', ), + 'validate_event_threat_detection_custom_module': ('parent', 'raw_text', 'type_', ), + } + + 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=securitycenterCallTransformer(), +): + """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 securitycenter 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-securitycenter/v1/setup.py b/owl-bot-staging/google-cloud-securitycenter/v1/setup.py new file mode 100644 index 000000000000..c4538ec101f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/setup.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. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-securitycenter' + + +description = "Google Cloud Securitycenter API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/securitycenter/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", + "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", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/unit/gapic/securitycenter_v1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_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-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py new file mode 100644 index 000000000000..534cd268c159 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py @@ -0,0 +1,48271 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +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 + +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.securitycenter_v1.services.security_center import SecurityCenterAsyncClient +from google.cloud.securitycenter_v1.services.security_center import SecurityCenterClient +from google.cloud.securitycenter_v1.services.security_center import pagers +from google.cloud.securitycenter_v1.services.security_center import transports +from google.cloud.securitycenter_v1.types import access +from google.cloud.securitycenter_v1.types import application +from google.cloud.securitycenter_v1.types import attack_exposure +from google.cloud.securitycenter_v1.types import attack_path +from google.cloud.securitycenter_v1.types import backup_disaster_recovery +from google.cloud.securitycenter_v1.types import bigquery_export +from google.cloud.securitycenter_v1.types import cloud_armor +from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile +from google.cloud.securitycenter_v1.types import cloud_dlp_inspection +from google.cloud.securitycenter_v1.types import compliance +from google.cloud.securitycenter_v1.types import connection +from google.cloud.securitycenter_v1.types import contact_details +from google.cloud.securitycenter_v1.types import container +from google.cloud.securitycenter_v1.types import database +from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module +from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors +from google.cloud.securitycenter_v1.types import exfiltration +from google.cloud.securitycenter_v1.types import external_system +from google.cloud.securitycenter_v1.types import external_system as gcs_external_system +from google.cloud.securitycenter_v1.types import file +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import group_membership +from google.cloud.securitycenter_v1.types import iam_binding +from google.cloud.securitycenter_v1.types import indicator +from google.cloud.securitycenter_v1.types import kernel_rootkit +from google.cloud.securitycenter_v1.types import kubernetes +from google.cloud.securitycenter_v1.types import label +from google.cloud.securitycenter_v1.types import load_balancer +from google.cloud.securitycenter_v1.types import log_entry +from google.cloud.securitycenter_v1.types import mitre_attack +from google.cloud.securitycenter_v1.types import mute_config +from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v1.types import notebook +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import org_policy +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import process +from google.cloud.securitycenter_v1.types import resource +from google.cloud.securitycenter_v1.types import resource_value_config +from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module +from google.cloud.securitycenter_v1.types import security_marks +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import security_posture +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import simulation +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.cloud.securitycenter_v1.types import toxic_combination +from google.cloud.securitycenter_v1.types import valued_resource +from google.cloud.securitycenter_v1.types import vulnerability +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 duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None + assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SecurityCenterClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SecurityCenterGrpcTransport, "grpc"), + (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + 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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + available_transports = [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterRestTransport, + ] + assert transport in available_transports + + transport = SecurityCenterClient.get_transport_class("grpc") + assert transport == transports.SecurityCenterGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, 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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), +]) +def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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_security_center_client_client_options_from_dict(): + with mock.patch('google.cloud.securitycenter_v1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.BulkMuteFindingsRequest, + dict, +]) +def test_bulk_mute_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BulkMuteFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_bulk_mute_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.bulk_mute_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest() + + +def test_bulk_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.BulkMuteFindingsRequest( + parent='parent_value', + filter='filter_value', + mute_annotation='mute_annotation_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.bulk_mute_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest( + parent='parent_value', + filter='filter_value', + mute_annotation='mute_annotation_value', + ) + +def test_bulk_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc + request = {} + client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest() + +@pytest.mark.asyncio +async def test_bulk_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.bulk_mute_findings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.bulk_mute_findings] = mock_object + + request = {} + await client.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.bulk_mute_findings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_bulk_mute_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BulkMuteFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BulkMuteFindingsRequest() + 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_bulk_mute_findings_async_from_dict(): + await test_bulk_mute_findings_async(request_type=dict) + + +def test_bulk_mute_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BulkMuteFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.bulk_mute_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_bulk_mute_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BulkMuteFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.bulk_mute_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_bulk_mute_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings( + 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_bulk_mute_findings_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_bulk_mute_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings( + 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_bulk_mute_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_create_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + ) + response = client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + + +def test_create_security_health_analytics_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + + +def test_create_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_security_health_analytics_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest( + parent='parent_value', + ) + +def test_create_security_health_analytics_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc + request = {} + client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_security_health_analytics_custom_module(request) + + # Establish that a new wrapper 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_security_health_analytics_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + )) + response = await client.create_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + +@pytest.mark.asyncio +async def test_create_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_security_health_analytics_custom_module] = mock_object + + request = {} + await client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + )) + response = await client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + + +@pytest.mark.asyncio +async def test_create_security_health_analytics_custom_module_async_from_dict(): + await test_create_security_health_analytics_custom_module_async(request_type=dict) + + +def test_create_security_health_analytics_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_security_health_analytics_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + await client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_security_health_analytics_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_security_health_analytics_custom_module( + parent='parent_value', + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + ) + + # Establish that the 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].security_health_analytics_custom_module + mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value') + assert arg == mock_val + + +def test_create_security_health_analytics_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_health_analytics_custom_module( + securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(), + parent='parent_value', + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_security_health_analytics_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_security_health_analytics_custom_module( + parent='parent_value', + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + ) + + # Establish that 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].security_health_analytics_custom_module + mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_security_health_analytics_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_security_health_analytics_custom_module( + securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(), + parent='parent_value', + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_create_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object + + request = {} + await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_create_source_async_from_dict(): + await test_create_source_async(request_type=dict) + + +def test_create_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.create_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.create_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + + +def test_create_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_create_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.create_finding] = mock_rpc + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object + + request = {} + await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_create_finding_async_from_dict(): + await test_create_finding_async(request_type=dict) + + +def test_create_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + arg = args[0].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + + +def test_create_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + arg = args[0].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateMuteConfigRequest, + dict, +]) +def test_create_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + response = client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_create_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest() + + +def test_create_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateMuteConfigRequest( + parent='parent_value', + mute_config_id='mute_config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest( + parent='parent_value', + mute_config_id='mute_config_id_value', + ) + +def test_create_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + request = {} + client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.create_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest() + +@pytest.mark.asyncio +async def test_create_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_mute_config] = mock_object + + request = {} + await client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +@pytest.mark.asyncio +async def test_create_mute_config_async_from_dict(): + await test_create_mute_config_async(request_type=dict) + + +def test_create_mute_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateMuteConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.create_mute_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_mute_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateMuteConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) + await client.create_mute_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_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_mute_config( + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_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].mute_config + mock_val = gcs_mute_config.MuteConfig(name='name_value') + assert arg == mock_val + arg = args[0].mute_config_id + mock_val = 'mute_config_id_value' + assert arg == mock_val + + +def test_create_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_mute_config( + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_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].mute_config + mock_val = gcs_mute_config.MuteConfig(name='name_value') + assert arg == mock_val + arg = args[0].mute_config_id + mock_val = 'mute_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateNotificationConfigRequest, + dict, +]) +def test_create_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_create_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateNotificationConfigRequest( + parent='parent_value', + config_id='config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest( + parent='parent_value', + config_id='config_id_value', + ) + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_create_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_notification_config] = mock_object + + request = {} + await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_create_notification_config_async_from_dict(): + await test_create_notification_config_async(request_type=dict) + + +def test_create_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.create_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.create_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_notification_config( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + # Establish that the 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].config_id + mock_val = 'config_id_value' + assert arg == mock_val + arg = args[0].notification_config + mock_val = gcs_notification_config.NotificationConfig(name='name_value') + assert arg == mock_val + + +def test_create_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_notification_config( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + # Establish that 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].config_id + mock_val = 'config_id_value' + assert arg == mock_val + arg = args[0].notification_config + mock_val = gcs_notification_config.NotificationConfig(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_notification_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteMuteConfigRequest, + dict, +]) +def test_delete_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest() + + +def test_delete_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteMuteConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest( + name='name_value', + ) + +def test_delete_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + request = {} + client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest() + +@pytest.mark.asyncio +async def test_delete_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_mute_config] = mock_object + + request = {} + await client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteMuteConfigRequest() + 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_mute_config_async_from_dict(): + await test_delete_mute_config_async(request_type=dict) + + +def test_delete_mute_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteMuteConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value = None + client.delete_mute_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_mute_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteMuteConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_mute_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_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, +]) +def test_delete_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteNotificationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest( + name='name_value', + ) + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_delete_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_notification_config] = mock_object + + request = {} + await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteNotificationConfigRequest() + 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_config_async_from_dict(): + await test_delete_notification_config_async(request_type=dict) + + +def test_delete_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = None + client.delete_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_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_notification_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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_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_notification_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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_notification_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_delete_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_security_health_analytics_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + + +def test_delete_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_security_health_analytics_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest( + name='name_value', + ) + +def test_delete_security_health_analytics_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc + request = {} + client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_security_health_analytics_custom_module(request) + + # Establish that a new wrapper 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_security_health_analytics_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + +@pytest.mark.asyncio +async def test_delete_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_security_health_analytics_custom_module] = mock_object + + request = {} + await client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + 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_security_health_analytics_custom_module_async_from_dict(): + await test_delete_security_health_analytics_custom_module_async(request_type=dict) + + +def test_delete_security_health_analytics_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = None + client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_security_health_analytics_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_security_health_analytics_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__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_security_health_analytics_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_security_health_analytics_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_health_analytics_custom_module( + securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_security_health_analytics_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_health_analytics_custom_module), + '__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_security_health_analytics_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_security_health_analytics_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_security_health_analytics_custom_module( + securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSimulationRequest, + dict, +]) +def test_get_simulation(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + response = client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSimulationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == 'name_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +def test_get_simulation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_simulation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest() + + +def test_get_simulation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSimulationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_simulation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest( + name='name_value', + ) + +def test_get_simulation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_simulation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc + request = {} + client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_simulation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_simulation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_simulation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest() + +@pytest.mark.asyncio +async def test_get_simulation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_simulation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_simulation] = mock_object + + request = {} + await client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_simulation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_simulation_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSimulationRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSimulationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == 'name_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +@pytest.mark.asyncio +async def test_get_simulation_async_from_dict(): + await test_get_simulation_async(request_type=dict) + + +def test_get_simulation_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSimulationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value = simulation.Simulation() + client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_simulation_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSimulationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) + await client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_simulation_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_simulation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_simulation_flattened_error(): + client = SecurityCenterClient( + credentials=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_simulation( + securitycenter_service.GetSimulationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_simulation_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_simulation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_simulation_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_simulation( + securitycenter_service.GetSimulationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetValuedResourceRequest, + dict, +]) +def test_get_valued_resource(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + ) + response = client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetValuedResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == 'name_value' + assert response.resource == 'resource_value' + assert response.resource_type == 'resource_type_value' + assert response.display_name == 'display_name_value' + assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + + +def test_get_valued_resource_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_valued_resource() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest() + + +def test_get_valued_resource_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetValuedResourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_valued_resource(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest( + name='name_value', + ) + +def test_get_valued_resource_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_valued_resource in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc + request = {} + client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_valued_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_valued_resource_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + )) + response = await client.get_valued_resource() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest() + +@pytest.mark.asyncio +async def test_get_valued_resource_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_valued_resource in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_valued_resource] = mock_object + + request = {} + await client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_valued_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_valued_resource_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetValuedResourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + )) + response = await client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetValuedResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == 'name_value' + assert response.resource == 'resource_value' + assert response.resource_type == 'resource_type_value' + assert response.display_name == 'display_name_value' + assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + + +@pytest.mark.asyncio +async def test_get_valued_resource_async_from_dict(): + await test_get_valued_resource_async(request_type=dict) + + +def test_get_valued_resource_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetValuedResourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value = valued_resource.ValuedResource() + client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_valued_resource_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetValuedResourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) + await client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_valued_resource_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_valued_resource( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_valued_resource_flattened_error(): + client = SecurityCenterClient( + credentials=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_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_valued_resource_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_valued_resource( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_valued_resource_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetBigQueryExportRequest, + dict, +]) +def test_get_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + response = client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +def test_get_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest() + + +def test_get_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetBigQueryExportRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest( + name='name_value', + ) + +def test_get_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc + request = {} + client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.get_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_get_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_big_query_export] = mock_object + + request = {} + await client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +@pytest.mark.asyncio +async def test_get_big_query_export_async_from_dict(): + await test_get_big_query_export_async(request_type=dict) + + +def test_get_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value = bigquery_export.BigQueryExport() + client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + await client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.GetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest( + resource='resource_value', + ) + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object + + request = {} + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetMuteConfigRequest, + dict, +]) +def test_get_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + ) + response = client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_get_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest() + + +def test_get_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetMuteConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest( + name='name_value', + ) + +def test_get_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_mute_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_mute_config] = mock_rpc + request = {} + client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.get_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest() + +@pytest.mark.asyncio +async def test_get_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_mute_config] = mock_object + + request = {} + await client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC + + +@pytest.mark.asyncio +async def test_get_mute_config_async_from_dict(): + await test_get_mute_config_async(request_type=dict) + + +def test_get_mute_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetMuteConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value = mute_config.MuteConfig() + client.get_mute_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_mute_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetMuteConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig()) + await client.get_mute_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_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_mute_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_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_mute_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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetNotificationConfigRequest, + dict, +]) +def test_get_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_get_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetNotificationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest( + name='name_value', + ) + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_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_notification_config] = mock_rpc + request = {} + client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_get_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_notification_config] = mock_object + + request = {} + await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_get_notification_config_async_from_dict(): + await test_get_notification_config_async(request_type=dict) + + +def test_get_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = notification_config.NotificationConfig() + client.get_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + await client.get_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_notification_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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_notification_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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_notification_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetOrganizationSettingsRequest, + dict, +]) +def test_get_organization_settings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_get_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetOrganizationSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_organization_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest( + name='name_value', + ) + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_organization_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_organization_settings] = mock_rpc + request = {} + client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_organization_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_organization_settings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + +@pytest.mark.asyncio +async def test_get_organization_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_organization_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_organization_settings] = mock_object + + request = {} + await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_organization_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_get_organization_settings_async_from_dict(): + await test_get_organization_settings_async(request_type=dict) + + +def test_get_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = organization_settings.OrganizationSettings() + client.get_organization_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_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + await client.get_organization_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_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_organization_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_organization_settings_flattened_error(): + client = SecurityCenterClient( + credentials=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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_organization_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_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_get_effective_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( + name='name_value', + enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + display_name='display_name_value', + ) + response = client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.enablement_state == effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.display_name == 'display_name_value' + + +def test_get_effective_security_health_analytics_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_effective_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + + +def test_get_effective_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_effective_security_health_analytics_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( + name='name_value', + ) + +def test_get_effective_security_health_analytics_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_effective_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_effective_security_health_analytics_custom_module] = mock_rpc + request = {} + client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_effective_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_effective_security_health_analytics_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( + name='name_value', + enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + display_name='display_name_value', + )) + response = await client.get_effective_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + +@pytest.mark.asyncio +async def test_get_effective_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_effective_security_health_analytics_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_effective_security_health_analytics_custom_module] = mock_object + + request = {} + await client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_effective_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_effective_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( + name='name_value', + enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + display_name='display_name_value', + )) + response = await client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.enablement_state == effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_get_effective_security_health_analytics_custom_module_async_from_dict(): + await test_get_effective_security_health_analytics_custom_module_async(request_type=dict) + + +def test_get_effective_security_health_analytics_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_effective_security_health_analytics_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule()) + await client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_effective_security_health_analytics_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_effective_security_health_analytics_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_effective_security_health_analytics_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_effective_security_health_analytics_custom_module( + securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_effective_security_health_analytics_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_effective_security_health_analytics_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_effective_security_health_analytics_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_effective_security_health_analytics_custom_module( + securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_get_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + ) + response = client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + + +def test_get_security_health_analytics_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + + +def test_get_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_security_health_analytics_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest( + name='name_value', + ) + +def test_get_security_health_analytics_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_security_health_analytics_custom_module] = mock_rpc + request = {} + client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_security_health_analytics_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + )) + response = await client.get_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + +@pytest.mark.asyncio +async def test_get_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_security_health_analytics_custom_module] = mock_object + + request = {} + await client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + )) + response = await client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + + +@pytest.mark.asyncio +async def test_get_security_health_analytics_custom_module_async_from_dict(): + await test_get_security_health_analytics_custom_module_async(request_type=dict) + + +def test_get_security_health_analytics_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_security_health_analytics_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + await client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_security_health_analytics_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_security_health_analytics_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_security_health_analytics_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_health_analytics_custom_module( + securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_security_health_analytics_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_security_health_analytics_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_security_health_analytics_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_security_health_analytics_custom_module( + securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_get_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest( + name='name_value', + ) + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + +@pytest.mark.asyncio +async def test_get_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object + + request = {} + await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_get_source_async_from_dict(): + await test_get_source_async(request_type=dict) + + +def test_get_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = source.Source() + client.get_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + await client.get_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_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_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupAssetsRequest, + dict, +]) +def test_group_assets(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_assets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + +def test_group_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupAssetsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc + request = {} + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_group_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + +@pytest.mark.asyncio +async def test_group_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_assets] = mock_object + + request = {} + await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_assets_async_from_dict(): + await test_group_assets_async(request_type=dict) + + +def test_group_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = securitycenter_service.GroupAssetsResponse() + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_group_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) + await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_group_assets_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_assets(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, securitycenter_service.GroupResult) + for i in results) +def test_group_assets_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_assets(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_group_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_assets(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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_assets(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", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + +@pytest.mark.asyncio +async def test_group_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_findings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object + + request = {} + await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_findings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_findings_async_from_dict(): + await test_group_findings_async(request_type=dict) + + +def test_group_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = securitycenter_service.GroupFindingsResponse() + client.group_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_group_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + await client.group_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_group_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that the 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + + +def test_group_findings_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + +@pytest.mark.asyncio +async def test_group_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_group_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_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, securitycenter_service.GroupResult) + for i in results) +def test_group_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_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_group_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_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", [ + securitycenter_service.ListAssetsRequest, + dict, +]) +def test_list_assets(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_assets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + +def test_list_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListAssetsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_value', + page_token='page_token_value', + ) + +def test_list_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + +@pytest.mark.asyncio +async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object + + request = {} + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + + +def test_list_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = securitycenter_service.ListAssetsResponse() + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_assets_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) +def test_list_assets_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(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_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + 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_assets(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", [ + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, + dict, +]) +def test_list_descendant_security_health_analytics_custom_modules(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_descendant_security_health_analytics_custom_modules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_descendant_security_health_analytics_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + + +def test_list_descendant_security_health_analytics_custom_modules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( + 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_descendant_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_descendant_security_health_analytics_custom_modules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_descendant_security_health_analytics_custom_modules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_descendant_security_health_analytics_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_descendant_security_health_analytics_custom_modules] = mock_rpc + request = {} + client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_descendant_security_health_analytics_custom_modules_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_descendant_security_health_analytics_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + +@pytest.mark.asyncio +async def test_list_descendant_security_health_analytics_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_descendant_security_health_analytics_custom_modules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_descendant_security_health_analytics_custom_modules] = mock_object + + request = {} + await client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_descendant_security_health_analytics_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_descendant_security_health_analytics_custom_modules_async_from_dict(): + await test_list_descendant_security_health_analytics_custom_modules_async(request_type=dict) + + +def test_list_descendant_security_health_analytics_custom_modules_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_descendant_security_health_analytics_custom_modules_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse()) + await client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_descendant_security_health_analytics_custom_modules_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_descendant_security_health_analytics_custom_modules( + 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_descendant_security_health_analytics_custom_modules_flattened_error(): + client = SecurityCenterClient( + credentials=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_descendant_security_health_analytics_custom_modules( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_descendant_security_health_analytics_custom_modules_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_descendant_security_health_analytics_custom_modules( + 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_descendant_security_health_analytics_custom_modules_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_descendant_security_health_analytics_custom_modules( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_descendant_security_health_analytics_custom_modules_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_descendant_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + for i in results) +def test_list_descendant_security_health_analytics_custom_modules_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_descendant_security_health_analytics_custom_modules(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_descendant_security_health_analytics_custom_modules_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_descendant_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_descendant_security_health_analytics_custom_modules_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_security_health_analytics_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + 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_descendant_security_health_analytics_custom_modules(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", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +def test_list_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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] == securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + +@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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object + + request = {} + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +@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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in results) +def test_list_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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 = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_findings_async_pages(): + client = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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", [ + securitycenter_service.ListMuteConfigsRequest, + dict, +]) +def test_list_mute_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListMuteConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_mute_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_mute_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest() + + +def test_list_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListMuteConfigsRequest( + 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_mute_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_mute_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_mute_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_mute_configs] = mock_rpc + request = {} + client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_mute_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_mute_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_mute_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest() + +@pytest.mark.asyncio +async def test_list_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_mute_configs] = mock_object + + request = {} + await client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_mute_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_mute_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListMuteConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListMuteConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_mute_configs_async_from_dict(): + await test_list_mute_configs_async(request_type=dict) + + +def test_list_mute_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListMuteConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListMuteConfigsResponse() + client.list_mute_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_mute_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListMuteConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse()) + await client.list_mute_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_mute_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_mute_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_mute_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_mute_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_mute_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_mute_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent='parent_value', + ) + + +def test_list_mute_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_mute_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, mute_config.MuteConfig) + for i in results) +def test_list_mute_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_mute_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_mute_configs_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_mute_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, mute_config.MuteConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_mute_configs_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + 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_mute_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", [ + securitycenter_service.ListNotificationConfigsRequest, + dict, +]) +def test_list_notification_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListNotificationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_notification_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListNotificationConfigsRequest( + 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_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notification_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_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_notification_configs] = mock_rpc + request = {} + client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_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_notification_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + +@pytest.mark.asyncio +async def test_list_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_notification_configs] = mock_object + + request = {} + await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_notification_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListNotificationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_from_dict(): + await test_list_notification_configs_async(request_type=dict) + + +def test_list_notification_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + 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_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + client.list_notification_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_notification_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + 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_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + await client.list_notification_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_notification_configs_flattened(): + client = SecurityCenterClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_notification_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_notification_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_notification_configs_flattened_async(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_notification_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_notification_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_notification_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + 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_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, notification_config.NotificationConfig) + for i in results) +def test_list_notification_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_notification_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_notification_configs_async_pager(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_notification_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, notification_config.NotificationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_pages(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + 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_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", [ + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, + dict, +]) +def test_list_effective_security_health_analytics_custom_modules(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_effective_security_health_analytics_custom_modules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_effective_security_health_analytics_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + + +def test_list_effective_security_health_analytics_custom_modules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( + 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_effective_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_effective_security_health_analytics_custom_modules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_effective_security_health_analytics_custom_modules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_effective_security_health_analytics_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_effective_security_health_analytics_custom_modules] = mock_rpc + request = {} + client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_effective_security_health_analytics_custom_modules_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_effective_security_health_analytics_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + +@pytest.mark.asyncio +async def test_list_effective_security_health_analytics_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_effective_security_health_analytics_custom_modules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_effective_security_health_analytics_custom_modules] = mock_object + + request = {} + await client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_effective_security_health_analytics_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_effective_security_health_analytics_custom_modules_async_from_dict(): + await test_list_effective_security_health_analytics_custom_modules_async(request_type=dict) + + +def test_list_effective_security_health_analytics_custom_modules_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_effective_security_health_analytics_custom_modules_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse()) + await client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_effective_security_health_analytics_custom_modules_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_effective_security_health_analytics_custom_modules( + 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_effective_security_health_analytics_custom_modules_flattened_error(): + client = SecurityCenterClient( + credentials=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_effective_security_health_analytics_custom_modules( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_effective_security_health_analytics_custom_modules_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_effective_security_health_analytics_custom_modules( + 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_effective_security_health_analytics_custom_modules_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_effective_security_health_analytics_custom_modules( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_effective_security_health_analytics_custom_modules_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_effective_security_health_analytics_custom_modules(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, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) + for i in results) +def test_list_effective_security_health_analytics_custom_modules_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_effective_security_health_analytics_custom_modules(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_effective_security_health_analytics_custom_modules_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_effective_security_health_analytics_custom_modules(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, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_effective_security_health_analytics_custom_modules_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_security_health_analytics_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + ), + 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_effective_security_health_analytics_custom_modules(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", [ + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, + dict, +]) +def test_list_security_health_analytics_custom_modules(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecurityHealthAnalyticsCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_security_health_analytics_custom_modules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_security_health_analytics_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + + +def test_list_security_health_analytics_custom_modules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest( + 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_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_security_health_analytics_custom_modules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_security_health_analytics_custom_modules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_security_health_analytics_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_security_health_analytics_custom_modules] = mock_rpc + request = {} + client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_security_health_analytics_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_security_health_analytics_custom_modules_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_security_health_analytics_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + +@pytest.mark.asyncio +async def test_list_security_health_analytics_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_health_analytics_custom_modules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_security_health_analytics_custom_modules] = mock_object + + request = {} + await client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_security_health_analytics_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_security_health_analytics_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_security_health_analytics_custom_modules_async_from_dict(): + await test_list_security_health_analytics_custom_modules_async(request_type=dict) + + +def test_list_security_health_analytics_custom_modules_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_security_health_analytics_custom_modules_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse()) + await client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_security_health_analytics_custom_modules_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_security_health_analytics_custom_modules( + 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_security_health_analytics_custom_modules_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_health_analytics_custom_modules( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_security_health_analytics_custom_modules_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_security_health_analytics_custom_modules( + 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_security_health_analytics_custom_modules_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_security_health_analytics_custom_modules( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_security_health_analytics_custom_modules_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + for i in results) +def test_list_security_health_analytics_custom_modules_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_security_health_analytics_custom_modules(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_security_health_analytics_custom_modules_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_security_health_analytics_custom_modules_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_health_analytics_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + 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_security_health_analytics_custom_modules(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", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListSourcesRequest( + 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_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + +@pytest.mark.asyncio +async def test_list_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_sources in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object + + request = {} + await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_sources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sources_async_from_dict(): + await test_list_sources_async(request_type=dict) + + +def test_list_sources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = securitycenter_service.ListSourcesResponse() + client.list_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_sources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + await client.list_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_sources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_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_sources_flattened_error(): + client = SecurityCenterClient( + credentials=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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_sources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_sources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_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, source.Source) + for i in results) +def test_list_sources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = list(client.list_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_sources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_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, source.Source) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_sources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + 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_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", [ + securitycenter_service.RunAssetDiscoveryRequest, + dict, +]) +def test_run_asset_discovery(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.RunAssetDiscoveryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_asset_discovery_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + +def test_run_asset_discovery_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.RunAssetDiscoveryRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_asset_discovery(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest( + parent='parent_value', + ) + +def test_run_asset_discovery_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_asset_discovery in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc + request = {} + client.run_asset_discovery(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.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_run_asset_discovery_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + +@pytest.mark.asyncio +async def test_run_asset_discovery_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.run_asset_discovery in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.run_asset_discovery] = mock_object + + request = {} + await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.RunAssetDiscoveryRequest() + 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_run_asset_discovery_async_from_dict(): + await test_run_asset_discovery_async(request_type=dict) + + +def test_run_asset_discovery_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_asset_discovery_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_run_asset_discovery_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery( + 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_run_asset_discovery_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_run_asset_discovery_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery( + 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_run_asset_discovery_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_set_finding_state_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + +@pytest.mark.asyncio +async def test_set_finding_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object + + request = {} + await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_finding_state(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_set_finding_state_async_from_dict(): + await test_set_finding_state_async(request_type=dict) + + +def test_set_finding_state_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = finding.Finding() + client.set_finding_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_set_finding_state_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_finding_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_set_finding_state_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetMuteRequest, + dict, +]) +def test_set_mute(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetMuteRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_set_mute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_mute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest() + + +def test_set_mute_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SetMuteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_mute(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest( + name='name_value', + ) + +def test_set_mute_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_mute in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc + request = {} + client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_mute(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_set_mute_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_mute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest() + +@pytest.mark.asyncio +async def test_set_mute_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_mute in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_mute] = mock_object + + request = {} + await client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_mute(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_mute_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetMuteRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetMuteRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_set_mute_async_from_dict(): + await test_set_mute_async(request_type=dict) + + +def test_set_mute_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetMuteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value = finding.Finding() + client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_mute_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetMuteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_set_mute_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__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.set_mute( + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].mute + mock_val = finding.Finding.Mute.MUTED + assert arg == mock_val + + +def test_set_mute_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_mute( + securitycenter_service.SetMuteRequest(), + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + +@pytest.mark.asyncio +async def test_set_mute_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__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.set_mute( + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].mute + mock_val = finding.Finding.Mute.MUTED + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_mute_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_mute( + securitycenter_service.SetMuteRequest(), + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.SetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest( + resource='resource_value', + ) + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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( + version=774, + etag=b'etag_blob', + )) + response = await client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object + + request = {} + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = SecurityCenterClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.TestIamPermissionsRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( + resource='resource_value', + ) + +def test_test_iam_permissions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object + + request = {} + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_simulate_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( + ) + response = client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) + + +def test_simulate_security_health_analytics_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.simulate_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + + +def test_simulate_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.simulate_security_health_analytics_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest( + parent='parent_value', + ) + +def test_simulate_security_health_analytics_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.simulate_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.simulate_security_health_analytics_custom_module] = mock_rpc + request = {} + client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.simulate_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( + )) + response = await client.simulate_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.simulate_security_health_analytics_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.simulate_security_health_analytics_custom_module] = mock_object + + request = {} + await client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.simulate_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( + )) + response = await client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) + + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_async_from_dict(): + await test_simulate_security_health_analytics_custom_module_async(request_type=dict) + + +def test_simulate_security_health_analytics_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse()) + await client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_simulate_security_health_analytics_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.simulate_security_health_analytics_custom_module( + parent='parent_value', + custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), + resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), + ) + + # Establish that the 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].custom_config + mock_val = security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')) + assert arg == mock_val + arg = args[0].resource + mock_val = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value') + assert arg == mock_val + + +def test_simulate_security_health_analytics_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.simulate_security_health_analytics_custom_module( + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(), + parent='parent_value', + custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), + resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), + ) + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.simulate_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.simulate_security_health_analytics_custom_module( + parent='parent_value', + custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), + resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), + ) + + # Establish that 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].custom_config + mock_val = security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')) + assert arg == mock_val + arg = args[0].resource + mock_val = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_simulate_security_health_analytics_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.simulate_security_health_analytics_custom_module( + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(), + parent='parent_value', + custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), + resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateExternalSystemRequest, + dict, +]) +def test_update_external_system(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + ) + response = client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateExternalSystemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == 'name_value' + assert response.assignees == ['assignees_value'] + assert response.external_uid == 'external_uid_value' + assert response.status == 'status_value' + assert response.case_uri == 'case_uri_value' + assert response.case_priority == 'case_priority_value' + + +def test_update_external_system_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_external_system() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest() + + +def test_update_external_system_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateExternalSystemRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_external_system(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest( + ) + +def test_update_external_system_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_external_system in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc + request = {} + client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_external_system(request) + + # Establish that a new wrapper 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_external_system_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + )) + response = await client.update_external_system() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest() + +@pytest.mark.asyncio +async def test_update_external_system_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_external_system in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_external_system] = mock_object + + request = {} + await client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_external_system(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_external_system_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateExternalSystemRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + )) + response = await client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateExternalSystemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == 'name_value' + assert response.assignees == ['assignees_value'] + assert response.external_uid == 'external_uid_value' + assert response.status == 'status_value' + assert response.case_uri == 'case_uri_value' + assert response.case_priority == 'case_priority_value' + + +@pytest.mark.asyncio +async def test_update_external_system_async_from_dict(): + await test_update_external_system_async(request_type=dict) + + +def test_update_external_system_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateExternalSystemRequest() + + request.external_system.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value = gcs_external_system.ExternalSystem() + client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'external_system.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_external_system_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateExternalSystemRequest() + + request.external_system.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) + await client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'external_system.name=name_value', + ) in kw['metadata'] + + +def test_update_external_system_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_external_system( + external_system=gcs_external_system.ExternalSystem(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].external_system + mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error(): + client = SecurityCenterClient( + credentials=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_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_external_system_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_external_system( + external_system=gcs_external_system.ExternalSystem(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].external_system + mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_update_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateFindingRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.update_finding] = mock_rpc + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object + + request = {} + await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_update_finding_async_from_dict(): + await test_update_finding_async(request_type=dict) + + +def test_update_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +def test_update_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_finding( + finding=gcs_finding.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].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + + +def test_update_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_finding( + finding=gcs_finding.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].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateMuteConfigRequest, + dict, +]) +def test_update_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + response = client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_update_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest() + + +def test_update_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateMuteConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest( + ) + +def test_update_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + request = {} + client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.update_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest() + +@pytest.mark.asyncio +async def test_update_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_mute_config] = mock_object + + request = {} + await client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +@pytest.mark.asyncio +async def test_update_mute_config_async_from_dict(): + await test_update_mute_config_async(request_type=dict) + + +def test_update_mute_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateMuteConfigRequest() + + request.mute_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.update_mute_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', + 'mute_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_mute_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateMuteConfigRequest() + + request.mute_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) + await client.update_mute_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', + 'mute_config.name=name_value', + ) in kw['metadata'] + + +def test_update_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_mute_config( + mute_config=gcs_mute_config.MuteConfig(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].mute_config + mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_mute_config( + mute_config=gcs_mute_config.MuteConfig(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].mute_config + mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, +]) +def test_update_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_update_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateNotificationConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest( + ) + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_update_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_notification_config] = mock_object + + request = {} + await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_update_notification_config_async_from_dict(): + await test_update_notification_config_async(request_type=dict) + + +def test_update_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.update_notification_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', + 'notification_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.update_notification_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', + 'notification_config.name=name_value', + ) in kw['metadata'] + + +def test_update_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_notification_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateOrganizationSettingsRequest, + dict, +]) +def test_update_organization_settings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_update_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateOrganizationSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_organization_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest( + ) + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_organization_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_organization_settings] = mock_rpc + request = {} + client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_organization_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_organization_settings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + +@pytest.mark.asyncio +async def test_update_organization_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_organization_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_organization_settings] = mock_object + + request = {} + await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_organization_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_update_organization_settings_async_from_dict(): + await test_update_organization_settings_async(request_type=dict) + + +def test_update_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = gcs_organization_settings.OrganizationSettings() + client.update_organization_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', + 'organization_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + await client.update_organization_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', + 'organization_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].organization_settings + mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') + assert arg == mock_val + + +def test_update_organization_settings_flattened_error(): + client = SecurityCenterClient( + credentials=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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].organization_settings + mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_update_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + ) + response = client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + + +def test_update_security_health_analytics_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + + +def test_update_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_health_analytics_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest( + ) + +def test_update_security_health_analytics_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_health_analytics_custom_module] = mock_rpc + request = {} + client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_health_analytics_custom_module(request) + + # Establish that a new wrapper 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_security_health_analytics_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + )) + response = await client.update_security_health_analytics_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + +@pytest.mark.asyncio +async def test_update_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_security_health_analytics_custom_module] = mock_object + + request = {} + await client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + )) + response = await client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + + +@pytest.mark.asyncio +async def test_update_security_health_analytics_custom_module_async_from_dict(): + await test_update_security_health_analytics_custom_module_async(request_type=dict) + + +def test_update_security_health_analytics_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + + request.security_health_analytics_custom_module.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_health_analytics_custom_module.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_health_analytics_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + + request.security_health_analytics_custom_module.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + await client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_health_analytics_custom_module.name=name_value', + ) in kw['metadata'] + + +def test_update_security_health_analytics_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_health_analytics_custom_module( + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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].security_health_analytics_custom_module + mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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_security_health_analytics_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_health_analytics_custom_module( + securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(), + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_security_health_analytics_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_health_analytics_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_health_analytics_custom_module( + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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].security_health_analytics_custom_module + mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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_security_health_analytics_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_security_health_analytics_custom_module( + securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(), + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSourceRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object + + request = {} + await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_source_async_from_dict(): + await test_update_source_async(request_type=dict) + + +def test_update_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +def test_update_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_source( + source=gcs_source.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].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + + +def test_update_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_source( + source=gcs_source.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].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + response = client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_security_marks_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + +def test_update_security_marks_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSecurityMarksRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( + ) + +def test_update_security_marks_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish that a new wrapper 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_security_marks_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + +@pytest.mark.asyncio +async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_marks in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object + + request = {} + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_security_marks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_security_marks_async_from_dict(): + await test_update_security_marks_async(request_type=dict) + + +def test_update_security_marks_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = gcs_security_marks.SecurityMarks() + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_marks_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +def test_update_security_marks_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].security_marks + mock_val = gcs_security_marks.SecurityMarks(name='name_value') + assert arg == mock_val + + +def test_update_security_marks_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].security_marks + mock_val = gcs_security_marks.SecurityMarks(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateBigQueryExportRequest, + dict, +]) +def test_create_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + response = client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +def test_create_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest() + + +def test_create_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateBigQueryExportRequest( + parent='parent_value', + big_query_export_id='big_query_export_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest( + parent='parent_value', + big_query_export_id='big_query_export_id_value', + ) + +def test_create_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + request = {} + client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_big_query_export(request) + + # Establish that a new wrapper 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_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.create_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_create_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_big_query_export] = mock_object + + request = {} + await client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +@pytest.mark.asyncio +async def test_create_big_query_export_async_from_dict(): + await test_create_big_query_export_async(request_type=dict) + + +def test_create_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateBigQueryExportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value = bigquery_export.BigQueryExport() + client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateBigQueryExportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + await client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_big_query_export( + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_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].big_query_export + mock_val = bigquery_export.BigQueryExport(name='name_value') + assert arg == mock_val + arg = args[0].big_query_export_id + mock_val = 'big_query_export_id_value' + assert arg == mock_val + + +def test_create_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_id_value', + ) + +@pytest.mark.asyncio +async def test_create_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_big_query_export( + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_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].big_query_export + mock_val = bigquery_export.BigQueryExport(name='name_value') + assert arg == mock_val + arg = args[0].big_query_export_id + mock_val = 'big_query_export_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteBigQueryExportRequest, + dict, +]) +def test_delete_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() + + +def test_delete_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteBigQueryExportRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest( + name='name_value', + ) + +def test_delete_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + request = {} + client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_big_query_export(request) + + # Establish that a new wrapper 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_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_delete_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_big_query_export] = mock_object + + request = {} + await client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteBigQueryExportRequest() + 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_big_query_export_async_from_dict(): + await test_delete_big_query_export_async(request_type=dict) + + +def test_delete_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value = None + client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__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_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__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_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateBigQueryExportRequest, + dict, +]) +def test_update_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + response = client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +def test_update_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() + + +def test_update_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateBigQueryExportRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest( + ) + +def test_update_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc + request = {} + client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_big_query_export(request) + + # Establish that a new wrapper 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_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.update_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_update_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_big_query_export] = mock_object + + request = {} + await client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +@pytest.mark.asyncio +async def test_update_big_query_export_async_from_dict(): + await test_update_big_query_export_async(request_type=dict) + + +def test_update_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateBigQueryExportRequest() + + request.big_query_export.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value = bigquery_export.BigQueryExport() + client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'big_query_export.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateBigQueryExportRequest() + + request.big_query_export.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + await client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'big_query_export.name=name_value', + ) in kw['metadata'] + + +def test_update_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_big_query_export( + big_query_export=bigquery_export.BigQueryExport(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].big_query_export + mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_big_query_export( + big_query_export=bigquery_export.BigQueryExport(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].big_query_export + mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListBigQueryExportsRequest, + dict, +]) +def test_list_big_query_exports(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListBigQueryExportsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_big_query_exports_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_big_query_exports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest() + + +def test_list_big_query_exports_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListBigQueryExportsRequest( + 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_big_query_exports), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_big_query_exports(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_big_query_exports_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_big_query_exports in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc + request = {} + client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_big_query_exports(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_big_query_exports_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_big_query_exports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest() + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_exports in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_big_query_exports] = mock_object + + request = {} + await client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_big_query_exports(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_big_query_exports_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListBigQueryExportsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListBigQueryExportsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_from_dict(): + await test_list_big_query_exports_async(request_type=dict) + + +def test_list_big_query_exports_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListBigQueryExportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_exports_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListBigQueryExportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) + await client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_exports_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_big_query_exports( + 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_big_query_exports_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_big_query_exports_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_big_query_exports( + 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_big_query_exports_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent='parent_value', + ) + + +def test_list_big_query_exports_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_big_query_exports(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, bigquery_export.BigQueryExport) + for i in results) +def test_list_big_query_exports_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + pages = list(client.list_big_query_exports(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_big_query_exports_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_big_query_exports(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, bigquery_export.BigQueryExport) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + 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_big_query_exports(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", [ + securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_create_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + ) + response = client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + + +def test_create_event_threat_detection_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + + +def test_create_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_event_threat_detection_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateEventThreatDetectionCustomModuleRequest( + parent='parent_value', + ) + +def test_create_event_threat_detection_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc + request = {} + client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_event_threat_detection_custom_module(request) + + # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + )) + response = await client.create_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + +@pytest.mark.asyncio +async def test_create_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_event_threat_detection_custom_module] = mock_object + + request = {} + await client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + )) + response = await client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + + +@pytest.mark.asyncio +async def test_create_event_threat_detection_custom_module_async_from_dict(): + await test_create_event_threat_detection_custom_module_async(request_type=dict) + + +def test_create_event_threat_detection_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_event_threat_detection_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + await client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_event_threat_detection_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_event_threat_detection_custom_module( + parent='parent_value', + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + ) + + # Establish that the 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].event_threat_detection_custom_module + mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value') + assert arg == mock_val + + +def test_create_event_threat_detection_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_event_threat_detection_custom_module( + securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(), + parent='parent_value', + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_event_threat_detection_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_event_threat_detection_custom_module( + parent='parent_value', + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + ) + + # Establish that 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].event_threat_detection_custom_module + mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_event_threat_detection_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_event_threat_detection_custom_module( + securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(), + parent='parent_value', + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_delete_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_event_threat_detection_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + + +def test_delete_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_event_threat_detection_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest( + name='name_value', + ) + +def test_delete_event_threat_detection_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc + request = {} + client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_event_threat_detection_custom_module(request) + + # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + +@pytest.mark.asyncio +async def test_delete_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_event_threat_detection_custom_module] = mock_object + + request = {} + await client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + 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_event_threat_detection_custom_module_async_from_dict(): + await test_delete_event_threat_detection_custom_module_async(request_type=dict) + + +def test_delete_event_threat_detection_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = None + client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_event_threat_detection_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_event_threat_detection_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__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_event_threat_detection_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_event_threat_detection_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_event_threat_detection_custom_module( + securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_event_threat_detection_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_threat_detection_custom_module), + '__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_event_threat_detection_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_event_threat_detection_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_event_threat_detection_custom_module( + securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_get_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + ) + response = client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + + +def test_get_event_threat_detection_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + + +def test_get_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_event_threat_detection_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEventThreatDetectionCustomModuleRequest( + name='name_value', + ) + +def test_get_event_threat_detection_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_event_threat_detection_custom_module] = mock_rpc + request = {} + client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_event_threat_detection_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + )) + response = await client.get_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + +@pytest.mark.asyncio +async def test_get_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_event_threat_detection_custom_module] = mock_object + + request = {} + await client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetEventThreatDetectionCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + )) + response = await client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + + +@pytest.mark.asyncio +async def test_get_event_threat_detection_custom_module_async_from_dict(): + await test_get_event_threat_detection_custom_module_async(request_type=dict) + + +def test_get_event_threat_detection_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_event_threat_detection_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + await client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_event_threat_detection_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_event_threat_detection_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_event_threat_detection_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_event_threat_detection_custom_module( + securitycenter_service.GetEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_event_threat_detection_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_event_threat_detection_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_event_threat_detection_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_event_threat_detection_custom_module( + securitycenter_service.GetEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, + dict, +]) +def test_list_descendant_event_threat_detection_custom_modules(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDescendantEventThreatDetectionCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_descendant_event_threat_detection_custom_modules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_descendant_event_threat_detection_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + + +def test_list_descendant_event_threat_detection_custom_modules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest( + 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_descendant_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_descendant_event_threat_detection_custom_modules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_descendant_event_threat_detection_custom_modules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_descendant_event_threat_detection_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_descendant_event_threat_detection_custom_modules] = mock_rpc + request = {} + client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_descendant_event_threat_detection_custom_modules_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_descendant_event_threat_detection_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + +@pytest.mark.asyncio +async def test_list_descendant_event_threat_detection_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_descendant_event_threat_detection_custom_modules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_descendant_event_threat_detection_custom_modules] = mock_object + + request = {} + await client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_descendant_event_threat_detection_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_descendant_event_threat_detection_custom_modules_async_from_dict(): + await test_list_descendant_event_threat_detection_custom_modules_async(request_type=dict) + + +def test_list_descendant_event_threat_detection_custom_modules_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_descendant_event_threat_detection_custom_modules_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse()) + await client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_descendant_event_threat_detection_custom_modules_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_descendant_event_threat_detection_custom_modules( + 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_descendant_event_threat_detection_custom_modules_flattened_error(): + client = SecurityCenterClient( + credentials=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_descendant_event_threat_detection_custom_modules( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_descendant_event_threat_detection_custom_modules_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_descendant_event_threat_detection_custom_modules( + 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_descendant_event_threat_detection_custom_modules_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_descendant_event_threat_detection_custom_modules( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_descendant_event_threat_detection_custom_modules_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_descendant_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + for i in results) +def test_list_descendant_event_threat_detection_custom_modules_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_descendant_event_threat_detection_custom_modules(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_descendant_event_threat_detection_custom_modules_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_descendant_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_descendant_event_threat_detection_custom_modules_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_descendant_event_threat_detection_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + 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_descendant_event_threat_detection_custom_modules(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", [ + securitycenter_service.ListEventThreatDetectionCustomModulesRequest, + dict, +]) +def test_list_event_threat_detection_custom_modules(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventThreatDetectionCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_event_threat_detection_custom_modules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_event_threat_detection_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + + +def test_list_event_threat_detection_custom_modules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest( + 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_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_event_threat_detection_custom_modules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEventThreatDetectionCustomModulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_event_threat_detection_custom_modules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_event_threat_detection_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_event_threat_detection_custom_modules] = mock_rpc + request = {} + client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_event_threat_detection_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_event_threat_detection_custom_modules_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_event_threat_detection_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + +@pytest.mark.asyncio +async def test_list_event_threat_detection_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_event_threat_detection_custom_modules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_event_threat_detection_custom_modules] = mock_object + + request = {} + await client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_event_threat_detection_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_event_threat_detection_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListEventThreatDetectionCustomModulesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventThreatDetectionCustomModulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_event_threat_detection_custom_modules_async_from_dict(): + await test_list_event_threat_detection_custom_modules_async(request_type=dict) + + +def test_list_event_threat_detection_custom_modules_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_event_threat_detection_custom_modules_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse()) + await client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_event_threat_detection_custom_modules_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_event_threat_detection_custom_modules( + 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_event_threat_detection_custom_modules_flattened_error(): + client = SecurityCenterClient( + credentials=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_event_threat_detection_custom_modules( + securitycenter_service.ListEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_event_threat_detection_custom_modules_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_event_threat_detection_custom_modules( + 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_event_threat_detection_custom_modules_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_event_threat_detection_custom_modules( + securitycenter_service.ListEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_event_threat_detection_custom_modules_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + for i in results) +def test_list_event_threat_detection_custom_modules_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_event_threat_detection_custom_modules(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_event_threat_detection_custom_modules_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_event_threat_detection_custom_modules_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_threat_detection_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + 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_event_threat_detection_custom_modules(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", [ + securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_update_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + ) + response = client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + + +def test_update_event_threat_detection_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + + +def test_update_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_event_threat_detection_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest( + ) + +def test_update_event_threat_detection_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_event_threat_detection_custom_module] = mock_rpc + request = {} + client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_event_threat_detection_custom_module(request) + + # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + )) + response = await client.update_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + +@pytest.mark.asyncio +async def test_update_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_event_threat_detection_custom_module] = mock_object + + request = {} + await client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + )) + response = await client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + + +@pytest.mark.asyncio +async def test_update_event_threat_detection_custom_module_async_from_dict(): + await test_update_event_threat_detection_custom_module_async(request_type=dict) + + +def test_update_event_threat_detection_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + + request.event_threat_detection_custom_module.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'event_threat_detection_custom_module.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_event_threat_detection_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + + request.event_threat_detection_custom_module.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + await client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'event_threat_detection_custom_module.name=name_value', + ) in kw['metadata'] + + +def test_update_event_threat_detection_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_event_threat_detection_custom_module( + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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].event_threat_detection_custom_module + mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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_event_threat_detection_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_event_threat_detection_custom_module( + securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(), + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_event_threat_detection_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_event_threat_detection_custom_module( + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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].event_threat_detection_custom_module + mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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_event_threat_detection_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_event_threat_detection_custom_module( + securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(), + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_validate_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( + ) + response = client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) + + +def test_validate_event_threat_detection_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.validate_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + + +def test_validate_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest( + parent='parent_value', + raw_text='raw_text_value', + type_='type__value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.validate_event_threat_detection_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest( + parent='parent_value', + raw_text='raw_text_value', + type_='type__value', + ) + +def test_validate_event_threat_detection_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc + request = {} + client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.validate_event_threat_detection_custom_module(request) + + # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( + )) + response = await client.validate_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + +@pytest.mark.asyncio +async def test_validate_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.validate_event_threat_detection_custom_module] = mock_object + + request = {} + await client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.validate_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_validate_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( + )) + response = await client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) + + +@pytest.mark.asyncio +async def test_validate_event_threat_detection_custom_module_async_from_dict(): + await test_validate_event_threat_detection_custom_module_async(request_type=dict) + + +def test_validate_event_threat_detection_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() + client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_validate_event_threat_detection_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse()) + await client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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", [ + securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_get_effective_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( + name='name_value', + enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + ) + response = client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.enablement_state == effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_effective_event_threat_detection_custom_module_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_effective_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + + +def test_get_effective_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_effective_event_threat_detection_custom_module(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest( + name='name_value', + ) + +def test_get_effective_event_threat_detection_custom_module_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_effective_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_effective_event_threat_detection_custom_module] = mock_rpc + request = {} + client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_effective_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_effective_event_threat_detection_custom_module_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( + name='name_value', + enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_effective_event_threat_detection_custom_module() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + +@pytest.mark.asyncio +async def test_get_effective_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_effective_event_threat_detection_custom_module in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_effective_event_threat_detection_custom_module] = mock_object + + request = {} + await client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_effective_event_threat_detection_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_effective_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( + name='name_value', + enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.enablement_state == effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_effective_event_threat_detection_custom_module_async_from_dict(): + await test_get_effective_event_threat_detection_custom_module_async(request_type=dict) + + +def test_get_effective_event_threat_detection_custom_module_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_effective_event_threat_detection_custom_module_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule()) + await client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_effective_event_threat_detection_custom_module_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_effective_event_threat_detection_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_effective_event_threat_detection_custom_module_flattened_error(): + client = SecurityCenterClient( + credentials=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_effective_event_threat_detection_custom_module( + securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_effective_event_threat_detection_custom_module_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_event_threat_detection_custom_module), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_effective_event_threat_detection_custom_module( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_effective_event_threat_detection_custom_module_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_effective_event_threat_detection_custom_module( + securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, + dict, +]) +def test_list_effective_event_threat_detection_custom_modules(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEffectiveEventThreatDetectionCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_effective_event_threat_detection_custom_modules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_effective_event_threat_detection_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + + +def test_list_effective_event_threat_detection_custom_modules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest( + 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_effective_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_effective_event_threat_detection_custom_modules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_effective_event_threat_detection_custom_modules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_effective_event_threat_detection_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_effective_event_threat_detection_custom_modules] = mock_rpc + request = {} + client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_effective_event_threat_detection_custom_modules_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_effective_event_threat_detection_custom_modules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + +@pytest.mark.asyncio +async def test_list_effective_event_threat_detection_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_effective_event_threat_detection_custom_modules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_effective_event_threat_detection_custom_modules] = mock_object + + request = {} + await client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_effective_event_threat_detection_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEffectiveEventThreatDetectionCustomModulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_effective_event_threat_detection_custom_modules_async_from_dict(): + await test_list_effective_event_threat_detection_custom_modules_async(request_type=dict) + + +def test_list_effective_event_threat_detection_custom_modules_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_effective_event_threat_detection_custom_modules_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse()) + await client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_effective_event_threat_detection_custom_modules_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_effective_event_threat_detection_custom_modules( + 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_effective_event_threat_detection_custom_modules_flattened_error(): + client = SecurityCenterClient( + credentials=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_effective_event_threat_detection_custom_modules( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_effective_event_threat_detection_custom_modules_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_effective_event_threat_detection_custom_modules( + 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_effective_event_threat_detection_custom_modules_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_effective_event_threat_detection_custom_modules( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_effective_event_threat_detection_custom_modules_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_effective_event_threat_detection_custom_modules(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, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) + for i in results) +def test_list_effective_event_threat_detection_custom_modules_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_effective_event_threat_detection_custom_modules(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_effective_event_threat_detection_custom_modules_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_effective_event_threat_detection_custom_modules(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, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_effective_event_threat_detection_custom_modules_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_event_threat_detection_custom_modules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + ), + 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_effective_event_threat_detection_custom_modules(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", [ + securitycenter_service.BatchCreateResourceValueConfigsRequest, + dict, +]) +def test_batch_create_resource_value_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse( + ) + response = client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) + + +def test_batch_create_resource_value_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_create_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() + + +def test_batch_create_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.BatchCreateResourceValueConfigsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_create_resource_value_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest( + parent='parent_value', + ) + +def test_batch_create_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc + request = {} + client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_resource_value_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_batch_create_resource_value_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( + )) + response = await client.batch_create_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() + +@pytest.mark.asyncio +async def test_batch_create_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.batch_create_resource_value_configs] = mock_object + + request = {} + await client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.batch_create_resource_value_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( + )) + response = await client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) + + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_async_from_dict(): + await test_batch_create_resource_value_configs_async(request_type=dict) + + +def test_batch_create_resource_value_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + client.batch_create_resource_value_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_batch_create_resource_value_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) + await client.batch_create_resource_value_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_batch_create_resource_value_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_resource_value_configs( + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(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 + arg = args[0].requests + mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] + assert arg == mock_val + + +def test_batch_create_resource_value_configs_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], + ) + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_resource_value_configs( + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(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 + arg = args[0].requests + mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteResourceValueConfigRequest, + dict, +]) +def test_delete_resource_value_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() + + +def test_delete_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteResourceValueConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_resource_value_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest( + name='name_value', + ) + +def test_delete_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + request = {} + client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_resource_value_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_resource_value_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() + +@pytest.mark.asyncio +async def test_delete_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_resource_value_config] = mock_object + + request = {} + await client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_resource_value_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteResourceValueConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteResourceValueConfigRequest() + 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_resource_value_config_async_from_dict(): + await test_delete_resource_value_config_async(request_type=dict) + + +def test_delete_resource_value_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value = None + client.delete_resource_value_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_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_resource_value_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_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetResourceValueConfigRequest, + dict, +]) +def test_get_resource_value_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + response = client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +def test_get_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest() + + +def test_get_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetResourceValueConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_resource_value_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest( + name='name_value', + ) + +def test_get_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc + request = {} + client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_resource_value_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_resource_value_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest() + +@pytest.mark.asyncio +async def test_get_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_resource_value_config] = mock_object + + request = {} + await client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_resource_value_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetResourceValueConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +@pytest.mark.asyncio +async def test_get_resource_value_config_async_from_dict(): + await test_get_resource_value_config_async(request_type=dict) + + +def test_get_resource_value_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value = resource_value_config.ResourceValueConfig() + client.get_resource_value_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_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) + await client.get_resource_value_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_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_resource_value_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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_resource_value_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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListResourceValueConfigsRequest, + dict, +]) +def test_list_resource_value_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_resource_value_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() + + +def test_list_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListResourceValueConfigsRequest( + 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_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_resource_value_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc + request = {} + client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_value_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_resource_value_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() + +@pytest.mark.asyncio +async def test_list_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_resource_value_configs] = mock_object + + request = {} + await client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_resource_value_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListResourceValueConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async_from_dict(): + await test_list_resource_value_configs_async(request_type=dict) + + +def test_list_resource_value_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + client.list_resource_value_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_resource_value_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) + await client.list_resource_value_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_resource_value_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_resource_value_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_resource_value_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_resource_value_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_resource_value_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_resource_value_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent='parent_value', + ) + + +def test_list_resource_value_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_resource_value_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, resource_value_config.ResourceValueConfig) + for i in results) +def test_list_resource_value_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_resource_value_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_resource_value_configs_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_resource_value_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, resource_value_config.ResourceValueConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + 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_resource_value_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", [ + securitycenter_service.UpdateResourceValueConfigRequest, + dict, +]) +def test_update_resource_value_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + response = client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +def test_update_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() + + +def test_update_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateResourceValueConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_resource_value_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest( + ) + +def test_update_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + request = {} + client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_resource_value_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_resource_value_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.update_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() + +@pytest.mark.asyncio +async def test_update_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_resource_value_config] = mock_object + + request = {} + await client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_resource_value_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateResourceValueConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +@pytest.mark.asyncio +async def test_update_resource_value_config_async_from_dict(): + await test_update_resource_value_config_async(request_type=dict) + + +def test_update_resource_value_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateResourceValueConfigRequest() + + request.resource_value_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value = gcs_resource_value_config.ResourceValueConfig() + client.update_resource_value_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', + 'resource_value_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateResourceValueConfigRequest() + + request.resource_value_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) + await client.update_resource_value_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', + 'resource_value_config.name=name_value', + ) in kw['metadata'] + + +def test_update_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_resource_value_config( + resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config + mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_resource_value_config( + resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config + mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListValuedResourcesRequest, + dict, +]) +def test_list_valued_resources(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListValuedResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_valued_resources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_valued_resources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest() + + +def test_list_valued_resources_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListValuedResourcesRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_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_valued_resources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_valued_resources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_value', + order_by='order_by_value', + ) + +def test_list_valued_resources_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_valued_resources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc + request = {} + client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_valued_resources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_valued_resources_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_valued_resources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest() + +@pytest.mark.asyncio +async def test_list_valued_resources_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_valued_resources in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_valued_resources] = mock_object + + request = {} + await client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_valued_resources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_valued_resources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListValuedResourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListValuedResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_valued_resources_async_from_dict(): + await test_list_valued_resources_async(request_type=dict) + + +def test_list_valued_resources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListValuedResourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + call.return_value = securitycenter_service.ListValuedResourcesResponse() + client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_valued_resources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListValuedResourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) + await client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_valued_resources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_valued_resources( + 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_valued_resources_flattened_error(): + client = SecurityCenterClient( + credentials=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_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_valued_resources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_valued_resources( + 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_valued_resources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent='parent_value', + ) + + +def test_list_valued_resources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_valued_resources(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, valued_resource.ValuedResource) + for i in results) +def test_list_valued_resources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_valued_resources(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_valued_resources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_valued_resources(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, valued_resource.ValuedResource) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_valued_resources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + 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_valued_resources(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", [ + securitycenter_service.ListAttackPathsRequest, + dict, +]) +def test_list_attack_paths(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAttackPathsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_attack_paths_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_attack_paths() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest() + + +def test_list_attack_paths_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListAttackPathsRequest( + 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_attack_paths), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_attack_paths(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_attack_paths_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_attack_paths in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc + request = {} + client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_attack_paths(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_attack_paths_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_attack_paths() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest() + +@pytest.mark.asyncio +async def test_list_attack_paths_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_attack_paths in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_attack_paths] = mock_object + + request = {} + await client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_attack_paths(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_attack_paths_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAttackPathsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAttackPathsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_attack_paths_async_from_dict(): + await test_list_attack_paths_async(request_type=dict) + + +def test_list_attack_paths_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAttackPathsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + call.return_value = securitycenter_service.ListAttackPathsResponse() + client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_attack_paths_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAttackPathsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) + await client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_attack_paths_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_attack_paths( + 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_attack_paths_flattened_error(): + client = SecurityCenterClient( + credentials=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_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_attack_paths_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_attack_paths( + 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_attack_paths_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent='parent_value', + ) + + +def test_list_attack_paths_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_attack_paths(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, attack_path.AttackPath) + for i in results) +def test_list_attack_paths_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + pages = list(client.list_attack_paths(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_attack_paths_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_attack_paths(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, attack_path.AttackPath) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_attack_paths_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + 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_attack_paths(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", [ + securitycenter_service.BulkMuteFindingsRequest, + dict, +]) +def test_bulk_mute_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') + + # 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 + response = client.bulk_mute_findings(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_bulk_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc + + request = {} + client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_rest_required_fields(request_type=securitycenter_service.BulkMuteFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).bulk_mute_findings._get_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()).bulk_mute_findings._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 = SecurityCenterClient( + 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.bulk_mute_findings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_bulk_mute_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.bulk_mute_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_bulk_mute_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_bulk_mute_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_bulk_mute_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.BulkMuteFindingsRequest.pb(securitycenter_service.BulkMuteFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = securitycenter_service.BulkMuteFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.bulk_mute_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_bulk_mute_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BulkMuteFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.bulk_mute_findings(request) + + +def test_bulk_mute_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.bulk_mute_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/v1/{parent=organizations/*}/findings:bulkMute" % client.transport._host, args[1]) + + +def test_bulk_mute_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent='parent_value', + ) + + +def test_bulk_mute_findings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_create_security_health_analytics_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request_init["security_health_analytics_custom_module"] = {'name': 'name_value', 'display_name': 'display_name_value', 'enablement_state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_value', 'ancestor_module': 'ancestor_module_value', 'custom_config': {'predicate': {'expression': 'expression_value', 'title': 'title_value', 'description': 'description_value', 'location': 'location_value'}, 'custom_output': {'properties': [{'name': 'name_value', 'value_expression': {}}]}, 'resource_selector': {'resource_types': ['resource_types_value1', 'resource_types_value2']}, 'severity': 1, 'description': 'description_value', 'recommendation': 'recommendation_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 = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.meta.fields["security_health_analytics_custom_module"] + + 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["security_health_analytics_custom_module"].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["security_health_analytics_custom_module"][field])): + del request_init["security_health_analytics_custom_module"][field][i][subfield] + else: + del request_init["security_health_analytics_custom_module"][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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) + 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_security_health_analytics_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + +def test_create_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc + + request = {} + client.create_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_security_health_analytics_custom_module(request) + + # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_security_health_analytics_custom_module._get_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_security_health_analytics_custom_module._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) + 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_security_health_analytics_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_security_health_analytics_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_security_health_analytics_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "securityHealthAnalyticsCustomModule", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_security_health_analytics_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_security_health_analytics_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_security_health_analytics_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.to_json(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + + request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + client.create_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_security_health_analytics_custom_module(request) + + +def test_create_security_health_analytics_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(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_security_health_analytics_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules" % client.transport._host, args[1]) + + +def test_create_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_health_analytics_custom_module( + securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(), + parent='parent_value', + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + ) + + +def test_create_security_health_analytics_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.CreateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_source(request) + + +def test_create_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_create_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +def test_create_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request_init["finding"] = {'name': 'name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_value', 'mute': 1, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True, 'exploit_release_date': {}}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'mute_info': {'static_mute': {'state': 1, 'apply_time': {}}, 'dynamic_mute_records': [{'mute_config': 'mute_config_value', 'match_time': {}}]}, 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.create_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.create_finding] = mock_rpc + + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["finding_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 "findingId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "findingId" in jsonified_request + assert jsonified_request["findingId"] == request_init["finding_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["findingId"] = 'finding_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request + assert jsonified_request["findingId"] == 'finding_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.create_finding(request) + + expected_params = [ + ( + "findingId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.CreateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_finding(request) + + +def test_create_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(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 = gcs_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.create_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/v1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) + + +def test_create_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_create_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateMuteConfigRequest, + dict, +]) +def test_create_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["mute_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'type_': 1, 'expiry_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 = securitycenter_service.CreateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): + del request_init["mute_config"][field][i][subfield] + else: + del request_init["mute_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 = gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + +def test_create_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + + request = {} + client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.CreateMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["mute_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 "muteConfigId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "muteConfigId" in jsonified_request + assert jsonified_request["muteConfigId"] == request_init["mute_config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["muteConfigId"] = 'mute_config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("mute_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 "muteConfigId" in jsonified_request + assert jsonified_request["muteConfigId"] == 'mute_config_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + expected_params = [ + ( + "muteConfigId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("muteConfigId", )) & set(("parent", "muteConfig", "muteConfigId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_mute_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_mute_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateMuteConfigRequest.pb(securitycenter_service.CreateMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) + + request = securitycenter_service.CreateMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_mute_config.MuteConfig() + + client.create_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_mute_config(request) + + +def test_create_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_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 = gcs_mute_config.MuteConfig.pb(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_mute_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=organizations/*}/muteConfigs" % client.transport._host, args[1]) + + +def test_create_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_id_value', + ) + + +def test_create_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateNotificationConfigRequest, + dict, +]) +def test_create_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["notification_config"] = {'name': 'name_value', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.CreateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.CreateNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["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 "configId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "configId" in jsonified_request + assert jsonified_request["configId"] == request_init["config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["configId"] = 'config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("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 "configId" in jsonified_request + assert jsonified_request["configId"] == 'config_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ( + "configId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("configId", )) & set(("parent", "configId", "notificationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateNotificationConfigRequest.pb(securitycenter_service.CreateNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) + + request = securitycenter_service.CreateNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.create_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_notification_config(request) + + +def test_create_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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=organizations/*}/notificationConfigs" % client.transport._host, args[1]) + + +def test_create_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + +def test_create_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteMuteConfigRequest, + dict, +]) +def test_delete_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/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 = 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + + request = {} + client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.DeleteMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( + 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_mute_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_mute_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteMuteConfigRequest.pb(securitycenter_service.DeleteMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_mute_config(request) + + +def test_delete_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/muteConfigs/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_mute_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=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name='name_value', + ) + + +def test_delete_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, +]) +def test_delete_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/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 = 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_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.DeleteNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_notification_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteNotificationConfigRequest.pb(securitycenter_service.DeleteNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_notification_config(request) + + +def test_delete_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/notificationConfigs/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_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=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +def test_delete_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_delete_security_health_analytics_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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 = 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_security_health_analytics_custom_module(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc + + request = {} + client.delete_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_security_health_analytics_custom_module(request) + + # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + 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_security_health_analytics_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_security_health_analytics_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_security_health_analytics_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_security_health_analytics_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_security_health_analytics_custom_module") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_security_health_analytics_custom_module(request) + + +def test_delete_security_health_analytics_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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_security_health_analytics_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings/customModules/*}" % client.transport._host, args[1]) + + +def test_delete_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_health_analytics_custom_module( + securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + + +def test_delete_security_health_analytics_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSimulationRequest, + dict, +]) +def test_get_simulation_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = simulation.Simulation.pb(return_value) + 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_simulation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == 'name_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + +def test_get_simulation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_simulation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc + + request = {} + client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_simulation(request) + + # Establish 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_simulation_rest_required_fields(request_type=securitycenter_service.GetSimulationRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_simulation._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_simulation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = simulation.Simulation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = simulation.Simulation.pb(return_value) + 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_simulation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_simulation_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_simulation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_simulation_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_simulation") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_simulation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSimulationRequest.pb(securitycenter_service.GetSimulationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = simulation.Simulation.to_json(simulation.Simulation()) + + request = securitycenter_service.GetSimulationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = simulation.Simulation() + + client.get_simulation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_simulation_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSimulationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_simulation(request) + + +def test_get_simulation_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = simulation.Simulation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation.pb(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_simulation(**mock_args) + + # Establish that the underlying call 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=organizations/*/simulations/*}" % client.transport._host, args[1]) + + +def test_get_simulation_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_simulation( + securitycenter_service.GetSimulationRequest(), + name='name_value', + ) + + +def test_get_simulation_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetValuedResourceRequest, + dict, +]) +def test_get_valued_resource_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = valued_resource.ValuedResource.pb(return_value) + 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_valued_resource(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == 'name_value' + assert response.resource == 'resource_value' + assert response.resource_type == 'resource_type_value' + assert response.display_name == 'display_name_value' + assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + +def test_get_valued_resource_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_valued_resource in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc + + request = {} + client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_valued_resource(request) + + # Establish 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_valued_resource_rest_required_fields(request_type=securitycenter_service.GetValuedResourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_valued_resource._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_valued_resource._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = valued_resource.ValuedResource() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = valued_resource.ValuedResource.pb(return_value) + 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_valued_resource(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_valued_resource_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_valued_resource._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_valued_resource_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_valued_resource") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_valued_resource") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetValuedResourceRequest.pb(securitycenter_service.GetValuedResourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = valued_resource.ValuedResource.to_json(valued_resource.ValuedResource()) + + request = securitycenter_service.GetValuedResourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = valued_resource.ValuedResource() + + client.get_valued_resource(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_valued_resource_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetValuedResourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_valued_resource(request) + + +def test_get_valued_resource_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = valued_resource.ValuedResource() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource.pb(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_valued_resource(**mock_args) + + # Establish that the underlying call 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=organizations/*/simulations/*/valuedResources/*}" % client.transport._host, args[1]) + + +def test_get_valued_resource_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name='name_value', + ) + + +def test_get_valued_resource_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetBigQueryExportRequest, + dict, +]) +def test_get_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/bigQueryExports/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 = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + +def test_get_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc + + request = {} + client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.GetBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_big_query_export") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_big_query_export") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetBigQueryExportRequest.pb(securitycenter_service.GetBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) + + request = securitycenter_service.GetBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.get_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/bigQueryExports/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_big_query_export(request) + + +def test_get_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/bigQueryExports/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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) + + # Establish that the underlying call 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=organizations/*/bigQueryExports/*}" % client.transport._host, args[1]) + + +def test_get_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name='name_value', + ) + + +def test_get_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.get_iam_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/v1/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetMuteConfigRequest, + dict, +]) +def test_get_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC + +def test_get_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_mute_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_mute_config] = mock_rpc + + request = {} + client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.GetMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = mute_config.MuteConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_mute_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_mute_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetMuteConfigRequest.pb(securitycenter_service.GetMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = mute_config.MuteConfig.to_json(mute_config.MuteConfig()) + + request = securitycenter_service.GetMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = mute_config.MuteConfig() + + client.get_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_mute_config(request) + + +def test_get_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig.pb(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_mute_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=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) + + +def test_get_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name='name_value', + ) + + +def test_get_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetNotificationConfigRequest, + dict, +]) +def test_get_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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_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_notification_config] = mock_rpc + + request = {} + client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.GetNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetNotificationConfigRequest.pb(securitycenter_service.GetNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = notification_config.NotificationConfig.to_json(notification_config.NotificationConfig()) + + request = securitycenter_service.GetNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = notification_config.NotificationConfig() + + client.get_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_notification_config(request) + + +def test_get_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig.pb(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_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=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_get_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +def test_get_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetOrganizationSettingsRequest, + dict, +]) +def test_get_organization_settings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/organizationSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_organization_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_organization_settings] = mock_rpc + + request = {} + client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.GetOrganizationSettingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_organization_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_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_organization_settings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_organization_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_organization_settings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_organization_settings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_organization_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetOrganizationSettingsRequest.pb(securitycenter_service.GetOrganizationSettingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = organization_settings.OrganizationSettings.to_json(organization_settings.OrganizationSettings()) + + request = securitycenter_service.GetOrganizationSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = organization_settings.OrganizationSettings() + + client.get_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/organizationSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_organization_settings(request) + + +def test_get_organization_settings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/organizationSettings'} + + # get truthy value for each flattened field + mock_args = dict( + 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 = organization_settings.OrganizationSettings.pb(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_organization_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/v1/{name=organizations/*/organizationSettings}" % client.transport._host, args[1]) + + +def test_get_organization_settings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +def test_get_organization_settings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_get_effective_security_health_analytics_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/effectiveCustomModules/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 = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( + name='name_value', + enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + display_name='display_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(return_value) + 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_effective_security_health_analytics_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.enablement_state == effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.display_name == 'display_name_value' + +def test_get_effective_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_effective_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_effective_security_health_analytics_custom_module] = mock_rpc + + request = {} + client.get_effective_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_effective_security_health_analytics_custom_module(request) + + # Establish 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_effective_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_effective_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_effective_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(return_value) + 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_effective_security_health_analytics_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_effective_security_health_analytics_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_effective_security_health_analytics_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_effective_security_health_analytics_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_effective_security_health_analytics_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_effective_security_health_analytics_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.to_json(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule()) + + request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + + client.get_effective_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_effective_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/effectiveCustomModules/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_effective_security_health_analytics_custom_module(request) + + +def test_get_effective_security_health_analytics_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/effectiveCustomModules/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 = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(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_effective_security_health_analytics_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}" % client.transport._host, args[1]) + + +def test_get_effective_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_effective_security_health_analytics_custom_module( + securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + + +def test_get_effective_security_health_analytics_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_get_security_health_analytics_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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 = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) + 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_security_health_analytics_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + +def test_get_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_security_health_analytics_custom_module] = mock_rpc + + request = {} + client.get_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_security_health_analytics_custom_module(request) + + # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) + 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_security_health_analytics_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_security_health_analytics_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_security_health_analytics_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_security_health_analytics_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_security_health_analytics_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_security_health_analytics_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.to_json(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + + request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + client.get_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_security_health_analytics_custom_module(request) + + +def test_get_security_health_analytics_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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 = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(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_security_health_analytics_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings/customModules/*}" % client.transport._host, args[1]) + + +def test_get_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_health_analytics_custom_module( + securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(), + name='name_value', + ) + + +def test_get_security_health_analytics_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/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 = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = source.Source.to_json(source.Source()) + + request = securitycenter_service.GetSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = source.Source() + + client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_source(request) + + +def test_get_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v1/{name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_get_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +def test_get_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupAssetsRequest, + dict, +]) +def test_group_assets_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_group_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc + + request = {} + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_group_assets_rest_required_fields(request_type=securitycenter_service.GroupAssetsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_assets_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_assets_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_assets") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupAssetsRequest.pb(securitycenter_service.GroupAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupAssetsResponse.to_json(securitycenter_service.GroupAssetsResponse()) + + request = securitycenter_service.GroupAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupAssetsResponse() + + client.group_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_assets(request) + + +def test_group_assets_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupAssetsResponse.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': 'organizations/sample1'} + + pager = client.group_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_findings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) + + request = securitycenter_service.GroupFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupFindingsResponse() + + client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_findings(request) + + +def test_group_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + group_by='group_by_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v1/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) + + +def test_group_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} + + pager = client.group_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_findings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListAssetsRequest, + dict, +]) +def test_list_assets_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListAssetsResponse.pb(return_value) + 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_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_list_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish 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_assets_rest_required_fields(request_type=securitycenter_service.ListAssetsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_assets._get_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_assets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) + jsonified_request.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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListAssetsResponse.pb(return_value) + 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_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_assets_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_assets_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_assets") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListAssetsRequest.pb(securitycenter_service.ListAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListAssetsResponse.to_json(securitycenter_service.ListAssetsResponse()) + + request = securitycenter_service.ListAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListAssetsResponse() + + client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_assets(request) + + +def test_list_assets_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListAssetsResponse.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': 'organizations/sample1'} + + pager = client.list_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) + + pages = list(client.list_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, + dict, +]) +def test_list_descendant_security_health_analytics_custom_modules_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) + 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_descendant_security_health_analytics_custom_modules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_descendant_security_health_analytics_custom_modules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_descendant_security_health_analytics_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_descendant_security_health_analytics_custom_modules] = mock_rpc + + request = {} + client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_descendant_security_health_analytics_custom_modules(request) + + # Establish 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_descendant_security_health_analytics_custom_modules_rest_required_fields(request_type=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_descendant_security_health_analytics_custom_modules._get_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_descendant_security_health_analytics_custom_modules._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) + 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_descendant_security_health_analytics_custom_modules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_descendant_security_health_analytics_custom_modules_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_descendant_security_health_analytics_custom_modules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_descendant_security_health_analytics_custom_modules_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_descendant_security_health_analytics_custom_modules") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_descendant_security_health_analytics_custom_modules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.pb(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.to_json(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse()) + + request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + + client.list_descendant_security_health_analytics_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_descendant_security_health_analytics_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_descendant_security_health_analytics_custom_modules(request) + + +def test_list_descendant_security_health_analytics_custom_modules_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + + # 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 = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(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_descendant_security_health_analytics_custom_modules(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules:listDescendant" % client.transport._host, args[1]) + + +def test_list_descendant_security_health_analytics_custom_modules_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_descendant_security_health_analytics_custom_modules( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_descendant_security_health_analytics_custom_modules_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.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': 'organizations/sample1/securityHealthAnalyticsSettings'} + + pager = client.list_descendant_security_health_analytics_custom_modules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + for i in results) + + pages = list(client.list_descendant_security_health_analytics_custom_modules(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.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' + assert response.total_size == 1086 + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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=securitycenter_service.ListFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) + jsonified_request.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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.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 = securitycenter_service.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 = [ + ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) + + request = securitycenter_service.ListFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListFindingsResponse() + + client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_findings(request) + + +def test_list_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} + + pager = client.list_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) + 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 + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListMuteConfigsRequest, + dict, +]) +def test_list_mute_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) + 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_mute_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_mute_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_mute_configs] = mock_rpc + + request = {} + client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_mute_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_mute_configs_rest_required_fields(request_type=securitycenter_service.ListMuteConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListMuteConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) + 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_mute_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_mute_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_mute_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_mute_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_mute_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_mute_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListMuteConfigsRequest.pb(securitycenter_service.ListMuteConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListMuteConfigsResponse.to_json(securitycenter_service.ListMuteConfigsResponse()) + + request = securitycenter_service.ListMuteConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListMuteConfigsResponse() + + client.list_mute_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_mute_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListMuteConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_mute_configs(request) + + +def test_list_mute_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListMuteConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse.pb(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_mute_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=organizations/*}/muteConfigs" % client.transport._host, args[1]) + + +def test_list_mute_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent='parent_value', + ) + + +def test_list_mute_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListMuteConfigsResponse.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': 'organizations/sample1'} + + pager = client.list_mute_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, mute_config.MuteConfig) + for i in results) + + pages = list(client.list_mute_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListNotificationConfigsRequest, + dict, +]) +def test_list_notification_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) + 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_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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_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_notification_configs] = mock_rpc + + request = {} + client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_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_notification_configs_rest_required_fields(request_type=securitycenter_service.ListNotificationConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListNotificationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) + 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_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_notification_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_notification_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_notification_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_notification_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_notification_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListNotificationConfigsRequest.pb(securitycenter_service.ListNotificationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListNotificationConfigsResponse.to_json(securitycenter_service.ListNotificationConfigsResponse()) + + request = securitycenter_service.ListNotificationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListNotificationConfigsResponse() + + client.list_notification_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_notification_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_notification_configs(request) + + +def test_list_notification_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListNotificationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse.pb(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_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=organizations/*}/notificationConfigs" % client.transport._host, args[1]) + + +def test_list_notification_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListNotificationConfigsResponse.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': 'organizations/sample1'} + + pager = client.list_notification_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, notification_config.NotificationConfig) + for i in results) + + pages = list(client.list_notification_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, + dict, +]) +def test_list_effective_security_health_analytics_custom_modules_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) + 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_effective_security_health_analytics_custom_modules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_effective_security_health_analytics_custom_modules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_effective_security_health_analytics_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_effective_security_health_analytics_custom_modules] = mock_rpc + + request = {} + client.list_effective_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_effective_security_health_analytics_custom_modules(request) + + # Establish 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_effective_security_health_analytics_custom_modules_rest_required_fields(request_type=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_effective_security_health_analytics_custom_modules._get_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_effective_security_health_analytics_custom_modules._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) + 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_effective_security_health_analytics_custom_modules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_effective_security_health_analytics_custom_modules_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_effective_security_health_analytics_custom_modules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_effective_security_health_analytics_custom_modules_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_effective_security_health_analytics_custom_modules") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_effective_security_health_analytics_custom_modules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.pb(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.to_json(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse()) + + request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + + client.list_effective_security_health_analytics_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_effective_security_health_analytics_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_effective_security_health_analytics_custom_modules(request) + + +def test_list_effective_security_health_analytics_custom_modules_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + + # 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 = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(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_effective_security_health_analytics_custom_modules(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/effectiveCustomModules" % client.transport._host, args[1]) + + +def test_list_effective_security_health_analytics_custom_modules_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_effective_security_health_analytics_custom_modules( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_effective_security_health_analytics_custom_modules_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( + effective_security_health_analytics_custom_modules=[ + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.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': 'organizations/sample1/securityHealthAnalyticsSettings'} + + pager = client.list_effective_security_health_analytics_custom_modules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) + for i in results) + + pages = list(client.list_effective_security_health_analytics_custom_modules(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, + dict, +]) +def test_list_security_health_analytics_custom_modules_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) + 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_security_health_analytics_custom_modules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecurityHealthAnalyticsCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_security_health_analytics_custom_modules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_security_health_analytics_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_security_health_analytics_custom_modules] = mock_rpc + + request = {} + client.list_security_health_analytics_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_security_health_analytics_custom_modules(request) + + # Establish 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_security_health_analytics_custom_modules_rest_required_fields(request_type=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_security_health_analytics_custom_modules._get_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_security_health_analytics_custom_modules._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) + 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_security_health_analytics_custom_modules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_security_health_analytics_custom_modules_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_security_health_analytics_custom_modules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_security_health_analytics_custom_modules_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_security_health_analytics_custom_modules") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_security_health_analytics_custom_modules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.pb(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.to_json(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse()) + + request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + + client.list_security_health_analytics_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_security_health_analytics_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_security_health_analytics_custom_modules(request) + + +def test_list_security_health_analytics_custom_modules_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + + # 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 = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(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_security_health_analytics_custom_modules(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules" % client.transport._host, args[1]) + + +def test_list_security_health_analytics_custom_modules_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_health_analytics_custom_modules( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_security_health_analytics_custom_modules_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( + security_health_analytics_custom_modules=[ + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.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': 'organizations/sample1/securityHealthAnalyticsSettings'} + + pager = client.list_security_health_analytics_custom_modules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + for i in results) + + pages = list(client.list_security_health_analytics_custom_modules(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_sources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_sources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) + + request = securitycenter_service.ListSourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListSourcesResponse() + + client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_sources(request) + + +def test_list_sources_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v1/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_list_sources_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} + + pager = client.list_sources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, source.Source) + for i in results) + + pages = list(client.list_sources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.RunAssetDiscoveryRequest, + dict, +]) +def test_run_asset_discovery_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') + + # 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 + response = client.run_asset_discovery(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_run_asset_discovery_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_asset_discovery in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc + + request = {} + client.run_asset_discovery(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.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_run_asset_discovery_rest_required_fields(request_type=securitycenter_service.RunAssetDiscoveryRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_asset_discovery._get_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()).run_asset_discovery._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 = SecurityCenterClient( + 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.run_asset_discovery(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_run_asset_discovery_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.run_asset_discovery._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_asset_discovery_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_run_asset_discovery") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_run_asset_discovery") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.RunAssetDiscoveryRequest.pb(securitycenter_service.RunAssetDiscoveryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = securitycenter_service.RunAssetDiscoveryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.run_asset_discovery(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_asset_discovery_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.run_asset_discovery(request) + + +def test_run_asset_discovery_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.run_asset_discovery(**mock_args) + + # Establish that the underlying call 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=organizations/*}/assets:runDiscovery" % client.transport._host, args[1]) + + +def test_run_asset_discovery_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +def test_run_asset_discovery_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # 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 + response = client.set_finding_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( + 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': "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 = 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.set_finding_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_finding_state_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_finding_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "state", "startTime", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_finding_state_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetFindingStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_finding_state(request) + + +def test_set_finding_state_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + mock_args.update(sample_request) + + # 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.set_finding_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/v1/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) + + +def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +def test_set_finding_state_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetMuteRequest, + dict, +]) +def test_set_mute_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # 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 + response = client.set_mute(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_set_mute_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_mute in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc + + request = {} + client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_mute(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_set_mute_rest_required_fields(request_type=securitycenter_service.SetMuteRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + 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': "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 = 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.set_mute(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_mute_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_mute._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "mute", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_mute_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_mute") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_mute") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetMuteRequest.pb(securitycenter_service.SetMuteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetMuteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_mute(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_mute_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetMuteRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_mute(request) + + +def test_set_mute_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + mock_args.update(sample_request) + + # 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.set_mute(**mock_args) + + # Establish that the underlying call 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=organizations/*/sources/*/findings/*}:setMute" % client.transport._host, args[1]) + + +def test_set_mute_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_mute( + securitycenter_service.SetMuteRequest(), + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + +def test_set_mute_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.set_iam_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/v1/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # 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 + response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_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.test_iam_permissions(**mock_args) + + # Establish that the underlying call 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/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_simulate_security_health_analytics_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.simulate_security_health_analytics_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) + +def test_simulate_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.simulate_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.simulate_security_health_analytics_custom_module] = mock_rpc + + request = {} + client.simulate_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.simulate_security_health_analytics_custom_module(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_simulate_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).simulate_security_health_analytics_custom_module._get_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()).simulate_security_health_analytics_custom_module._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.simulate_security_health_analytics_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_simulate_security_health_analytics_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.simulate_security_health_analytics_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "customConfig", "resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_simulate_security_health_analytics_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_simulate_security_health_analytics_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_simulate_security_health_analytics_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.to_json(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse()) + + request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + + client.simulate_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_simulate_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.simulate_security_health_analytics_custom_module(request) + + +def test_simulate_security_health_analytics_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), + resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(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.simulate_security_health_analytics_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules:simulate" % client.transport._host, args[1]) + + +def test_simulate_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.simulate_security_health_analytics_custom_module( + securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(), + parent='parent_value', + custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), + resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), + ) + + +def test_simulate_security_health_analytics_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateExternalSystemRequest, + dict, +]) +def test_update_external_system_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} + request_init["external_system"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4', 'assignees': ['assignees_value1', 'assignees_value2'], 'external_uid': 'external_uid_value', 'status': 'status_value', 'external_system_update_time': {'seconds': 751, 'nanos': 543}, 'case_uri': 'case_uri_value', 'case_priority': 'case_priority_value', 'case_sla': {}, 'case_create_time': {}, 'case_close_time': {}, 'ticket_info': {'id': 'id_value', 'assignee': 'assignee_value', 'description': 'description_value', 'uri': 'uri_value', 'status': 'status_value', 'update_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 = securitycenter_service.UpdateExternalSystemRequest.meta.fields["external_system"] + + 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["external_system"].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["external_system"][field])): + del request_init["external_system"][field][i][subfield] + else: + del request_init["external_system"][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 = gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_external_system.ExternalSystem.pb(return_value) + 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_external_system(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == 'name_value' + assert response.assignees == ['assignees_value'] + assert response.external_uid == 'external_uid_value' + assert response.status == 'status_value' + assert response.case_uri == 'case_uri_value' + assert response.case_priority == 'case_priority_value' + +def test_update_external_system_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_external_system in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc + + request = {} + client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_external_system(request) + + # Establish 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_external_system_rest_required_fields(request_type=securitycenter_service.UpdateExternalSystemRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_external_system._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_external_system._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_external_system.ExternalSystem() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_external_system.ExternalSystem.pb(return_value) + 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_external_system(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_external_system_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_external_system._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("externalSystem", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_external_system_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_external_system") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_external_system") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateExternalSystemRequest.pb(securitycenter_service.UpdateExternalSystemRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_external_system.ExternalSystem.to_json(gcs_external_system.ExternalSystem()) + + request = securitycenter_service.UpdateExternalSystemRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_external_system.ExternalSystem() + + client.update_external_system(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_external_system_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateExternalSystemRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_external_system(request) + + +def test_update_external_system_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_external_system.ExternalSystem() + + # get arguments that satisfy an http rule for this method + sample_request = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + external_system=gcs_external_system.ExternalSystem(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 = gcs_external_system.ExternalSystem.pb(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_external_system(**mock_args) + + # Establish that the underlying call 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/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}" % client.transport._host, args[1]) + + +def test_update_external_system_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_external_system_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_value', 'mute': 1, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True, 'exploit_release_date': {}}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'mute_info': {'static_mute': {'state': 1, 'apply_time': {}}, 'dynamic_mute_records': [{'mute_config': 'mute_config_value', 'match_time': {}}]}, 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.update_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.update_finding] = mock_rpc + + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_finding._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_finding._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.update_finding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.UpdateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_finding(request) + + +def test_update_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + finding=gcs_finding.Finding(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 = gcs_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.update_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/v1/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) + + +def test_update_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_update_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateMuteConfigRequest, + dict, +]) +def test_update_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} + request_init["mute_config"] = {'name': 'organizations/sample1/muteConfigs/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'type_': 1, 'expiry_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 = securitycenter_service.UpdateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): + del request_init["mute_config"][field][i][subfield] + else: + del request_init["mute_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 = gcs_mute_config.MuteConfig( + name='name_value', + display_name='display_name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + +def test_update_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + + request = {} + client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.UpdateMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("muteConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_mute_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_mute_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateMuteConfigRequest.pb(securitycenter_service.UpdateMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) + + request = securitycenter_service.UpdateMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_mute_config.MuteConfig() + + client.update_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_mute_config(request) + + +def test_update_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + mute_config=gcs_mute_config.MuteConfig(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 = gcs_mute_config.MuteConfig.pb(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_mute_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/{mute_config.name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) + + +def test_update_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, +]) +def test_update_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} + request_init["notification_config"] = {'name': 'organizations/sample1/notificationConfigs/sample2', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.UpdateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.UpdateNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("notificationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateNotificationConfigRequest.pb(securitycenter_service.UpdateNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) + + request = securitycenter_service.UpdateNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.update_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_notification_config(request) + + +def test_update_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/{notification_config.name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_update_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateOrganizationSettingsRequest, + dict, +]) +def test_update_organization_settings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + request_init["organization_settings"] = {'name': 'organizations/sample1/organizationSettings', 'enable_asset_discovery': True, 'asset_discovery_config': {'project_ids': ['project_ids_value1', 'project_ids_value2'], 'inclusion_mode': 1, 'folder_ids': ['folder_ids_value1', 'folder_ids_value2']}} + # The version of a generated dependency at test runtime may differ from the version used 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 = securitycenter_service.UpdateOrganizationSettingsRequest.meta.fields["organization_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["organization_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["organization_settings"][field])): + del request_init["organization_settings"][field][i][subfield] + else: + del request_init["organization_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 = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_organization_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_organization_settings] = mock_rpc + + request = {} + client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_organization_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_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_organization_settings.OrganizationSettings() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_organization_settings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_organization_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("organizationSettings", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_organization_settings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_organization_settings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_organization_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateOrganizationSettingsRequest.pb(securitycenter_service.UpdateOrganizationSettingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_organization_settings.OrganizationSettings.to_json(gcs_organization_settings.OrganizationSettings()) + + request = securitycenter_service.UpdateOrganizationSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_organization_settings.OrganizationSettings() + + client.update_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_organization_settings(request) + + +def test_update_organization_settings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_organization_settings.OrganizationSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + organization_settings=gcs_organization_settings.OrganizationSettings(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 = gcs_organization_settings.OrganizationSettings.pb(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_organization_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/v1/{organization_settings.name=organizations/*/organizationSettings}" % client.transport._host, args[1]) + + +def test_update_organization_settings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +def test_update_organization_settings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, + dict, +]) +def test_update_security_health_analytics_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'security_health_analytics_custom_module': {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'}} + request_init["security_health_analytics_custom_module"] = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2', 'display_name': 'display_name_value', 'enablement_state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_value', 'ancestor_module': 'ancestor_module_value', 'custom_config': {'predicate': {'expression': 'expression_value', 'title': 'title_value', 'description': 'description_value', 'location': 'location_value'}, 'custom_output': {'properties': [{'name': 'name_value', 'value_expression': {}}]}, 'resource_selector': {'resource_types': ['resource_types_value1', 'resource_types_value2']}, 'severity': 1, 'description': 'description_value', 'recommendation': 'recommendation_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 = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.meta.fields["security_health_analytics_custom_module"] + + 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["security_health_analytics_custom_module"].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["security_health_analytics_custom_module"][field])): + del request_init["security_health_analytics_custom_module"][field][i][subfield] + else: + del request_init["security_health_analytics_custom_module"][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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( + name='name_value', + display_name='display_name_value', + enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, + last_editor='last_editor_value', + ancestor_module='ancestor_module_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) + 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_security_health_analytics_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED + assert response.last_editor == 'last_editor_value' + assert response.ancestor_module == 'ancestor_module_value' + +def test_update_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_health_analytics_custom_module] = mock_rpc + + request = {} + client.update_security_health_analytics_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_health_analytics_custom_module(request) + + # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_security_health_analytics_custom_module._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_security_health_analytics_custom_module._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) + 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_security_health_analytics_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_security_health_analytics_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_security_health_analytics_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("securityHealthAnalyticsCustomModule", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_security_health_analytics_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_health_analytics_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_health_analytics_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.to_json(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) + + request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + client.update_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'security_health_analytics_custom_module': {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_security_health_analytics_custom_module(request) + + +def test_update_security_health_analytics_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'security_health_analytics_custom_module': {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(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_security_health_analytics_custom_module(**mock_args) + + # Establish that the underlying call 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/{security_health_analytics_custom_module.name=organizations/*/securityHealthAnalyticsSettings/customModules/*}" % client.transport._host, args[1]) + + +def test_update_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_health_analytics_custom_module( + securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(), + security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_security_health_analytics_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.UpdateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_source(request) + + +def test_update_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_update_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + + +def test_update_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + request_init["security_marks"] = {'name': 'organizations/sample1/assets/sample2/securityMarks', 'marks': {}, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] + + 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["security_marks"].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["security_marks"][field])): + del request_init["security_marks"][field][i][subfield] + else: + del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + +def test_update_security_marks_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_security_marks._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_security_marks._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("start_time", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_security_marks_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_security_marks._get_unset_required_fields({}) + assert set(unset_fields) == (set(("startTime", "updateMask", )) & set(("securityMarks", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_security_marks_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) + + request = securitycenter_service.UpdateSecurityMarksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_security_marks.SecurityMarks() + + client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_security_marks(request) + + +def test_update_security_marks_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + + # get arguments that satisfy an http rule for this method + sample_request = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + + # get truthy value for each flattened field + mock_args = dict( + security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) + + # Establish that the underlying call 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/{security_marks.name=organizations/*/assets/*/securityMarks}" % client.transport._host, args[1]) + + +def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + +def test_update_security_marks_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateBigQueryExportRequest, + dict, +]) +def test_create_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["big_query_export"] = {'name': 'name_value', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.CreateBigQueryExportRequest.meta.fields["big_query_export"] + + 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["big_query_export"].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["big_query_export"][field])): + del request_init["big_query_export"][field][i][subfield] + else: + del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + +def test_create_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + + request = {} + client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.CreateBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["big_query_export_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 "bigQueryExportId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "bigQueryExportId" in jsonified_request + assert jsonified_request["bigQueryExportId"] == request_init["big_query_export_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["bigQueryExportId"] = 'big_query_export_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("big_query_export_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 "bigQueryExportId" in jsonified_request + assert jsonified_request["bigQueryExportId"] == 'big_query_export_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + expected_params = [ + ( + "bigQueryExportId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(("bigQueryExportId", )) & set(("parent", "bigQueryExport", "bigQueryExportId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_big_query_export") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_big_query_export") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateBigQueryExportRequest.pb(securitycenter_service.CreateBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) + + request = securitycenter_service.CreateBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.create_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_big_query_export(request) + + +def test_create_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) + + # Establish that the underlying call 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=organizations/*}/bigQueryExports" % client.transport._host, args[1]) + + +def test_create_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_id_value', + ) + + +def test_create_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteBigQueryExportRequest, + dict, +]) +def test_delete_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/bigQueryExports/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 = 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + + request = {} + client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.DeleteBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + 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_big_query_export(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_big_query_export") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteBigQueryExportRequest.pb(securitycenter_service.DeleteBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/bigQueryExports/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_big_query_export(request) + + +def test_delete_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/bigQueryExports/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_big_query_export(**mock_args) + + # Establish that the underlying call 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=organizations/*/bigQueryExports/*}" % client.transport._host, args[1]) + + +def test_delete_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name='name_value', + ) + + +def test_delete_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateBigQueryExportRequest, + dict, +]) +def test_update_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'big_query_export': {'name': 'organizations/sample1/bigQueryExports/sample2'}} + request_init["big_query_export"] = {'name': 'organizations/sample1/bigQueryExports/sample2', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.UpdateBigQueryExportRequest.meta.fields["big_query_export"] + + 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["big_query_export"].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["big_query_export"][field])): + del request_init["big_query_export"][field][i][subfield] + else: + del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + +def test_update_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc + + request = {} + client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.UpdateBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_big_query_export._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_big_query_export._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("bigQueryExport", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_big_query_export") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_big_query_export") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateBigQueryExportRequest.pb(securitycenter_service.UpdateBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) + + request = securitycenter_service.UpdateBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.update_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'big_query_export': {'name': 'organizations/sample1/bigQueryExports/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_big_query_export(request) + + +def test_update_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = {'big_query_export': {'name': 'organizations/sample1/bigQueryExports/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + big_query_export=bigquery_export.BigQueryExport(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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) + + # Establish that the underlying call 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/{big_query_export.name=organizations/*/bigQueryExports/*}" % client.transport._host, args[1]) + + +def test_update_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListBigQueryExportsRequest, + dict, +]) +def test_list_big_query_exports_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) + 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_big_query_exports(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_big_query_exports_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_big_query_exports in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc + + request = {} + client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_big_query_exports(request) + + # Establish 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_big_query_exports_rest_required_fields(request_type=securitycenter_service.ListBigQueryExportsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_big_query_exports._get_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_big_query_exports._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListBigQueryExportsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) + 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_big_query_exports(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_big_query_exports_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_big_query_exports._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_big_query_exports_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_big_query_exports") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_big_query_exports") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListBigQueryExportsRequest.pb(securitycenter_service.ListBigQueryExportsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListBigQueryExportsResponse.to_json(securitycenter_service.ListBigQueryExportsResponse()) + + request = securitycenter_service.ListBigQueryExportsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListBigQueryExportsResponse() + + client.list_big_query_exports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_big_query_exports_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListBigQueryExportsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_big_query_exports(request) + + +def test_list_big_query_exports_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListBigQueryExportsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse.pb(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_big_query_exports(**mock_args) + + # Establish that the underlying call 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=organizations/*}/bigQueryExports" % client.transport._host, args[1]) + + +def test_list_big_query_exports_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent='parent_value', + ) + + +def test_list_big_query_exports_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListBigQueryExportsResponse.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': 'organizations/sample1'} + + pager = client.list_big_query_exports(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, bigquery_export.BigQueryExport) + for i in results) + + pages = list(client.list_big_query_exports(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_create_event_threat_detection_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request_init["event_threat_detection_custom_module"] = {'name': 'name_value', 'config': {'fields': {}}, 'ancestor_module': 'ancestor_module_value', 'enablement_state': 1, 'type_': 'type__value', 'display_name': 'display_name_value', 'description': 'description_value', 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_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 = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.meta.fields["event_threat_detection_custom_module"] + + 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["event_threat_detection_custom_module"].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["event_threat_detection_custom_module"][field])): + del request_init["event_threat_detection_custom_module"][field][i][subfield] + else: + del request_init["event_threat_detection_custom_module"][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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) + 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_event_threat_detection_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + +def test_create_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc + + request = {} + client.create_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_event_threat_detection_custom_module(request) + + # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_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_event_threat_detection_custom_module._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) + 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_event_threat_detection_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_event_threat_detection_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_event_threat_detection_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "eventThreatDetectionCustomModule", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_event_threat_detection_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_event_threat_detection_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_event_threat_detection_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.CreateEventThreatDetectionCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.to_json(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + + request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + client.create_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_event_threat_detection_custom_module(request) + + +def test_create_event_threat_detection_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(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_event_threat_detection_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/customModules" % client.transport._host, args[1]) + + +def test_create_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_event_threat_detection_custom_module( + securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(), + parent='parent_value', + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + ) + + +def test_create_event_threat_detection_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_delete_event_threat_detection_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/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 = 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_event_threat_detection_custom_module(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc + + request = {} + client.delete_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_event_threat_detection_custom_module(request) + + # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + 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_event_threat_detection_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_event_threat_detection_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_event_threat_detection_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_event_threat_detection_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_event_threat_detection_custom_module") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_event_threat_detection_custom_module(request) + + +def test_delete_event_threat_detection_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/eventThreatDetectionSettings/customModules/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_event_threat_detection_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings/customModules/*}" % client.transport._host, args[1]) + + +def test_delete_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_event_threat_detection_custom_module( + securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + + +def test_delete_event_threat_detection_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_get_event_threat_detection_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/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 = event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) + 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_event_threat_detection_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + +def test_get_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_event_threat_detection_custom_module] = mock_rpc + + request = {} + client.get_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_event_threat_detection_custom_module(request) + + # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.GetEventThreatDetectionCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) + 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_event_threat_detection_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_event_threat_detection_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_event_threat_detection_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_event_threat_detection_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_event_threat_detection_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_event_threat_detection_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.GetEventThreatDetectionCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = event_threat_detection_custom_module.EventThreatDetectionCustomModule.to_json(event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + + request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + client.get_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetEventThreatDetectionCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_event_threat_detection_custom_module(request) + + +def test_get_event_threat_detection_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/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 = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(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_event_threat_detection_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings/customModules/*}" % client.transport._host, args[1]) + + +def test_get_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_event_threat_detection_custom_module( + securitycenter_service.GetEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + + +def test_get_event_threat_detection_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, + dict, +]) +def test_list_descendant_event_threat_detection_custom_modules_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(return_value) + 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_descendant_event_threat_detection_custom_modules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDescendantEventThreatDetectionCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_descendant_event_threat_detection_custom_modules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_descendant_event_threat_detection_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_descendant_event_threat_detection_custom_modules] = mock_rpc + + request = {} + client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_descendant_event_threat_detection_custom_modules(request) + + # Establish 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_descendant_event_threat_detection_custom_modules_rest_required_fields(request_type=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_descendant_event_threat_detection_custom_modules._get_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_descendant_event_threat_detection_custom_modules._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(return_value) + 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_descendant_event_threat_detection_custom_modules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_descendant_event_threat_detection_custom_modules_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_descendant_event_threat_detection_custom_modules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_descendant_event_threat_detection_custom_modules_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_descendant_event_threat_detection_custom_modules") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_descendant_event_threat_detection_custom_modules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.pb(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.to_json(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse()) + + request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + + client.list_descendant_event_threat_detection_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_descendant_event_threat_detection_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_descendant_event_threat_detection_custom_modules(request) + + +def test_list_descendant_event_threat_detection_custom_modules_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + + # 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 = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(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_descendant_event_threat_detection_custom_modules(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/customModules:listDescendant" % client.transport._host, args[1]) + + +def test_list_descendant_event_threat_detection_custom_modules_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_descendant_event_threat_detection_custom_modules( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_descendant_event_threat_detection_custom_modules_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.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': 'organizations/sample1/eventThreatDetectionSettings'} + + pager = client.list_descendant_event_threat_detection_custom_modules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + for i in results) + + pages = list(client.list_descendant_event_threat_detection_custom_modules(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListEventThreatDetectionCustomModulesRequest, + dict, +]) +def test_list_event_threat_detection_custom_modules_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(return_value) + 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_event_threat_detection_custom_modules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventThreatDetectionCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_event_threat_detection_custom_modules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_event_threat_detection_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_event_threat_detection_custom_modules] = mock_rpc + + request = {} + client.list_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_event_threat_detection_custom_modules(request) + + # Establish 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_event_threat_detection_custom_modules_rest_required_fields(request_type=securitycenter_service.ListEventThreatDetectionCustomModulesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_event_threat_detection_custom_modules._get_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_event_threat_detection_custom_modules._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(return_value) + 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_event_threat_detection_custom_modules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_event_threat_detection_custom_modules_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_event_threat_detection_custom_modules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_event_threat_detection_custom_modules_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_event_threat_detection_custom_modules") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_event_threat_detection_custom_modules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListEventThreatDetectionCustomModulesRequest.pb(securitycenter_service.ListEventThreatDetectionCustomModulesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.to_json(securitycenter_service.ListEventThreatDetectionCustomModulesResponse()) + + request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + + client.list_event_threat_detection_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_event_threat_detection_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListEventThreatDetectionCustomModulesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_event_threat_detection_custom_modules(request) + + +def test_list_event_threat_detection_custom_modules_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + + # 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 = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(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_event_threat_detection_custom_modules(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/customModules" % client.transport._host, args[1]) + + +def test_list_event_threat_detection_custom_modules_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_event_threat_detection_custom_modules( + securitycenter_service.ListEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_event_threat_detection_custom_modules_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEventThreatDetectionCustomModulesResponse( + event_threat_detection_custom_modules=[ + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + event_threat_detection_custom_module.EventThreatDetectionCustomModule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListEventThreatDetectionCustomModulesResponse.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': 'organizations/sample1/eventThreatDetectionSettings'} + + pager = client.list_event_threat_detection_custom_modules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, event_threat_detection_custom_module.EventThreatDetectionCustomModule) + for i in results) + + pages = list(client.list_event_threat_detection_custom_modules(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_update_event_threat_detection_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'event_threat_detection_custom_module': {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'}} + request_init["event_threat_detection_custom_module"] = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2', 'config': {'fields': {}}, 'ancestor_module': 'ancestor_module_value', 'enablement_state': 1, 'type_': 'type__value', 'display_name': 'display_name_value', 'description': 'description_value', 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_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 = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.meta.fields["event_threat_detection_custom_module"] + + 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["event_threat_detection_custom_module"].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["event_threat_detection_custom_module"][field])): + del request_init["event_threat_detection_custom_module"][field][i][subfield] + else: + del request_init["event_threat_detection_custom_module"][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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( + name='name_value', + ancestor_module='ancestor_module_value', + enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + last_editor='last_editor_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) + 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_event_threat_detection_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.ancestor_module == 'ancestor_module_value' + assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.last_editor == 'last_editor_value' + +def test_update_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_event_threat_detection_custom_module] = mock_rpc + + request = {} + client.update_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_event_threat_detection_custom_module(request) + + # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_event_threat_detection_custom_module._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_event_threat_detection_custom_module._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) + 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_event_threat_detection_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_event_threat_detection_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_event_threat_detection_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("eventThreatDetectionCustomModule", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_event_threat_detection_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_event_threat_detection_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_event_threat_detection_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.to_json(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) + + request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + client.update_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'event_threat_detection_custom_module': {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_event_threat_detection_custom_module(request) + + +def test_update_event_threat_detection_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'event_threat_detection_custom_module': {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(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_event_threat_detection_custom_module(**mock_args) + + # Establish that the underlying call 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/{event_threat_detection_custom_module.name=organizations/*/eventThreatDetectionSettings/customModules/*}" % client.transport._host, args[1]) + + +def test_update_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_event_threat_detection_custom_module( + securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(), + event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_event_threat_detection_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_validate_event_threat_detection_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.pb(return_value) + 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_event_threat_detection_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) + +def test_validate_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc + + request = {} + client.validate_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.validate_event_threat_detection_custom_module(request) + + # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["raw_text"] = "" + request_init["type_"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["rawText"] = 'raw_text_value' + jsonified_request["type"] = 'type__value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).validate_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "rawText" in jsonified_request + assert jsonified_request["rawText"] == 'raw_text_value' + assert "type" in jsonified_request + assert jsonified_request["type"] == 'type__value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.pb(return_value) + 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_event_threat_detection_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_validate_event_threat_detection_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.validate_event_threat_detection_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "rawText", "type", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_validate_event_threat_detection_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_validate_event_threat_detection_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_validate_event_threat_detection_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.to_json(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse()) + + request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() + + client.validate_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_validate_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.validate_event_threat_detection_custom_module(request) + + +def test_validate_event_threat_detection_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, + dict, +]) +def test_get_effective_event_threat_detection_custom_module_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/effectiveCustomModules/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 = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( + name='name_value', + enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, + type_='type__value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(return_value) + 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_effective_event_threat_detection_custom_module(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) + assert response.name == 'name_value' + assert response.enablement_state == effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED + assert response.type_ == 'type__value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_get_effective_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_effective_event_threat_detection_custom_module in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_effective_event_threat_detection_custom_module] = mock_rpc + + request = {} + client.get_effective_event_threat_detection_custom_module(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_effective_event_threat_detection_custom_module(request) + + # Establish 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_effective_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_effective_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_effective_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(return_value) + 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_effective_event_threat_detection_custom_module(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_effective_event_threat_detection_custom_module_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_effective_event_threat_detection_custom_module._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_effective_event_threat_detection_custom_module_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_effective_event_threat_detection_custom_module") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_effective_event_threat_detection_custom_module") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.to_json(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule()) + + request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + + client.get_effective_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_effective_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/effectiveCustomModules/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_effective_event_threat_detection_custom_module(request) + + +def test_get_effective_event_threat_detection_custom_module_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/eventThreatDetectionSettings/effectiveCustomModules/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 = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(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_effective_event_threat_detection_custom_module(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings/effectiveCustomModules/*}" % client.transport._host, args[1]) + + +def test_get_effective_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_effective_event_threat_detection_custom_module( + securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(), + name='name_value', + ) + + +def test_get_effective_event_threat_detection_custom_module_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, + dict, +]) +def test_list_effective_event_threat_detection_custom_modules_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(return_value) + 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_effective_event_threat_detection_custom_modules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEffectiveEventThreatDetectionCustomModulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_effective_event_threat_detection_custom_modules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_effective_event_threat_detection_custom_modules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_effective_event_threat_detection_custom_modules] = mock_rpc + + request = {} + client.list_effective_event_threat_detection_custom_modules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_effective_event_threat_detection_custom_modules(request) + + # Establish 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_effective_event_threat_detection_custom_modules_rest_required_fields(request_type=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_effective_event_threat_detection_custom_modules._get_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_effective_event_threat_detection_custom_modules._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(return_value) + 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_effective_event_threat_detection_custom_modules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_effective_event_threat_detection_custom_modules_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_effective_event_threat_detection_custom_modules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_effective_event_threat_detection_custom_modules_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_effective_event_threat_detection_custom_modules") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_effective_event_threat_detection_custom_modules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.pb(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.to_json(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse()) + + request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + + client.list_effective_event_threat_detection_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_effective_event_threat_detection_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_effective_event_threat_detection_custom_modules(request) + + +def test_list_effective_event_threat_detection_custom_modules_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} + + # 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 = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(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_effective_event_threat_detection_custom_modules(**mock_args) + + # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/effectiveCustomModules" % client.transport._host, args[1]) + + +def test_list_effective_event_threat_detection_custom_modules_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_effective_event_threat_detection_custom_modules( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(), + parent='parent_value', + ) + + +def test_list_effective_event_threat_detection_custom_modules_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='abc', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[], + next_page_token='def', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( + effective_event_threat_detection_custom_modules=[ + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.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': 'organizations/sample1/eventThreatDetectionSettings'} + + pager = client.list_effective_event_threat_detection_custom_modules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) + for i in results) + + pages = list(client.list_effective_event_threat_detection_custom_modules(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.BatchCreateResourceValueConfigsRequest, + dict, +]) +def test_batch_create_resource_value_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.BatchCreateResourceValueConfigsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) + +def test_batch_create_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc + + request = {} + client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_resource_value_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_batch_create_resource_value_configs_rest_required_fields(request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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()).batch_create_resource_value_configs._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_create_resource_value_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_create_resource_value_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_resource_value_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_batch_create_resource_value_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_batch_create_resource_value_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(securitycenter_service.BatchCreateResourceValueConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.BatchCreateResourceValueConfigsResponse.to_json(securitycenter_service.BatchCreateResourceValueConfigsResponse()) + + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + client.batch_create_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_create_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_create_resource_value_configs(request) + + +def test_batch_create_resource_value_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(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.batch_create_resource_value_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=organizations/*}/resourceValueConfigs:batchCreate" % client.transport._host, args[1]) + + +def test_batch_create_resource_value_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], + ) + + +def test_batch_create_resource_value_configs_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteResourceValueConfigRequest, + dict, +]) +def test_delete_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = 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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + + request = {} + client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.DeleteResourceValueConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( + 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_resource_value_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_resource_value_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteResourceValueConfigRequest.pb(securitycenter_service.DeleteResourceValueConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteResourceValueConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteResourceValueConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_resource_value_config(request) + + +def test_delete_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/resourceValueConfigs/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_resource_value_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=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_resource_value_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name='name_value', + ) + + +def test_delete_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetResourceValueConfigRequest, + dict, +]) +def test_get_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + +def test_get_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc + + request = {} + client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.GetResourceValueConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource_value_config.ResourceValueConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_resource_value_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_resource_value_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetResourceValueConfigRequest.pb(securitycenter_service.GetResourceValueConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource_value_config.ResourceValueConfig.to_json(resource_value_config.ResourceValueConfig()) + + request = securitycenter_service.GetResourceValueConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource_value_config.ResourceValueConfig() + + client.get_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetResourceValueConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_resource_value_config(request) + + +def test_get_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resource_value_config.ResourceValueConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig.pb(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_resource_value_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=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) + + +def test_get_resource_value_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name='name_value', + ) + + +def test_get_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListResourceValueConfigsRequest, + dict, +]) +def test_list_resource_value_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc + + request = {} + client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_value_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_resource_value_configs_rest_required_fields(request_type=securitycenter_service.ListResourceValueConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListResourceValueConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_resource_value_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_resource_value_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_resource_value_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_resource_value_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_resource_value_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListResourceValueConfigsRequest.pb(securitycenter_service.ListResourceValueConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListResourceValueConfigsResponse.to_json(securitycenter_service.ListResourceValueConfigsResponse()) + + request = securitycenter_service.ListResourceValueConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListResourceValueConfigsResponse() + + client.list_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListResourceValueConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_resource_value_configs(request) + + +def test_list_resource_value_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListResourceValueConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse.pb(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_resource_value_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=organizations/*}/resourceValueConfigs" % client.transport._host, args[1]) + + +def test_list_resource_value_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent='parent_value', + ) + + +def test_list_resource_value_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListResourceValueConfigsResponse.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': 'organizations/sample1'} + + pager = client.list_resource_value_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource_value_config.ResourceValueConfig) + for i in results) + + pages = list(client.list_resource_value_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateResourceValueConfigRequest, + dict, +]) +def test_update_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} + request_init["resource_value_config"] = {'name': 'organizations/sample1/resourceValueConfigs/sample2', 'resource_value': 1, 'tag_values': ['tag_values_value1', 'tag_values_value2'], 'resource_type': 'resource_type_value', 'scope': 'scope_value', 'resource_labels_selector': {}, 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'cloud_provider': 1, 'sensitive_data_protection_mapping': {'high_sensitivity_mapping': 1, 'medium_sensitivity_mapping': 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 = securitycenter_service.UpdateResourceValueConfigRequest.meta.fields["resource_value_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["resource_value_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["resource_value_config"][field])): + del request_init["resource_value_config"][field][i][subfield] + else: + del request_init["resource_value_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 = gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + +def test_update_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + + request = {} + client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.UpdateResourceValueConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_resource_value_config.ResourceValueConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("resourceValueConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_resource_value_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_resource_value_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateResourceValueConfigRequest.pb(securitycenter_service.UpdateResourceValueConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_resource_value_config.ResourceValueConfig.to_json(gcs_resource_value_config.ResourceValueConfig()) + + request = securitycenter_service.UpdateResourceValueConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_resource_value_config.ResourceValueConfig() + + client.update_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateResourceValueConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_resource_value_config(request) + + +def test_update_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_resource_value_config.ResourceValueConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + resource_value_config=gcs_resource_value_config.ResourceValueConfig(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 = gcs_resource_value_config.ResourceValueConfig.pb(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_resource_value_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/{resource_value_config.name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) + + +def test_update_resource_value_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListValuedResourcesRequest, + dict, +]) +def test_list_valued_resources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) + 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_valued_resources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_list_valued_resources_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_valued_resources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc + + request = {} + client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_valued_resources(request) + + # Establish 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_valued_resources_rest_required_fields(request_type=securitycenter_service.ListValuedResourcesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_valued_resources._get_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_valued_resources._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListValuedResourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) + 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_valued_resources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_valued_resources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_valued_resources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_valued_resources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_valued_resources") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_valued_resources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListValuedResourcesRequest.pb(securitycenter_service.ListValuedResourcesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListValuedResourcesResponse.to_json(securitycenter_service.ListValuedResourcesResponse()) + + request = securitycenter_service.ListValuedResourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListValuedResourcesResponse() + + client.list_valued_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_valued_resources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListValuedResourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_valued_resources(request) + + +def test_list_valued_resources_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListValuedResourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse.pb(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_valued_resources(**mock_args) + + # Establish that the underlying call 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=organizations/*/simulations/*}/valuedResources" % client.transport._host, args[1]) + + +def test_list_valued_resources_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent='parent_value', + ) + + +def test_list_valued_resources_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListValuedResourcesResponse.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': 'organizations/sample1/simulations/sample2'} + + pager = client.list_valued_resources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, valued_resource.ValuedResource) + for i in results) + + pages = list(client.list_valued_resources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListAttackPathsRequest, + dict, +]) +def test_list_attack_paths_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) + 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_attack_paths(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_attack_paths_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_attack_paths in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc + + request = {} + client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_attack_paths(request) + + # Establish 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_attack_paths_rest_required_fields(request_type=securitycenter_service.ListAttackPathsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_attack_paths._get_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_attack_paths._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAttackPathsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) + 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_attack_paths(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_attack_paths_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_attack_paths._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_attack_paths_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_attack_paths") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_attack_paths") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListAttackPathsRequest.pb(securitycenter_service.ListAttackPathsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListAttackPathsResponse.to_json(securitycenter_service.ListAttackPathsResponse()) + + request = securitycenter_service.ListAttackPathsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListAttackPathsResponse() + + client.list_attack_paths(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_attack_paths_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAttackPathsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_attack_paths(request) + + +def test_list_attack_paths_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAttackPathsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse.pb(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_attack_paths(**mock_args) + + # Establish that the underlying call 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=organizations/*/simulations/*}/attackPaths" % client.transport._host, args[1]) + + +def test_list_attack_paths_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent='parent_value', + ) + + +def test_list_attack_paths_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListAttackPathsResponse.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': 'organizations/sample1/simulations/sample2'} + + pager = client.list_attack_paths(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, attack_path.AttackPath) + for i in results) + + pages = list(client.list_attack_paths(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.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SecurityCenterClient( + 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 = SecurityCenterClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecurityCenterClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, +]) +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() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SecurityCenterClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecurityCenterGrpcTransport, + ) + +def test_security_center_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_security_center_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.securitycenter_v1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'bulk_mute_findings', + 'create_security_health_analytics_custom_module', + 'create_source', + 'create_finding', + 'create_mute_config', + 'create_notification_config', + 'delete_mute_config', + 'delete_notification_config', + 'delete_security_health_analytics_custom_module', + 'get_simulation', + 'get_valued_resource', + 'get_big_query_export', + 'get_iam_policy', + 'get_mute_config', + 'get_notification_config', + 'get_organization_settings', + 'get_effective_security_health_analytics_custom_module', + 'get_security_health_analytics_custom_module', + 'get_source', + 'group_assets', + 'group_findings', + 'list_assets', + 'list_descendant_security_health_analytics_custom_modules', + 'list_findings', + 'list_mute_configs', + 'list_notification_configs', + 'list_effective_security_health_analytics_custom_modules', + 'list_security_health_analytics_custom_modules', + 'list_sources', + 'run_asset_discovery', + 'set_finding_state', + 'set_mute', + 'set_iam_policy', + 'test_iam_permissions', + 'simulate_security_health_analytics_custom_module', + 'update_external_system', + 'update_finding', + 'update_mute_config', + 'update_notification_config', + 'update_organization_settings', + 'update_security_health_analytics_custom_module', + 'update_source', + 'update_security_marks', + 'create_big_query_export', + 'delete_big_query_export', + 'update_big_query_export', + 'list_big_query_exports', + 'create_event_threat_detection_custom_module', + 'delete_event_threat_detection_custom_module', + 'get_event_threat_detection_custom_module', + 'list_descendant_event_threat_detection_custom_modules', + 'list_event_threat_detection_custom_modules', + 'update_event_threat_detection_custom_module', + 'validate_event_threat_detection_custom_module', + 'get_effective_event_threat_detection_custom_module', + 'list_effective_event_threat_detection_custom_modules', + 'batch_create_resource_value_configs', + 'delete_resource_value_config', + 'get_resource_value_config', + 'list_resource_value_configs', + 'update_resource_value_config', + 'list_valued_resources', + 'list_attack_paths', + '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_security_center_base_transport_with_credentials_file(): + # Instantiate the 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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + 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_security_center_base_transport_with_adc(): + # Test the default 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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +def test_security_center_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) + SecurityCenterClient() + 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_transport_auth_adc(transport_class): + # If 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, + ], +) +def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_security_center_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host 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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_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.SecurityCenterRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_security_center_rest_lro_client(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a 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 + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_no_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_with_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_security_center_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SecurityCenterClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SecurityCenterClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.bulk_mute_findings._session + session2 = client2.transport.bulk_mute_findings._session + assert session1 != session2 + session1 = client1.transport.create_security_health_analytics_custom_module._session + session2 = client2.transport.create_security_health_analytics_custom_module._session + assert session1 != session2 + session1 = client1.transport.create_source._session + session2 = client2.transport.create_source._session + assert session1 != session2 + session1 = client1.transport.create_finding._session + session2 = client2.transport.create_finding._session + assert session1 != session2 + session1 = client1.transport.create_mute_config._session + session2 = client2.transport.create_mute_config._session + assert session1 != session2 + session1 = client1.transport.create_notification_config._session + session2 = client2.transport.create_notification_config._session + assert session1 != session2 + session1 = client1.transport.delete_mute_config._session + session2 = client2.transport.delete_mute_config._session + assert session1 != session2 + session1 = client1.transport.delete_notification_config._session + session2 = client2.transport.delete_notification_config._session + assert session1 != session2 + session1 = client1.transport.delete_security_health_analytics_custom_module._session + session2 = client2.transport.delete_security_health_analytics_custom_module._session + assert session1 != session2 + session1 = client1.transport.get_simulation._session + session2 = client2.transport.get_simulation._session + assert session1 != session2 + session1 = client1.transport.get_valued_resource._session + session2 = client2.transport.get_valued_resource._session + assert session1 != session2 + session1 = client1.transport.get_big_query_export._session + session2 = client2.transport.get_big_query_export._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.get_mute_config._session + session2 = client2.transport.get_mute_config._session + assert session1 != session2 + session1 = client1.transport.get_notification_config._session + session2 = client2.transport.get_notification_config._session + assert session1 != session2 + session1 = client1.transport.get_organization_settings._session + session2 = client2.transport.get_organization_settings._session + assert session1 != session2 + session1 = client1.transport.get_effective_security_health_analytics_custom_module._session + session2 = client2.transport.get_effective_security_health_analytics_custom_module._session + assert session1 != session2 + session1 = client1.transport.get_security_health_analytics_custom_module._session + session2 = client2.transport.get_security_health_analytics_custom_module._session + assert session1 != session2 + session1 = client1.transport.get_source._session + session2 = client2.transport.get_source._session + assert session1 != session2 + session1 = client1.transport.group_assets._session + session2 = client2.transport.group_assets._session + assert session1 != session2 + session1 = client1.transport.group_findings._session + session2 = client2.transport.group_findings._session + assert session1 != session2 + session1 = client1.transport.list_assets._session + session2 = client2.transport.list_assets._session + assert session1 != session2 + session1 = client1.transport.list_descendant_security_health_analytics_custom_modules._session + session2 = client2.transport.list_descendant_security_health_analytics_custom_modules._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_mute_configs._session + session2 = client2.transport.list_mute_configs._session + assert session1 != session2 + session1 = client1.transport.list_notification_configs._session + session2 = client2.transport.list_notification_configs._session + assert session1 != session2 + session1 = client1.transport.list_effective_security_health_analytics_custom_modules._session + session2 = client2.transport.list_effective_security_health_analytics_custom_modules._session + assert session1 != session2 + session1 = client1.transport.list_security_health_analytics_custom_modules._session + session2 = client2.transport.list_security_health_analytics_custom_modules._session + assert session1 != session2 + session1 = client1.transport.list_sources._session + session2 = client2.transport.list_sources._session + assert session1 != session2 + session1 = client1.transport.run_asset_discovery._session + session2 = client2.transport.run_asset_discovery._session + assert session1 != session2 + session1 = client1.transport.set_finding_state._session + session2 = client2.transport.set_finding_state._session + assert session1 != session2 + session1 = client1.transport.set_mute._session + session2 = client2.transport.set_mute._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 + session1 = client1.transport.simulate_security_health_analytics_custom_module._session + session2 = client2.transport.simulate_security_health_analytics_custom_module._session + assert session1 != session2 + session1 = client1.transport.update_external_system._session + session2 = client2.transport.update_external_system._session + assert session1 != session2 + session1 = client1.transport.update_finding._session + session2 = client2.transport.update_finding._session + assert session1 != session2 + session1 = client1.transport.update_mute_config._session + session2 = client2.transport.update_mute_config._session + assert session1 != session2 + session1 = client1.transport.update_notification_config._session + session2 = client2.transport.update_notification_config._session + assert session1 != session2 + session1 = client1.transport.update_organization_settings._session + session2 = client2.transport.update_organization_settings._session + assert session1 != session2 + session1 = client1.transport.update_security_health_analytics_custom_module._session + session2 = client2.transport.update_security_health_analytics_custom_module._session + assert session1 != session2 + session1 = client1.transport.update_source._session + session2 = client2.transport.update_source._session + assert session1 != session2 + session1 = client1.transport.update_security_marks._session + session2 = client2.transport.update_security_marks._session + assert session1 != session2 + session1 = client1.transport.create_big_query_export._session + session2 = client2.transport.create_big_query_export._session + assert session1 != session2 + session1 = client1.transport.delete_big_query_export._session + session2 = client2.transport.delete_big_query_export._session + assert session1 != session2 + session1 = client1.transport.update_big_query_export._session + session2 = client2.transport.update_big_query_export._session + assert session1 != session2 + session1 = client1.transport.list_big_query_exports._session + session2 = client2.transport.list_big_query_exports._session + assert session1 != session2 + session1 = client1.transport.create_event_threat_detection_custom_module._session + session2 = client2.transport.create_event_threat_detection_custom_module._session + assert session1 != session2 + session1 = client1.transport.delete_event_threat_detection_custom_module._session + session2 = client2.transport.delete_event_threat_detection_custom_module._session + assert session1 != session2 + session1 = client1.transport.get_event_threat_detection_custom_module._session + session2 = client2.transport.get_event_threat_detection_custom_module._session + assert session1 != session2 + session1 = client1.transport.list_descendant_event_threat_detection_custom_modules._session + session2 = client2.transport.list_descendant_event_threat_detection_custom_modules._session + assert session1 != session2 + session1 = client1.transport.list_event_threat_detection_custom_modules._session + session2 = client2.transport.list_event_threat_detection_custom_modules._session + assert session1 != session2 + session1 = client1.transport.update_event_threat_detection_custom_module._session + session2 = client2.transport.update_event_threat_detection_custom_module._session + assert session1 != session2 + session1 = client1.transport.validate_event_threat_detection_custom_module._session + session2 = client2.transport.validate_event_threat_detection_custom_module._session + assert session1 != session2 + session1 = client1.transport.get_effective_event_threat_detection_custom_module._session + session2 = client2.transport.get_effective_event_threat_detection_custom_module._session + assert session1 != session2 + session1 = client1.transport.list_effective_event_threat_detection_custom_modules._session + session2 = client2.transport.list_effective_event_threat_detection_custom_modules._session + assert session1 != session2 + session1 = client1.transport.batch_create_resource_value_configs._session + session2 = client2.transport.batch_create_resource_value_configs._session + assert session1 != session2 + session1 = client1.transport.delete_resource_value_config._session + session2 = client2.transport.delete_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.get_resource_value_config._session + session2 = client2.transport.get_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.list_resource_value_configs._session + session2 = client2.transport.list_resource_value_configs._session + assert session1 != session2 + session1 = client1.transport.update_resource_value_config._session + session2 = client2.transport.update_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.list_valued_resources._session + session2 = client2.transport.list_valued_resources._session + assert session1 != session2 + session1 = client1.transport.list_attack_paths._session + session2 = client2.transport.list_attack_paths._session + assert session1 != session2 +def test_security_center_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcTransport( + 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_security_center_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcAsyncIOTransport( + 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(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_security_center_grpc_lro_client(): + client = SecurityCenterClient( + 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_security_center_grpc_lro_async_client(): + client = SecurityCenterAsyncClient( + 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_asset_path(): + organization = "squid" + asset = "clam" + expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.asset_path(organization, asset) + assert expected == actual + + +def test_parse_asset_path(): + expected = { + "organization": "whelk", + "asset": "octopus", + } + path = SecurityCenterClient.asset_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_asset_path(path) + assert expected == actual + +def test_attack_path_path(): + organization = "oyster" + simulation = "nudibranch" + valued_resource = "cuttlefish" + attack_path = "mussel" + expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) + actual = SecurityCenterClient.attack_path_path(organization, simulation, valued_resource, attack_path) + assert expected == actual + + +def test_parse_attack_path_path(): + expected = { + "organization": "winkle", + "simulation": "nautilus", + "valued_resource": "scallop", + "attack_path": "abalone", + } + path = SecurityCenterClient.attack_path_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_attack_path_path(path) + assert expected == actual + +def test_big_query_export_path(): + organization = "squid" + export = "clam" + expected = "organizations/{organization}/bigQueryExports/{export}".format(organization=organization, export=export, ) + actual = SecurityCenterClient.big_query_export_path(organization, export) + assert expected == actual + + +def test_parse_big_query_export_path(): + expected = { + "organization": "whelk", + "export": "octopus", + } + path = SecurityCenterClient.big_query_export_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_big_query_export_path(path) + assert expected == actual + +def test_dlp_job_path(): + project = "oyster" + dlp_job = "nudibranch" + expected = "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) + actual = SecurityCenterClient.dlp_job_path(project, dlp_job) + assert expected == actual + + +def test_parse_dlp_job_path(): + expected = { + "project": "cuttlefish", + "dlp_job": "mussel", + } + path = SecurityCenterClient.dlp_job_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_dlp_job_path(path) + assert expected == actual + +def test_effective_event_threat_detection_custom_module_path(): + organization = "winkle" + module = "nautilus" + expected = "organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}".format(organization=organization, module=module, ) + actual = SecurityCenterClient.effective_event_threat_detection_custom_module_path(organization, module) + assert expected == actual + + +def test_parse_effective_event_threat_detection_custom_module_path(): + expected = { + "organization": "scallop", + "module": "abalone", + } + path = SecurityCenterClient.effective_event_threat_detection_custom_module_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_effective_event_threat_detection_custom_module_path(path) + assert expected == actual + +def test_effective_security_health_analytics_custom_module_path(): + organization = "squid" + effective_custom_module = "clam" + expected = "organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{effective_custom_module}".format(organization=organization, effective_custom_module=effective_custom_module, ) + actual = SecurityCenterClient.effective_security_health_analytics_custom_module_path(organization, effective_custom_module) + assert expected == actual + + +def test_parse_effective_security_health_analytics_custom_module_path(): + expected = { + "organization": "whelk", + "effective_custom_module": "octopus", + } + path = SecurityCenterClient.effective_security_health_analytics_custom_module_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_effective_security_health_analytics_custom_module_path(path) + assert expected == actual + +def test_event_threat_detection_custom_module_path(): + organization = "oyster" + module = "nudibranch" + expected = "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}".format(organization=organization, module=module, ) + actual = SecurityCenterClient.event_threat_detection_custom_module_path(organization, module) + assert expected == actual + + +def test_parse_event_threat_detection_custom_module_path(): + expected = { + "organization": "cuttlefish", + "module": "mussel", + } + path = SecurityCenterClient.event_threat_detection_custom_module_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_event_threat_detection_custom_module_path(path) + assert expected == actual + +def test_external_system_path(): + organization = "winkle" + source = "nautilus" + finding = "scallop" + externalsystem = "abalone" + expected = "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) + actual = SecurityCenterClient.external_system_path(organization, source, finding, externalsystem) + assert expected == actual + + +def test_parse_external_system_path(): + expected = { + "organization": "squid", + "source": "clam", + "finding": "whelk", + "externalsystem": "octopus", + } + path = SecurityCenterClient.external_system_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_external_system_path(path) + assert expected == actual + +def test_finding_path(): + organization = "oyster" + source = "nudibranch" + finding = "cuttlefish" + expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + actual = SecurityCenterClient.finding_path(organization, source, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "organization": "mussel", + "source": "winkle", + "finding": "nautilus", + } + path = SecurityCenterClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_finding_path(path) + assert expected == actual + +def test_mute_config_path(): + organization = "scallop" + mute_config = "abalone" + expected = "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) + actual = SecurityCenterClient.mute_config_path(organization, mute_config) + assert expected == actual + + +def test_parse_mute_config_path(): + expected = { + "organization": "squid", + "mute_config": "clam", + } + path = SecurityCenterClient.mute_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_mute_config_path(path) + assert expected == actual + +def test_notification_config_path(): + organization = "whelk" + notification_config = "octopus" + expected = "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) + actual = SecurityCenterClient.notification_config_path(organization, notification_config) + assert expected == actual + + +def test_parse_notification_config_path(): + expected = { + "organization": "oyster", + "notification_config": "nudibranch", + } + path = SecurityCenterClient.notification_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_notification_config_path(path) + assert expected == actual + +def test_organization_settings_path(): + organization = "cuttlefish" + expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) + actual = SecurityCenterClient.organization_settings_path(organization) + assert expected == actual + + +def test_parse_organization_settings_path(): + expected = { + "organization": "mussel", + } + path = SecurityCenterClient.organization_settings_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_organization_settings_path(path) + assert expected == actual + +def test_policy_path(): + organization = "winkle" + constraint_name = "nautilus" + expected = "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) + actual = SecurityCenterClient.policy_path(organization, constraint_name) + assert expected == actual + + +def test_parse_policy_path(): + expected = { + "organization": "scallop", + "constraint_name": "abalone", + } + path = SecurityCenterClient.policy_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_policy_path(path) + assert expected == actual + +def test_resource_value_config_path(): + organization = "squid" + resource_value_config = "clam" + expected = "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) + actual = SecurityCenterClient.resource_value_config_path(organization, resource_value_config) + assert expected == actual + + +def test_parse_resource_value_config_path(): + expected = { + "organization": "whelk", + "resource_value_config": "octopus", + } + path = SecurityCenterClient.resource_value_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_resource_value_config_path(path) + assert expected == actual + +def test_security_health_analytics_custom_module_path(): + organization = "oyster" + custom_module = "nudibranch" + expected = "organizations/{organization}/securityHealthAnalyticsSettings/customModules/{custom_module}".format(organization=organization, custom_module=custom_module, ) + actual = SecurityCenterClient.security_health_analytics_custom_module_path(organization, custom_module) + assert expected == actual + + +def test_parse_security_health_analytics_custom_module_path(): + expected = { + "organization": "cuttlefish", + "custom_module": "mussel", + } + path = SecurityCenterClient.security_health_analytics_custom_module_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_health_analytics_custom_module_path(path) + assert expected == actual + +def test_security_marks_path(): + organization = "winkle" + asset = "nautilus" + expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.security_marks_path(organization, asset) + assert expected == actual + + +def test_parse_security_marks_path(): + expected = { + "organization": "scallop", + "asset": "abalone", + } + path = SecurityCenterClient.security_marks_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_marks_path(path) + assert expected == actual + +def test_simulation_path(): + organization = "squid" + simulation = "clam" + expected = "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) + actual = SecurityCenterClient.simulation_path(organization, simulation) + assert expected == actual + + +def test_parse_simulation_path(): + expected = { + "organization": "whelk", + "simulation": "octopus", + } + path = SecurityCenterClient.simulation_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_simulation_path(path) + assert expected == actual + +def test_source_path(): + organization = "oyster" + source = "nudibranch" + expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + actual = SecurityCenterClient.source_path(organization, source) + assert expected == actual + + +def test_parse_source_path(): + expected = { + "organization": "cuttlefish", + "source": "mussel", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_path(path) + assert expected == actual + +def test_table_data_profile_path(): + project = "winkle" + table_profile = "nautilus" + expected = "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) + actual = SecurityCenterClient.table_data_profile_path(project, table_profile) + assert expected == actual + + +def test_parse_table_data_profile_path(): + expected = { + "project": "scallop", + "table_profile": "abalone", + } + path = SecurityCenterClient.table_data_profile_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_table_data_profile_path(path) + assert expected == actual + +def test_topic_path(): + project = "squid" + topic = "clam" + expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + actual = SecurityCenterClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "whelk", + "topic": "octopus", + } + path = SecurityCenterClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_topic_path(path) + assert expected == actual + +def test_valued_resource_path(): + organization = "oyster" + simulation = "nudibranch" + valued_resource = "cuttlefish" + expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) + actual = SecurityCenterClient.valued_resource_path(organization, simulation, valued_resource) + assert expected == actual + + +def test_parse_valued_resource_path(): + expected = { + "organization": "mussel", + "simulation": "winkle", + "valued_resource": "nautilus", + } + path = SecurityCenterClient.valued_resource_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_valued_resource_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SecurityCenterClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = SecurityCenterClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = SecurityCenterClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = SecurityCenterClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SecurityCenterClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = SecurityCenterClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = SecurityCenterClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = SecurityCenterClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SecurityCenterClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = SecurityCenterClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + transport_class = SecurityCenterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations/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 = 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.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations/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 = 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_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations/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() + + # 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 + + 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(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations'}, 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() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations'} + request = request_type(**request_init) + # Mock the http request call within the method and 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.ListOperationsResponse() + + # 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), +]) +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-securitycenter/v1beta1/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v1beta1/.coveragerc new file mode 100644 index 000000000000..45cb273f8f7c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/securitycenter/__init__.py + google/cloud/securitycenter/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-securitycenter/v1beta1/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v1beta1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/.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-securitycenter/v1beta1/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v1beta1/MANIFEST.in new file mode 100644 index 000000000000..328e3b8929b0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/securitycenter *.py +recursive-include google/cloud/securitycenter_v1beta1 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst new file mode 100644 index 000000000000..f8c63f4cb48a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v1beta1/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/conf.py new file mode 100644 index 000000000000..8e92d2319721 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter 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-securitycenter" +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-securitycenter-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-securitycenter.tex", + u"google-cloud-securitycenter 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-securitycenter", + u"Google Cloud Securitycenter 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-securitycenter", + u"google-cloud-securitycenter Documentation", + author, + "google-cloud-securitycenter", + "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v1beta1/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/index.rst new file mode 100644 index 000000000000..883606269b5e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + securitycenter_v1beta1/services + securitycenter_v1beta1/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst new file mode 100644 index 000000000000..304849ecc112 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst @@ -0,0 +1,10 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center + :members: + :inherited-members: + +.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst new file mode 100644 index 000000000000..a09a4b86906d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v1beta1 API +==================================================== +.. toctree:: + :maxdepth: 2 + + security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst new file mode 100644 index 000000000000..0bbeba064657 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Securitycenter v1beta1 API +================================================= + +.. automodule:: google.cloud.securitycenter_v1beta1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__init__.py new file mode 100644 index 000000000000..34bcf9197d85 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__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.cloud.securitycenter import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.securitycenter_v1beta1.services.security_center.client import SecurityCenterClient +from google.cloud.securitycenter_v1beta1.services.security_center.async_client import SecurityCenterAsyncClient + +from google.cloud.securitycenter_v1beta1.types.asset import Asset +from google.cloud.securitycenter_v1beta1.types.finding import Finding +from google.cloud.securitycenter_v1beta1.types.organization_settings import OrganizationSettings +from google.cloud.securitycenter_v1beta1.types.run_asset_discovery_response import RunAssetDiscoveryResponse +from google.cloud.securitycenter_v1beta1.types.security_marks import SecurityMarks +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import CreateFindingRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import CreateSourceRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GetOrganizationSettingsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GetSourceRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupAssetsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupAssetsResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupFindingsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupFindingsResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupResult +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListAssetsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListAssetsResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListFindingsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListFindingsResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListSourcesRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListSourcesResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import RunAssetDiscoveryRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import SetFindingStateRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateFindingRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateOrganizationSettingsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateSecurityMarksRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateSourceRequest +from google.cloud.securitycenter_v1beta1.types.source import Source + +__all__ = ('SecurityCenterClient', + 'SecurityCenterAsyncClient', + 'Asset', + 'Finding', + 'OrganizationSettings', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateSourceRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/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-securitycenter/v1beta1/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py new file mode 100644 index 000000000000..4f049ee47efe --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__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.cloud.securitycenter_v1beta1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + +from .types.asset import Asset +from .types.finding import Finding +from .types.organization_settings import OrganizationSettings +from .types.run_asset_discovery_response import RunAssetDiscoveryResponse +from .types.security_marks import SecurityMarks +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import GetOrganizationSettingsRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GroupAssetsRequest +from .types.securitycenter_service import GroupAssetsResponse +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAssetsRequest +from .types.securitycenter_service import ListAssetsResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import RunAssetDiscoveryRequest +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateOrganizationSettingsRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.source import Source + +__all__ = ( + 'SecurityCenterAsyncClient', +'Asset', +'CreateFindingRequest', +'CreateSourceRequest', +'Finding', +'GetOrganizationSettingsRequest', +'GetSourceRequest', +'GroupAssetsRequest', +'GroupAssetsResponse', +'GroupFindingsRequest', +'GroupFindingsResponse', +'GroupResult', +'ListAssetsRequest', +'ListAssetsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListSourcesRequest', +'ListSourcesResponse', +'OrganizationSettings', +'RunAssetDiscoveryRequest', +'RunAssetDiscoveryResponse', +'SecurityCenterClient', +'SecurityMarks', +'SetFindingStateRequest', +'Source', +'UpdateFindingRequest', +'UpdateOrganizationSettingsRequest', +'UpdateSecurityMarksRequest', +'UpdateSourceRequest', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json new file mode 100644 index 000000000000..afd9dcb019c2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json @@ -0,0 +1,298 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v1beta1", + "protoPackage": "google.cloud.securitycenter.v1beta1", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "rest": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/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-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/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-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py new file mode 100644 index 000000000000..bffcff5da306 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + 'SecurityCenterClient', + 'SecurityCenterAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py new file mode 100644 index 000000000000..6e93123eb92f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.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. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.securitycenter_v1beta1 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.securitycenter_v1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V1 Beta APIs for Security Center service.""" + + _client: SecurityCenterClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE + + asset_path = staticmethod(SecurityCenterClient.asset_path) + parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) + parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) + organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) + parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) + source_path = staticmethod(SecurityCenterClient.source_path) + parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) + common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) + parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) + common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) + parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) + common_project_path = staticmethod(SecurityCenterClient.common_project_path) + parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) + common_location_path = staticmethod(SecurityCenterClient.common_location_path) + parse_common_location_path = staticmethod(SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v1beta1 + + async def sample_create_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.CreateSourceRequest, dict]]): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = 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_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding_id: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_create_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.CreateFindingRequest, dict]]): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 get_organization_settings(self, + request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest, dict]]): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_organization_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 get_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v1beta1 + + async def sample_get_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GetSourceRequest, dict]]): + The request object. Request message for getting a source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 group_assets(self, + request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsAsyncPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_group_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest, dict]]): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsAsyncPager: + Response message for grouping by + assets. + 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, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.GroupAssetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_group_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest, dict]]): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". + To groupBy across all sources provide a source_id of + ``-``. For example: + organizations/{organization_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state``). The string value + should follow SQL syntax: comma separated list of + fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets(self, + request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists an organization's assets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_list_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.ListAssetsRequest, dict]]): + The request object. Request message for listing assets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsAsyncPager: + Response message for listing assets. + + 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, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(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_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListAssetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings(self, + request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_list_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListFindingsRequest( + parent="parent_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.securitycenter_v1beta1.types.ListFindingsRequest, dict]]): + The request object. Request message for listing findings. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.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_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_list_sources(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.ListSourcesRequest, dict]]): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]". + + 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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesAsyncPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_asset_discovery(self, + request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS 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 securitycenter_v1beta1 + + async def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest, dict]]): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.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([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, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.run_asset_discovery] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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, + empty_pb2.Empty, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + start_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of 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 securitycenter_v1beta1 + + async def sample_set_finding_state(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest, dict]]): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`google.cloud.securitycenter_v1beta1.types.Finding.State`): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 update_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_update_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest, dict]]): + The request object. Request message for updating or + creating a finding. + finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe domain. + self._client._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_organization_settings(self, + request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, + *, + organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = await client.update_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest, dict]]): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`google.cloud.securitycenter_v1beta1.types.OrganizationSettings`): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_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 update_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v1beta1 + + async def sample_update_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest, dict]]): + The request object. Request message for updating a + source. + source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): + Required. The source resource to + update. + + This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + async def sample_update_security_marks(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest, dict]]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`google.cloud.securitycenter_v1beta1.types.SecurityMarks`): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe domain. + self._client._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) -> "SecurityCenterAsyncClient": + 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__ = ( + "SecurityCenterAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py new file mode 100644 index 000000000000..72d03d765968 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py @@ -0,0 +1,2755 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_v1beta1 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.securitycenter_v1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .transports.rest import SecurityCenterRestTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + _transport_registry["rest"] = SecurityCenterRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SecurityCenterTransport]: + """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V1 Beta APIs for Security Center 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 = "securitycenter.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: + SecurityCenterClient: 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: + SecurityCenterClient: 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) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def asset_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified asset string.""" + return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_asset_path(path: str) -> Dict[str,str]: + """Parses a asset path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def finding_path(organization: str,source: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def organization_settings_path(organization: str,) -> str: + """Returns a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format(organization=organization, ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str,str]: + """Parses a organization_settings path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str,str]: + """Parses a security_marks path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str,source: str,) -> str: + """Returns a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str,str]: + """Parses a source path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 + SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient._read_environment_variables() + self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) + if transport_provided: + # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SecurityCenterTransport], 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_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v1beta1 + + def sample_create_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.CreateSourceRequest, dict]): + The request object. Request message for creating a + source. + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (google.cloud.securitycenter_v1beta1.types.Source): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding_id: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_create_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.CreateFindingRequest, dict]): + The request object. Request message for creating a + finding. + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (google.cloud.securitycenter_v1beta1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 get_organization_settings(self, + request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest, dict]): + The request object. Request message for getting + organization settings. + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_organization_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 get_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v1beta1 + + def sample_get_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.GetSourceRequest, dict]): + The request object. Request message for getting a source. + name (str): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 group_assets(self, + request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_group_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest, dict]): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsPager: + Response message for grouping by + assets. + 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, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.GroupAssetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_group_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest, dict]): + The request object. Request message for grouping by + findings. + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". + To groupBy across all sources provide a source_id of + ``-``. For example: + organizations/{organization_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (str): + Required. Expression that defines what assets fields to + use for grouping (including ``state``). The string value + should follow SQL syntax: comma separated list of + fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets(self, + request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists an organization's assets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_list_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.ListAssetsRequest, dict]): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsPager: + Response message for listing assets. + + 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, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListAssetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings(self, + request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_list_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListFindingsRequest( + parent="parent_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.securitycenter_v1beta1.types.ListFindingsRequest, dict]): + The request object. Request message for listing findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsPager: + Response message for listing + findings. + 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.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_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_list_sources(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.ListSourcesRequest, dict]): + The request object. Request message for listing sources. + parent (str): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]". + + 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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_asset_discovery(self, + request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), + ) -> operation.Operation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS 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 securitycenter_v1beta1 + + def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest, dict]): + The request object. Request message for running asset + discovery for an organization. + parent (str): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.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([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, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.run_asset_discovery] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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, + empty_pb2.Empty, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + start_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of 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 securitycenter_v1beta1 + + def sample_set_finding_state(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest, dict]): + The request object. Request message for updating a + finding's state. + name (str): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (google.cloud.securitycenter_v1beta1.types.Finding.State): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # 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 + + def update_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_update_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest, dict]): + The request object. Request message for updating or + creating a finding. + finding (google.cloud.securitycenter_v1beta1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe 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_organization_settings(self, + request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, + *, + organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = client.update_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest, dict]): + The request object. Request message for updating an + organization's settings. + organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_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 update_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v1beta1 + + def sample_update_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest, dict]): + The request object. Request message for updating a + source. + source (google.cloud.securitycenter_v1beta1.types.Source): + Required. The source resource to + update. + + This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1beta1 + + def sample_update_security_marks(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest, dict]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1beta1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe 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) -> "SecurityCenterClient": + 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__ = ( + "SecurityCenterClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py new file mode 100644 index 000000000000..51807c4b0d79 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.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 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.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source + + +class GroupAssetsPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupAssetsResponse], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1beta1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + 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[securitycenter_service.GroupAssetsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupAssetsAsyncPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` + attributes are available on the 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[securitycenter_service.GroupAssetsResponse]], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1beta1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + 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[securitycenter_service.GroupAssetsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1beta1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` + attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1beta1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListAssetsResponse], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + 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[securitycenter_service.ListAssetsResponse]: + 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + for page in self.pages: + yield from page.list_assets_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` + attributes are available on the 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[securitycenter_service.ListAssetsResponse]], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + 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[securitycenter_service.ListAssetsResponse]: + 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_assets_results: + 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.securitycenter_v1beta1.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.securitycenter_v1beta1.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[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v1beta1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.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 = securitycenter_service.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[securitycenter_service.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.securitycenter_v1beta1.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.securitycenter_v1beta1.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[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v1beta1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.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 = securitycenter_service.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[securitycenter_service.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) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1beta1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` + attributes are available on the 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[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1beta1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.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-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py new file mode 100644 index 000000000000..9d36139c1a9b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/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 SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .rest import SecurityCenterRestTransport +from .rest import SecurityCenterRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry['grpc'] = SecurityCenterGrpcTransport +_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport +_transport_registry['rest'] = SecurityCenterRestTransport + +__all__ = ( + 'SecurityCenterTransport', + 'SecurityCenterGrpcTransport', + 'SecurityCenterGrpcAsyncIOTransport', + 'SecurityCenterRestTransport', + 'SecurityCenterRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py new file mode 100644 index 000000000000..9c83124b6382 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py @@ -0,0 +1,498 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.securitycenter_v1beta1 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.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +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 SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'securitycenter.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.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: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_source: gapic_v1.method.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_settings: gapic_v1.method.wrap_method( + self.get_organization_settings, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_source: gapic_v1.method.wrap_method( + self.get_source, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.group_assets: gapic_v1.method.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_sources: gapic_v1.method.wrap_method( + self.list_sources, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.run_asset_discovery: gapic_v1.method.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_finding: gapic_v1.method.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=480.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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + 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 get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Union[ + organization_settings.OrganizationSettings, + Awaitable[organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Union[ + source.Source, + Awaitable[source.Source] + ]]: + raise NotImplementedError() + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Union[ + securitycenter_service.GroupAssetsResponse, + Awaitable[securitycenter_service.GroupAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Union[ + securitycenter_service.GroupFindingsResponse, + Awaitable[securitycenter_service.GroupFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Union[ + securitycenter_service.ListAssetsResponse, + Awaitable[securitycenter_service.ListAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Union[ + securitycenter_service.ListFindingsResponse, + Awaitable[securitycenter_service.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Union[ + securitycenter_service.ListSourcesResponse, + Awaitable[securitycenter_service.ListSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + 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 test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Union[ + gcs_organization_settings.OrganizationSettings, + Awaitable[gcs_organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Union[ + gcs_security_marks.SecurityMarks, + Awaitable[gcs_security_marks.SecurityMarks] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SecurityCenterTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py new file mode 100644 index 000000000000..bd93a5f13210 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.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. +# +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.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +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 SecurityCenterTransport, DEFAULT_CLIENT_INFO + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V1 Beta APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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 create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + ~.GroupAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + 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.securitycenter.v1beta1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + operations_pb2.Operation]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + ~.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 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + ~.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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SecurityCenterGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 000000000000..47e586023e58 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,945 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +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 SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V1 Beta APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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._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 create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + 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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Awaitable[organization_settings.OrganizationSettings]]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Awaitable[securitycenter_service.GroupAssetsResponse]]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + Awaitable[~.GroupAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse]]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Awaitable[securitycenter_service.ListAssetsResponse]]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + 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.securitycenter.v1beta1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse]]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + 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 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + 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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.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.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + 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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Awaitable[gcs_organization_settings.OrganizationSettings]]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks]]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + 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_source: gapic_v1.method_async.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method_async.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_settings: gapic_v1.method_async.wrap_method( + self.get_organization_settings, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_source: gapic_v1.method_async.wrap_method( + self.get_source, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.group_assets: gapic_v1.method_async.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method_async.wrap_method( + self.group_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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method_async.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method_async.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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_sources: gapic_v1.method_async.wrap_method( + self.list_sources, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.run_asset_discovery: gapic_v1.method_async.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method_async.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_finding: gapic_v1.method_async.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method_async.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method_async.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method_async.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py new file mode 100644 index 000000000000..a44f2b2a1487 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py @@ -0,0 +1,2542 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # 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 path_template +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 +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +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 SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SecurityCenterRestInterceptor: + """Interceptor for SecurityCenter. + + 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 SecurityCenterRestTransport. + + .. code-block:: python + class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): + def pre_create_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_organization_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_organization_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_assets(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_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_run_asset_discovery(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_asset_discovery(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_finding_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_finding_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_organization_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_organization_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_security_marks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_security_marks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_source(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) + client = SecurityCenterClient(transport=transport) + + + """ + def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for create_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for create_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_organization_settings(self, request: securitycenter_service.GetOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_organization_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_organization_settings(self, response: organization_settings.OrganizationSettings) -> organization_settings.OrganizationSettings: + """Post-rpc interceptor for get_organization_settings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_source(self, response: source.Source) -> source.Source: + """Post-rpc interceptor for get_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_assets(self, request: securitycenter_service.GroupAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_assets(self, response: securitycenter_service.GroupAssetsResponse) -> securitycenter_service.GroupAssetsResponse: + """Post-rpc interceptor for group_assets + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: + """Post-rpc interceptor for group_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_assets(self, request: securitycenter_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_assets(self, response: securitycenter_service.ListAssetsResponse) -> securitycenter_service.ListAssetsResponse: + """Post-rpc interceptor for list_assets + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. + """ + return request, metadata + + def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_sources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: + """Post-rpc interceptor for list_sources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_run_asset_discovery(self, request: securitycenter_service.RunAssetDiscoveryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.RunAssetDiscoveryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for run_asset_discovery + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_run_asset_discovery(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for run_asset_discovery + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for update_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_organization_settings(self, request: securitycenter_service.UpdateOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_organization_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_organization_settings(self, response: gcs_organization_settings.OrganizationSettings) -> gcs_organization_settings.OrganizationSettings: + """Post-rpc interceptor for update_organization_settings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: + """Post-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for update_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SecurityCenterRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SecurityCenterRestInterceptor + + +class SecurityCenterRestTransport(SecurityCenterTransport): + """REST backend transport for SecurityCenter. + + V1 Beta APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[SecurityCenterRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 + 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 + ) + 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 SecurityCenterRestInterceptor() + 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': '/v1beta1/{name=organizations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1beta1/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=organizations/*/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="v1beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "findingId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the create finding method over HTTP. + + Args: + request (~.securitycenter_service.CreateFindingRequest): + The request object. Request message for creating a + finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=organizations/*/sources/*}/findings', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_create_finding(request, metadata) + pb_request = securitycenter_service.CreateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_finding(resp) + return resp + + class _CreateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the create source method over HTTP. + + Args: + request (~.securitycenter_service.CreateSourceRequest): + The request object. Request message for creating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=organizations/*}/sources', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_create_source(request, metadata) + pb_request = securitycenter_service.CreateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_source(resp) + return resp + + class _GetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{resource=organizations/*/sources/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetOrganizationSettings(SecurityCenterRestStub): + def __hash__(self): + return hash("GetOrganizationSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetOrganizationSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> organization_settings.OrganizationSettings: + r"""Call the get organization settings method over HTTP. + + Args: + request (~.securitycenter_service.GetOrganizationSettingsRequest): + The request object. Request message for getting + organization 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: + ~.organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=organizations/*/organizationSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_organization_settings(request, metadata) + pb_request = securitycenter_service.GetOrganizationSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = organization_settings.OrganizationSettings() + pb_resp = organization_settings.OrganizationSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_organization_settings(resp) + return resp + + class _GetSource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> source.Source: + r"""Call the get source method over HTTP. + + Args: + request (~.securitycenter_service.GetSourceRequest): + The request object. Request message for getting a source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=organizations/*/sources/*}', + }, + ] + request, metadata = self._interceptor.pre_get_source(request, metadata) + pb_request = securitycenter_service.GetSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = source.Source() + pb_resp = source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_source(resp) + return resp + + class _GroupAssets(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupAssetsResponse: + r"""Call the group assets method over HTTP. + + Args: + request (~.securitycenter_service.GroupAssetsRequest): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupAssetsResponse: + Response message for grouping by + assets. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=organizations/*}/assets:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_assets(request, metadata) + pb_request = securitycenter_service.GroupAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupAssetsResponse() + pb_resp = securitycenter_service.GroupAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_assets(resp) + return resp + + class _GroupFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupFindingsResponse: + r"""Call the group findings method over HTTP. + + Args: + request (~.securitycenter_service.GroupFindingsRequest): + The request object. Request message for grouping by + findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupFindingsResponse: + Response message for group by + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=organizations/*/sources/*}/findings:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_findings(request, metadata) + pb_request = securitycenter_service.GroupFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupFindingsResponse() + pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_findings(resp) + return resp + + class _ListAssets(SecurityCenterRestStub): + def __hash__(self): + return hash("ListAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListAssetsResponse: + r"""Call the list assets method over HTTP. + + Args: + request (~.securitycenter_service.ListAssetsRequest): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListAssetsResponse: + Response message for listing assets. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=organizations/*}/assets', + }, + ] + request, metadata = self._interceptor.pre_list_assets(request, metadata) + pb_request = securitycenter_service.ListAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListAssetsResponse() + pb_resp = securitycenter_service.ListAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_assets(resp) + return resp + + class _ListFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("ListFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.securitycenter_service.ListFindingsRequest): + The request object. Request message for listing findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListFindingsResponse: + Response message for listing + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=organizations/*/sources/*}/findings', + }, + ] + request, metadata = self._interceptor.pre_list_findings(request, metadata) + pb_request = securitycenter_service.ListFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListFindingsResponse() + pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListSources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListSources") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListSourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListSourcesResponse: + r"""Call the list sources method over HTTP. + + Args: + request (~.securitycenter_service.ListSourcesRequest): + The request object. Request message for listing sources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListSourcesResponse: + Response message for listing sources. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=organizations/*}/sources', + }, + ] + request, metadata = self._interceptor.pre_list_sources(request, metadata) + pb_request = securitycenter_service.ListSourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListSourcesResponse() + pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sources(resp) + return resp + + class _RunAssetDiscovery(SecurityCenterRestStub): + def __hash__(self): + return hash("RunAssetDiscovery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.RunAssetDiscoveryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the run asset discovery method over HTTP. + + Args: + request (~.securitycenter_service.RunAssetDiscoveryRequest): + The request object. Request message for running asset + discovery for an organization. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=organizations/*}/assets:runDiscovery', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_run_asset_discovery(request, metadata) + pb_request = securitycenter_service.RunAssetDiscoveryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_run_asset_discovery(resp) + return resp + + class _SetFindingState(SecurityCenterRestStub): + def __hash__(self): + return hash("SetFindingState") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SetFindingStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the set finding state method over HTTP. + + Args: + request (~.securitycenter_service.SetFindingStateRequest): + The request object. Request message for updating a + finding's state. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{name=organizations/*/sources/*/findings/*}:setState', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_finding_state(request, metadata) + pb_request = securitycenter_service.SetFindingStateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_set_finding_state(resp) + return resp + + class _SetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{resource=organizations/*/sources/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _TestIamPermissions(SecurityCenterRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{resource=organizations/*/sources/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UpdateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the update finding method over HTTP. + + Args: + request (~.securitycenter_service.UpdateFindingRequest): + The request object. Request message for updating or + creating a finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta1/{finding.name=organizations/*/sources/*/findings/*}', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_update_finding(request, metadata) + pb_request = securitycenter_service.UpdateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_finding(resp) + return resp + + class _UpdateOrganizationSettings(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateOrganizationSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateOrganizationSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Call the update organization + settings method over HTTP. + + Args: + request (~.securitycenter_service.UpdateOrganizationSettingsRequest): + The request object. Request message for updating an + organization's 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: + ~.gcs_organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta1/{organization_settings.name=organizations/*/organizationSettings}', + 'body': 'organization_settings', + }, + ] + request, metadata = self._interceptor.pre_update_organization_settings(request, metadata) + pb_request = securitycenter_service.UpdateOrganizationSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_organization_settings.OrganizationSettings() + pb_resp = gcs_organization_settings.OrganizationSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_organization_settings(resp) + return resp + + class _UpdateSecurityMarks(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSecurityMarks") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSecurityMarksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_security_marks.SecurityMarks: + r"""Call the update security marks method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSecurityMarksRequest): + The request object. Request message for updating a + SecurityMarks resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1beta1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, + ] + request, metadata = self._interceptor.pre_update_security_marks(request, metadata) + pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_security_marks.SecurityMarks() + pb_resp = gcs_security_marks.SecurityMarks.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_security_marks(resp) + return resp + + class _UpdateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the update source method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSourceRequest): + The request object. Request message for updating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta1/{source.name=organizations/*/sources/*}', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_update_source(request, metadata) + pb_request = securitycenter_service.UpdateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_source(resp) + return resp + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.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_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + 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._RunAssetDiscovery(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SecurityCenterRestTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py new file mode 100644 index 000000000000..d3d5b965f804 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .asset import ( + Asset, +) +from .finding import ( + Finding, +) +from .organization_settings import ( + OrganizationSettings, +) +from .run_asset_discovery_response import ( + RunAssetDiscoveryResponse, +) +from .security_marks import ( + SecurityMarks, +) +from .securitycenter_service import ( + CreateFindingRequest, + CreateSourceRequest, + GetOrganizationSettingsRequest, + GetSourceRequest, + GroupAssetsRequest, + GroupAssetsResponse, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListAssetsRequest, + ListAssetsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListSourcesRequest, + ListSourcesResponse, + RunAssetDiscoveryRequest, + SetFindingStateRequest, + UpdateFindingRequest, + UpdateOrganizationSettingsRequest, + UpdateSecurityMarksRequest, + UpdateSourceRequest, +) +from .source import ( + Source, +) + +__all__ = ( + 'Asset', + 'Finding', + 'OrganizationSettings', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateSourceRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py new file mode 100644 index 000000000000..16ad84206b64 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'Asset', + }, +) + + +class Asset(proto.Message): + r"""Security Command Center representation of a Google Cloud + resource. + + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All + modifications to an Asset are only within the context of + Security Command Center and don't affect the referenced Google + Cloud resource. + + Attributes: + name (str): + The relative resource name of this asset. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/assets/{asset_id}". + security_center_properties (google.cloud.securitycenter_v1beta1.types.Asset.SecurityCenterProperties): + Security Command Center managed properties. + These properties are managed by Security Command + Center and cannot be modified by the user. + resource_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Resource managed properties. These properties + are managed and defined by the Google Cloud + resource and cannot be modified by the user. + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): + User specified security marks. These marks + are entirely managed by the user and come from + the SecurityMarks resource that belongs to the + asset. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was last updated, + added, or deleted in Security Command Center. + """ + + class SecurityCenterProperties(proto.Message): + r"""Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified by + the user. + + Attributes: + resource_name (str): + Immutable. The full resource name of the Google Cloud + resource this asset represents. This field is immutable + after create time. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_type (str): + The type of the Google Cloud resource. + Examples include: APPLICATION, PROJECT, and + ORGANIZATION. This is a case insensitive field + defined by Security Command Center and/or the + producer of the resource and is immutable after + create time. + resource_parent (str): + The full resource name of the immediate parent of the + resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_project (str): + The full resource name of the project the resource belongs + to. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_owners (MutableSequence[str]): + Owners of the Google Cloud resource. + """ + + resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + resource_parent: str = proto.Field( + proto.STRING, + number=3, + ) + resource_project: str = proto.Field( + proto.STRING, + number=4, + ) + resource_owners: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + security_center_properties: SecurityCenterProperties = proto.Field( + proto.MESSAGE, + number=2, + message=SecurityCenterProperties, + ) + resource_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py new file mode 100644 index 000000000000..15d2a4ec1ee5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.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.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + + A finding is a record of assessment data (security, risk, health + or privacy) ingested into Security Command Center for + presentation, notification, analysis, policy testing, and + enforcement. For example, an XSS vulnerability in an App Engine + application is a finding. + + Attributes: + name (str): + The relative resource name of this finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". + parent (str): + Immutable. The relative resource name of the source the + finding belongs to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. For example: + "organizations/{organization_id}/sources/{source_id}". + resource_name (str): + For findings on Google Cloud resources, the full resource + name of the Google Cloud resource this finding is for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + This field is immutable after creation time. + state (google.cloud.securitycenter_v1beta1.types.Finding.State): + The state of the finding. + category (str): + The additional taxonomy group within findings from a given + source. This field is immutable after creation time. + Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the event took place, or + when an update to the finding occurred. For + example, if the finding represents an open + firewall it would capture the time the detector + believes the firewall became open. The accuracy + is determined by the detector. If the finding + were to be resolved afterward, this time would + reflect when the finding was resolved. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the finding was created in + Security Command Center. + """ + class State(proto.Enum): + r"""The state of the finding. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + ACTIVE (1): + The finding requires attention and has not + been addressed yet. + INACTIVE (2): + The finding has been fixed, triaged as a + non-issue or otherwise addressed and is no + longer active. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + resource_name: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + category: str = proto.Field( + proto.STRING, + number=5, + ) + external_uri: str = proto.Field( + proto.STRING, + number=6, + ) + source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py new file mode 100644 index 000000000000..e94e037fd61a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'OrganizationSettings', + }, +) + + +class OrganizationSettings(proto.Message): + r"""User specified settings that are attached to the Security + Command Center organization. + + Attributes: + name (str): + The relative resource name of the settings. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/organizationSettings". + enable_asset_discovery (bool): + A flag that indicates if Asset Discovery should be enabled. + If the flag is set to ``true``, then discovery of assets + will occur. If it is set to \`false, all historical assets + will remain, but discovery of future assets will not occur. + asset_discovery_config (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig): + The configuration used for Asset Discovery + runs. + """ + + class AssetDiscoveryConfig(proto.Message): + r"""The configuration used for Asset Discovery runs. + + Attributes: + project_ids (MutableSequence[str]): + The project ids to use for filtering asset + discovery. + inclusion_mode (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + The mode to use for filtering asset + discovery. + """ + class InclusionMode(proto.Enum): + r"""The mode of inclusion when running Asset Discovery. Asset discovery + can be limited by explicitly identifying projects to be included or + excluded. If INCLUDE_ONLY is set, then only those projects within + the organization and their children are discovered during asset + discovery. If EXCLUDE is set, then projects that don't match those + projects are discovered during asset discovery. If neither are set, + then all projects within the organization are discovered during + asset discovery. + + Values: + INCLUSION_MODE_UNSPECIFIED (0): + Unspecified. Setting the mode with this value + will disable inclusion/exclusion filtering for + Asset Discovery. + INCLUDE_ONLY (1): + Asset Discovery will capture only the + resources within the projects specified. All + other resources will be ignored. + EXCLUDE (2): + Asset Discovery will ignore all resources + under the projects specified. All other + resources will be retrieved. + """ + INCLUSION_MODE_UNSPECIFIED = 0 + INCLUDE_ONLY = 1 + EXCLUDE = 2 + + project_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + inclusion_mode: 'OrganizationSettings.AssetDiscoveryConfig.InclusionMode' = proto.Field( + proto.ENUM, + number=2, + enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + enable_asset_discovery: bool = proto.Field( + proto.BOOL, + number=2, + ) + asset_discovery_config: AssetDiscoveryConfig = proto.Field( + proto.MESSAGE, + number=3, + message=AssetDiscoveryConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py new file mode 100644 index 000000000000..c5bccb3dd7f2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.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 + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'RunAssetDiscoveryResponse', + }, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + + Attributes: + state (google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (google.protobuf.duration_pb2.Duration): + The duration between asset discovery run + start and end + """ + class State(proto.Enum): + r"""The state of an asset discovery run. + + Values: + STATE_UNSPECIFIED (0): + Asset discovery run state was unspecified. + COMPLETED (1): + Asset discovery run completed successfully. + SUPERSEDED (2): + Asset discovery run was cancelled with tasks + still pending, as another run for the same + organization was started with a higher priority. + TERMINATED (3): + Asset discovery run was killed and + terminated. + """ + STATE_UNSPECIFIED = 0 + COMPLETED = 1 + SUPERSEDED = 2 + TERMINATED = 3 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py new file mode 100644 index 000000000000..f2b762a6f2ec --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'SecurityMarks', + }, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". + marks (MutableMapping[str, str]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + marks: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py new file mode 100644 index 000000000000..dd7fedfd6122 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py @@ -0,0 +1,1053 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1beta1.types import asset as gcs_asset +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'CreateFindingRequest', + 'CreateSourceRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'SetFindingStateRequest', + 'RunAssetDiscoveryRequest', + 'UpdateFindingRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSourceRequest', + 'UpdateSecurityMarksRequest', + }, +) + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + + Attributes: + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + alphanumeric and less than or equal to 32 + characters and greater than 0 characters in + length. + finding (google.cloud.securitycenter_v1beta1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + finding_id: str = proto.Field( + proto.STRING, + number=2, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_finding.Finding, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + source (google.cloud.securitycenter_v1beta1.types.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_source.Source, + ) + + +class GetOrganizationSettingsRequest(proto.Message): + r"""Request message for getting organization settings. + + Attributes: + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is "organizations/[organization_id]/source/[source_id]". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GroupAssetsRequest(proto.Message): + r"""Request message for grouping by assets. + + Attributes: + parent (str): + Required. Name of the organization to groupBy. Its format is + "organizations/[organization_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``resource_properties.size = 100`` is a valid + filter string. + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is + not set: + + - security_center_properties.resource_project + - security_center_properties.resource_type + - security_center_properties.resource_parent + + The following fields are supported when compare_duration is + set: + + - security_center_properties.resource_type + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the Asset's "state" property + is updated to indicate whether the asset was added, removed, + or remained present during the compare_duration period of + time that precedes the read_time. This is the time between + (read_time - compare_duration) and read_time. + + The state value is derived based on the presence of the + asset at the two points in time. Intermediate state changes + between the two times don't affect the result. For example, + the results aren't affected if the asset is removed and + re-created again. + + Possible "state" values when compare_duration is specified: + + - "ADDED": indicates that the asset was not present before + compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at + reference_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and reference_time. + + This field is ignored if ``state`` is not a field in + ``group_by``. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupAssetsResponse``; + indicates that this is a continuation of a prior + ``GroupAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupAssetsResponse(proto.Message): + r"""Response message for grouping by assets. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + + Attributes: + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". To + groupBy across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``source_properties.size = 100`` is a valid + filter string. + group_by (str): + Required. Expression that defines what assets fields to use + for grouping (including ``state``). The string value should + follow SQL syntax: comma separated list of fields. For + example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + page_size: int = proto.Field( + proto.INT32, + number=6, + ) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=struct_pb2.Value, + ) + count: int = proto.Field( + proto.INT64, + number=2, + ) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be "organizations/[organization_id]". + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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=7, + ) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v1beta1.types.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAssetsRequest(proto.Message): + r"""Request message for listing assets. + + Attributes: + parent (str): + Required. Name of the organization assets should belong to. + Its format is "organizations/[organization_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``resource_properties.size = 100`` is a valid + filter string. + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,resource_properties.a_property". + Redundant space characters in the syntax are insignificant. + "name desc,resource_properties.a_property" and " name desc , + resource_properties.a_property " are equivalent. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListAssetResult's "state" + attribute is updated to indicate whether the asset was + added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state value is derived based on the presence of the + asset at the two points in time. Intermediate state changes + between the two times don't affect the result. For example, + the results aren't affected if the asset is removed and + re-created again. + + Possible "state" values when compare_duration is specified: + + - "ADDED": indicates that the asset was not present before + compare_duration, but present at read_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at read_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and read_time. + + If compare_duration is not specified, then the only possible + state is "UNUSED", which indicates that the asset is present + at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. A field mask to specify the + ListAssetsResult fields to be listed in the + response. An empty field mask will list all + fields. + page_token (str): + The value returned by the last ``ListAssetsResponse``; + indicates that this is a continuation of a prior + ``ListAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=9, + ) + + +class ListAssetsResponse(proto.Message): + r"""Response message for listing assets. + + Attributes: + list_assets_results (MutableSequence[google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of assets matching the + query. + """ + + class ListAssetsResult(proto.Message): + r"""Result containing the Asset and its State. + + Attributes: + asset (google.cloud.securitycenter_v1beta1.types.Asset): + Asset matching the search request. + state (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult.State): + State of the asset. + """ + class State(proto.Enum): + r"""State of the asset. + + When querying across two points in time this describes the change + between the two points: ADDED, REMOVED, or ACTIVE. If there was no + compare_duration supplied in the request the state should be: UNUSED + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + UNUSED (1): + Request did not specify use of this field in + the result. + ADDED (2): + Asset was added between the points in time. + REMOVED (3): + Asset was removed between the points in time. + ACTIVE (4): + Asset was active at both point(s) in time. + """ + STATE_UNSPECIFIED = 0 + UNUSED = 1 + ADDED = 2 + REMOVED = 3 + ACTIVE = 4 + + asset: gcs_asset.Asset = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_asset.Asset, + ) + state: 'ListAssetsResponse.ListAssetsResult.State' = proto.Field( + proto.ENUM, + number=2, + enum='ListAssetsResponse.ListAssetsResult.State', + ) + + @property + def raw_page(self): + return self + + list_assets_results: MutableSequence[ListAssetsResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListAssetsResult, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + + Attributes: + parent (str): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id]". To + list across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``source_properties.size = 100`` is a valid + filter string. + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,source_properties.a_property". Redundant + space characters in the syntax are insignificant. "name + desc,source_properties.a_property" and " name desc , + source_properties.a_property " are equivalent. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. A field mask to specify the Finding + fields to be listed in the response. An empty + field mask will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=6, + ) + page_size: int = proto.Field( + proto.INT32, + number=7, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + + Attributes: + findings (MutableSequence[google.cloud.securitycenter_v1beta1.types.Finding]): + Findings matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + @property + def raw_page(self): + return self + + findings: MutableSequence[gcs_finding.Finding] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + + Attributes: + name (str): + Required. The relative resource name of the finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + state (google.cloud.securitycenter_v1beta1.types.Finding.State): + Required. The desired State of the finding. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the updated state + takes effect. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: gcs_finding.Finding.State = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.State, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class RunAssetDiscoveryRequest(proto.Message): + r"""Request message for running asset discovery for an + organization. + + Attributes: + parent (str): + Required. Name of the organization to run asset discovery + for. Its format is "organizations/[organization_id]". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + + Attributes: + finding (google.cloud.securitycenter_v1beta1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + finding resource. This field should not be + specified when creating a finding. + """ + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + + Attributes: + organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + settings resource. + """ + + organization_settings: gcs_organization_settings.OrganizationSettings = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_organization_settings.OrganizationSettings, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (google.cloud.securitycenter_v1beta1.types.Source): + Required. The source resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the source + resource. + """ + + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): + Required. The security marks resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + security marks resource. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the updated SecurityMarks + take effect. + """ + + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_marks.SecurityMarks, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + start_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-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py new file mode 100644 index 000000000000..761384a9c28f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v1beta1', + manifest={ + 'Source', + }, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, etc. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and + outdated/insecure libraries.". + """ + + 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, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/noxfile.py new file mode 100644 index 000000000000..09f9f6872402 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-securitycenter' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +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"): + 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/securitycenter_v1beta1/', + '--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"): + 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", + "grpcio", + "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/securitycenter_v1beta1/', + '--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( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): + # Ignore release of mypy 1.11.0 which may have a regression + 'mypy!=1.11.0', + '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-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_async.py new file mode 100644 index 000000000000..e2ccd162023c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_create_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_sync.py new file mode 100644 index 000000000000..8a6cd38a65ea --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_create_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_async.py new file mode 100644 index 000000000000..b705b58ee221 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_CreateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_create_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_sync.py new file mode 100644 index 000000000000..ed1f60c4c944 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_CreateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_create_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py new file mode 100644 index 000000000000..8f5186953423 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py new file mode 100644 index 000000000000..74daec484fa2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py new file mode 100644 index 000000000000..e21dbe268313 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_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 GetOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py new file mode 100644 index 000000000000..40c62b6f158e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_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 GetOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_async.py new file mode 100644 index 000000000000..92eeeb159eb1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GetSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_get_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_sync.py new file mode 100644 index 000000000000..4432d6697cb8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GetSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_get_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_async.py new file mode 100644 index 000000000000..7bc11cd58a3d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_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 GroupAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_group_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_sync.py new file mode 100644 index 000000000000..b5a0c8f1322b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_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 GroupAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_group_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_async.py new file mode 100644 index 000000000000..367437acd112 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_group_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_sync.py new file mode 100644 index 000000000000..2b3cdac52e46 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_group_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_async.py new file mode 100644 index 000000000000..80d46cf5ce6f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_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 ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_ListAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_list_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_sync.py new file mode 100644 index 000000000000..6f45a7b22700 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_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 ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_ListAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_list_assets(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_async.py new file mode 100644 index 000000000000..3ee6027b07d6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_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 securitycenter_v1beta1 + + +async def sample_list_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_sync.py new file mode 100644 index 000000000000..6a9a7c526574 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_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 securitycenter_v1beta1 + + +def sample_list_findings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_async.py new file mode 100644 index 000000000000..ced7ea701eeb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_ListSources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_list_sources(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_sync.py new file mode 100644 index 000000000000..3eff727dc701 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_ListSources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_list_sources(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py new file mode 100644 index 000000000000..7ec0a72a67a5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py new file mode 100644 index 000000000000..7efbac655d2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_async.py new file mode 100644 index 000000000000..f9245b6f398e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_set_finding_state(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py new file mode 100644 index 000000000000..a2b160db84a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_set_finding_state(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py new file mode 100644 index 000000000000..9863d798d645 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py new file mode 100644 index 000000000000..ddac6e4fadb8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py new file mode 100644 index 000000000000..f1ecc97a8e8c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py new file mode 100644 index 000000000000..87f3b0ee6c7b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_async.py new file mode 100644 index 000000000000..8f8e6f58f99f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_update_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_sync.py new file mode 100644 index 000000000000..9c214219e880 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_update_finding(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py new file mode 100644 index 000000000000..8174ebf4f93b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = await client.update_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py new file mode 100644 index 000000000000..b587f61c0ce3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = client.update_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_async.py new file mode 100644 index 000000000000..230075087471 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_update_security_marks(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py new file mode 100644 index 000000000000..f041a1b1fa1a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_update_security_marks(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_async.py new file mode 100644 index 000000000000..3afe218c0c83 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +async def sample_update_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_sync.py new file mode 100644 index 000000000000..0ff7573f017d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1beta1 + + +def sample_update_source(): + # Create a client + client = securitycenter_v1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1beta1.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json new file mode 100644 index 000000000000..a4c1295eaf99 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json @@ -0,0 +1,2945 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.securitycenter.v1beta1", + "version": "v1beta1" + } + ], + "language": "PYTHON", + "name": "google-cloud-securitycenter", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1beta1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v1beta1_generated_security_center_create_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1beta1_generated_security_center_create_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1beta1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v1beta1_generated_security_center_create_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1beta1_generated_security_center_create_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1beta1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v1beta1_generated_security_center_create_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_create_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1beta1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v1beta1_generated_security_center_create_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_create_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.get_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest" + }, + { + "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.securitycenter_v1beta1.types.OrganizationSettings", + "shortName": "get_organization_settings" + }, + "description": "Sample for GetOrganizationSettings", + "file": "securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.get_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest" + }, + { + "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.securitycenter_v1beta1.types.OrganizationSettings", + "shortName": "get_organization_settings" + }, + "description": "Sample for GetOrganizationSettings", + "file": "securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GetSourceRequest" + }, + { + "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.securitycenter_v1beta1.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v1beta1_generated_security_center_get_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_get_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GetSourceRequest" + }, + { + "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.securitycenter_v1beta1.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v1beta1_generated_security_center_get_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_get_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.group_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsAsyncPager", + "shortName": "group_assets" + }, + "description": "Sample for GroupAssets", + "file": "securitycenter_v1beta1_generated_security_center_group_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1beta1_generated_security_center_group_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.group_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsPager", + "shortName": "group_assets" + }, + "description": "Sample for GroupAssets", + "file": "securitycenter_v1beta1_generated_security_center_group_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1beta1_generated_security_center_group_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsAsyncPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v1beta1_generated_security_center_group_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1beta1_generated_security_center_group_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v1beta1_generated_security_center_group_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1beta1_generated_security_center_group_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.list_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.ListAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsAsyncPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "securitycenter_v1beta1_generated_security_center_list_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1beta1_generated_security_center_list_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.list_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.ListAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "securitycenter_v1beta1_generated_security_center_list_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1beta1_generated_security_center_list_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.ListFindingsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsAsyncPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v1beta1_generated_security_center_list_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1beta1_generated_security_center_list_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.ListFindingsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v1beta1_generated_security_center_list_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1beta1_generated_security_center_list_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.ListSourcesRequest" + }, + { + "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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesAsyncPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v1beta1_generated_security_center_list_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1beta1_generated_security_center_list_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.ListSourcesRequest" + }, + { + "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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v1beta1_generated_security_center_list_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1beta1_generated_security_center_list_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.run_asset_discovery", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.RunAssetDiscovery", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "RunAssetDiscovery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "run_asset_discovery" + }, + "description": "Sample for RunAssetDiscovery", + "file": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.run_asset_discovery", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.RunAssetDiscovery", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "RunAssetDiscovery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "run_asset_discovery" + }, + "description": "Sample for RunAssetDiscovery", + "file": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v1beta1.types.Finding.State" + }, + { + "name": "start_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v1beta1_generated_security_center_set_finding_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1beta1_generated_security_center_set_finding_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v1beta1.types.Finding.State" + }, + { + "name": "start_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1beta1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v1beta1_generated_security_center_update_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1beta1_generated_security_center_update_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1beta1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v1beta1_generated_security_center_update_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1beta1_generated_security_center_update_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest" + }, + { + "name": "organization_settings", + "type": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings", + "shortName": "update_organization_settings" + }, + "description": "Sample for UpdateOrganizationSettings", + "file": "securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest" + }, + { + "name": "organization_settings", + "type": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings", + "shortName": "update_organization_settings" + }, + "description": "Sample for UpdateOrganizationSettings", + "file": "securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v1beta1.types.SecurityMarks" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v1beta1_generated_security_center_update_security_marks_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1beta1_generated_security_center_update_security_marks_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v1beta1.types.SecurityMarks" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1beta1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v1beta1_generated_security_center_update_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1beta1_generated_security_center_update_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1beta1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1beta1.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v1beta1_generated_security_center_update_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1beta1_generated_security_center_update_source_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py new file mode 100644 index 000000000000..e4b81a3218c2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py @@ -0,0 +1,193 @@ +#! /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 securitycenterCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_source': ('parent', 'source', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_organization_settings': ('name', ), + 'get_source': ('name', ), + 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), + 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'page_token', 'page_size', ), + 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'field_mask', 'page_token', 'page_size', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'run_asset_discovery': ('parent', ), + 'set_finding_state': ('name', 'state', 'start_time', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_organization_settings': ('organization_settings', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), + 'update_source': ('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=securitycenterCallTransformer(), +): + """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 securitycenter 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-securitycenter/v1beta1/setup.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/setup.py new file mode 100644 index 000000000000..c4538ec101f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/setup.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. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-securitycenter' + + +description = "Google Cloud Securitycenter API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/securitycenter/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", + "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", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__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-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py new file mode 100644 index 000000000000..1ba9f20c0bed --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py @@ -0,0 +1,14372 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +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 + +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.securitycenter_v1beta1.services.security_center import SecurityCenterAsyncClient +from google.cloud.securitycenter_v1beta1.services.security_center import SecurityCenterClient +from google.cloud.securitycenter_v1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1beta1.services.security_center import transports +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +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 duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None + assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SecurityCenterClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SecurityCenterGrpcTransport, "grpc"), + (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + 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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + available_transports = [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterRestTransport, + ] + assert transport in available_transports + + transport = SecurityCenterClient.get_transport_class("grpc") + assert transport == transports.SecurityCenterGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, 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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), +]) +def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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_security_center_client_client_options_from_dict(): + with mock.patch('google.cloud.securitycenter_v1beta1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_create_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object + + request = {} + await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_create_source_async_from_dict(): + await test_create_source_async(request_type=dict) + + +def test_create_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.create_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.create_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + + +def test_create_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + response = client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +def test_create_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.create_finding] = mock_rpc + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object + + request = {} + await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +@pytest.mark.asyncio +async def test_create_finding_async_from_dict(): + await test_create_finding_async(request_type=dict) + + +def test_create_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + arg = args[0].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + + +def test_create_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + arg = args[0].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.GetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest( + resource='resource_value', + ) + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object + + request = {} + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetOrganizationSettingsRequest, + dict, +]) +def test_get_organization_settings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_get_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetOrganizationSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_organization_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest( + name='name_value', + ) + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_organization_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_organization_settings] = mock_rpc + request = {} + client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_organization_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_organization_settings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + +@pytest.mark.asyncio +async def test_get_organization_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_organization_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_organization_settings] = mock_object + + request = {} + await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_organization_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_get_organization_settings_async_from_dict(): + await test_get_organization_settings_async(request_type=dict) + + +def test_get_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = organization_settings.OrganizationSettings() + client.get_organization_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_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + await client.get_organization_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_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_organization_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_organization_settings_flattened_error(): + client = SecurityCenterClient( + credentials=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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_organization_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_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest( + name='name_value', + ) + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + +@pytest.mark.asyncio +async def test_get_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object + + request = {} + await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_source_async_from_dict(): + await test_get_source_async(request_type=dict) + + +def test_get_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = source.Source() + client.get_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + await client.get_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_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_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupAssetsRequest, + dict, +]) +def test_group_assets(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + ) + response = client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_group_assets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + +def test_group_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupAssetsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc + request = {} + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_group_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + +@pytest.mark.asyncio +async def test_group_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_assets] = mock_object + + request = {} + await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_group_assets_async_from_dict(): + await test_group_assets_async(request_type=dict) + + +def test_group_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = securitycenter_service.GroupAssetsResponse() + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_group_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) + await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_group_assets_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_assets(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, securitycenter_service.GroupResult) + for i in results) +def test_group_assets_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_assets(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_group_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_assets(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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_assets(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", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + ) + response = client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_group_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + +@pytest.mark.asyncio +async def test_group_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_findings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object + + request = {} + await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_findings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_group_findings_async_from_dict(): + await test_group_findings_async(request_type=dict) + + +def test_group_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = securitycenter_service.GroupFindingsResponse() + client.group_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_group_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + await client.group_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_group_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that the 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + + +def test_group_findings_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + +@pytest.mark.asyncio +async def test_group_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_group_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_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, securitycenter_service.GroupResult) + for i in results) +def test_group_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_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_group_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_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", [ + securitycenter_service.ListAssetsRequest, + dict, +]) +def test_list_assets(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_assets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + +def test_list_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListAssetsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_value', + page_token='page_token_value', + ) + +def test_list_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + +@pytest.mark.asyncio +async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object + + request = {} + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + + +def test_list_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = securitycenter_service.ListAssetsResponse() + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_assets_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) +def test_list_assets_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(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_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + 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_assets(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", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +def test_list_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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] == securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + +@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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object + + request = {} + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +@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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.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 = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.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 = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.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 = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.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", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListSourcesRequest( + 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_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + +@pytest.mark.asyncio +async def test_list_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_sources in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object + + request = {} + await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_sources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sources_async_from_dict(): + await test_list_sources_async(request_type=dict) + + +def test_list_sources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = securitycenter_service.ListSourcesResponse() + client.list_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_sources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + await client.list_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_sources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_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_sources_flattened_error(): + client = SecurityCenterClient( + credentials=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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_sources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_sources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_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, source.Source) + for i in results) +def test_list_sources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = list(client.list_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_sources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_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, source.Source) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_sources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + 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_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", [ + securitycenter_service.RunAssetDiscoveryRequest, + dict, +]) +def test_run_asset_discovery(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.RunAssetDiscoveryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_asset_discovery_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + +def test_run_asset_discovery_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.RunAssetDiscoveryRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_asset_discovery(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest( + parent='parent_value', + ) + +def test_run_asset_discovery_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_asset_discovery in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc + request = {} + client.run_asset_discovery(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.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_run_asset_discovery_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + +@pytest.mark.asyncio +async def test_run_asset_discovery_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.run_asset_discovery in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.run_asset_discovery] = mock_object + + request = {} + await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.RunAssetDiscoveryRequest() + 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_run_asset_discovery_async_from_dict(): + await test_run_asset_discovery_async(request_type=dict) + + +def test_run_asset_discovery_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_asset_discovery_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_run_asset_discovery_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery( + 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_run_asset_discovery_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_run_asset_discovery_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery( + 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_run_asset_discovery_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + response = client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +def test_set_finding_state_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + +@pytest.mark.asyncio +async def test_set_finding_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object + + request = {} + await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_finding_state(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +@pytest.mark.asyncio +async def test_set_finding_state_async_from_dict(): + await test_set_finding_state_async(request_type=dict) + + +def test_set_finding_state_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = finding.Finding() + client.set_finding_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_set_finding_state_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_finding_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_set_finding_state_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.SetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest( + resource='resource_value', + ) + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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( + version=774, + etag=b'etag_blob', + )) + response = await client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object + + request = {} + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = SecurityCenterClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.TestIamPermissionsRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( + resource='resource_value', + ) + +def test_test_iam_permissions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object + + request = {} + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + response = client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +def test_update_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateFindingRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.update_finding] = mock_rpc + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object + + request = {} + await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +@pytest.mark.asyncio +async def test_update_finding_async_from_dict(): + await test_update_finding_async(request_type=dict) + + +def test_update_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +def test_update_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_finding( + finding=gcs_finding.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].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + + +def test_update_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_finding( + finding=gcs_finding.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].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateOrganizationSettingsRequest, + dict, +]) +def test_update_organization_settings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_update_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateOrganizationSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_organization_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest( + ) + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_organization_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_organization_settings] = mock_rpc + request = {} + client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_organization_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_organization_settings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + +@pytest.mark.asyncio +async def test_update_organization_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_organization_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_organization_settings] = mock_object + + request = {} + await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_organization_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_update_organization_settings_async_from_dict(): + await test_update_organization_settings_async(request_type=dict) + + +def test_update_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = gcs_organization_settings.OrganizationSettings() + client.update_organization_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', + 'organization_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + await client.update_organization_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', + 'organization_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].organization_settings + mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') + assert arg == mock_val + + +def test_update_organization_settings_flattened_error(): + client = SecurityCenterClient( + credentials=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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].organization_settings + mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_update_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSourceRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object + + request = {} + await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_update_source_async_from_dict(): + await test_update_source_async(request_type=dict) + + +def test_update_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +def test_update_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_source( + source=gcs_source.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].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + + +def test_update_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_source( + source=gcs_source.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].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks( + name='name_value', + ) + response = client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + + +def test_update_security_marks_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + +def test_update_security_marks_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSecurityMarksRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( + ) + +def test_update_security_marks_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish that a new wrapper 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_security_marks_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + )) + response = await client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + +@pytest.mark.asyncio +async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_marks in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object + + request = {} + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_security_marks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + )) + response = await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_security_marks_async_from_dict(): + await test_update_security_marks_async(request_type=dict) + + +def test_update_security_marks_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = gcs_security_marks.SecurityMarks() + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_marks_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +def test_update_security_marks_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].security_marks + mock_val = gcs_security_marks.SecurityMarks(name='name_value') + assert arg == mock_val + + +def test_update_security_marks_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].security_marks + mock_val = gcs_security_marks.SecurityMarks(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': '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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.CreateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_source(request) + + +def test_create_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_create_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +def test_create_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request_init["finding"] = {'name': 'name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.create_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.create_finding] = mock_rpc + + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["finding_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 "findingId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "findingId" in jsonified_request + assert jsonified_request["findingId"] == request_init["finding_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["findingId"] = 'finding_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request + assert jsonified_request["findingId"] == 'finding_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.create_finding(request) + + expected_params = [ + ( + "findingId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.CreateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_finding(request) + + +def test_create_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(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 = gcs_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.create_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/v1beta1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) + + +def test_create_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_create_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.get_iam_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/v1beta1/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetOrganizationSettingsRequest, + dict, +]) +def test_get_organization_settings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/organizationSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_organization_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_organization_settings] = mock_rpc + + request = {} + client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.GetOrganizationSettingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_organization_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_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_organization_settings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_organization_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_organization_settings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_organization_settings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_organization_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetOrganizationSettingsRequest.pb(securitycenter_service.GetOrganizationSettingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = organization_settings.OrganizationSettings.to_json(organization_settings.OrganizationSettings()) + + request = securitycenter_service.GetOrganizationSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = organization_settings.OrganizationSettings() + + client.get_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/organizationSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_organization_settings(request) + + +def test_get_organization_settings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/organizationSettings'} + + # get truthy value for each flattened field + mock_args = dict( + 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 = organization_settings.OrganizationSettings.pb(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_organization_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/v1beta1/{name=organizations/*/organizationSettings}" % client.transport._host, args[1]) + + +def test_get_organization_settings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +def test_get_organization_settings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/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 = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = source.Source.to_json(source.Source()) + + request = securitycenter_service.GetSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = source.Source() + + client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_source(request) + + +def test_get_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v1beta1/{name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_get_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +def test_get_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupAssetsRequest, + dict, +]) +def test_group_assets_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_group_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc + + request = {} + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_group_assets_rest_required_fields(request_type=securitycenter_service.GroupAssetsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_assets_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_assets_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_assets") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupAssetsRequest.pb(securitycenter_service.GroupAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupAssetsResponse.to_json(securitycenter_service.GroupAssetsResponse()) + + request = securitycenter_service.GroupAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupAssetsResponse() + + client.group_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_assets(request) + + +def test_group_assets_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupAssetsResponse.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': 'organizations/sample1'} + + pager = client.group_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_findings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) + + request = securitycenter_service.GroupFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupFindingsResponse() + + client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_findings(request) + + +def test_group_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + group_by='group_by_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v1beta1/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) + + +def test_group_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} + + pager = client.group_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_findings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListAssetsRequest, + dict, +]) +def test_list_assets_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListAssetsResponse.pb(return_value) + 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_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_list_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish 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_assets_rest_required_fields(request_type=securitycenter_service.ListAssetsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_assets._get_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_assets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) + jsonified_request.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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListAssetsResponse.pb(return_value) + 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_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_assets_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_assets_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_assets") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListAssetsRequest.pb(securitycenter_service.ListAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListAssetsResponse.to_json(securitycenter_service.ListAssetsResponse()) + + request = securitycenter_service.ListAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListAssetsResponse() + + client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_assets(request) + + +def test_list_assets_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListAssetsResponse.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': 'organizations/sample1'} + + pager = client.list_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) + + pages = list(client.list_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.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' + assert response.total_size == 1086 + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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=securitycenter_service.ListFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) + jsonified_request.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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.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 = securitycenter_service.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 = [ + ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) + + request = securitycenter_service.ListFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListFindingsResponse() + + client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_findings(request) + + +def test_list_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} + + 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 + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_sources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_sources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) + + request = securitycenter_service.ListSourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListSourcesResponse() + + client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_sources(request) + + +def test_list_sources_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_list_sources_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} + + pager = client.list_sources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, source.Source) + for i in results) + + pages = list(client.list_sources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.RunAssetDiscoveryRequest, + dict, +]) +def test_run_asset_discovery_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') + + # 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 + response = client.run_asset_discovery(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_run_asset_discovery_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_asset_discovery in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc + + request = {} + client.run_asset_discovery(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.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_run_asset_discovery_rest_required_fields(request_type=securitycenter_service.RunAssetDiscoveryRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_asset_discovery._get_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()).run_asset_discovery._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 = SecurityCenterClient( + 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.run_asset_discovery(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_run_asset_discovery_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.run_asset_discovery._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_asset_discovery_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_run_asset_discovery") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_run_asset_discovery") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.RunAssetDiscoveryRequest.pb(securitycenter_service.RunAssetDiscoveryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = securitycenter_service.RunAssetDiscoveryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.run_asset_discovery(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_asset_discovery_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.run_asset_discovery(request) + + +def test_run_asset_discovery_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.run_asset_discovery(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=organizations/*}/assets:runDiscovery" % client.transport._host, args[1]) + + +def test_run_asset_discovery_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +def test_run_asset_discovery_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + + # 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 + response = client.set_finding_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( + 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': "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 = 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.set_finding_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_finding_state_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_finding_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "state", "startTime", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_finding_state_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetFindingStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_finding_state(request) + + +def test_set_finding_state_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + mock_args.update(sample_request) + + # 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.set_finding_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/v1beta1/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) + + +def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +def test_set_finding_state_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.set_iam_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/v1beta1/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # 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 + response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_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.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.update_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.update_finding] = mock_rpc + + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_finding._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_finding._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.update_finding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.UpdateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_finding(request) + + +def test_update_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + finding=gcs_finding.Finding(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 = gcs_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.update_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/v1beta1/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) + + +def test_update_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_update_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateOrganizationSettingsRequest, + dict, +]) +def test_update_organization_settings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + request_init["organization_settings"] = {'name': 'organizations/sample1/organizationSettings', 'enable_asset_discovery': True, 'asset_discovery_config': {'project_ids': ['project_ids_value1', 'project_ids_value2'], 'inclusion_mode': 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 = securitycenter_service.UpdateOrganizationSettingsRequest.meta.fields["organization_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["organization_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["organization_settings"][field])): + del request_init["organization_settings"][field][i][subfield] + else: + del request_init["organization_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 = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_organization_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_organization_settings] = mock_rpc + + request = {} + client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_organization_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_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_organization_settings.OrganizationSettings() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_organization_settings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_organization_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("organizationSettings", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_organization_settings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_organization_settings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_organization_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateOrganizationSettingsRequest.pb(securitycenter_service.UpdateOrganizationSettingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_organization_settings.OrganizationSettings.to_json(gcs_organization_settings.OrganizationSettings()) + + request = securitycenter_service.UpdateOrganizationSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_organization_settings.OrganizationSettings() + + client.update_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_organization_settings(request) + + +def test_update_organization_settings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_organization_settings.OrganizationSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + organization_settings=gcs_organization_settings.OrganizationSettings(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 = gcs_organization_settings.OrganizationSettings.pb(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_organization_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/v1beta1/{organization_settings.name=organizations/*/organizationSettings}" % client.transport._host, args[1]) + + +def test_update_organization_settings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +def test_update_organization_settings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': '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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.UpdateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_source(request) + + +def test_update_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1beta1/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_update_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + + +def test_update_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + request_init["security_marks"] = {'name': 'organizations/sample1/assets/sample2/securityMarks', 'marks': {}} + # The version of a generated dependency at test runtime may differ from the version used 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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] + + 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["security_marks"].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["security_marks"][field])): + del request_init["security_marks"][field][i][subfield] + else: + del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + +def test_update_security_marks_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_security_marks._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_security_marks._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("start_time", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_security_marks_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_security_marks._get_unset_required_fields({}) + assert set(unset_fields) == (set(("startTime", "updateMask", )) & set(("securityMarks", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_security_marks_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) + + request = securitycenter_service.UpdateSecurityMarksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_security_marks.SecurityMarks() + + client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_security_marks(request) + + +def test_update_security_marks_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + + # get arguments that satisfy an http rule for this method + sample_request = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + + # get truthy value for each flattened field + mock_args = dict( + security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}" % client.transport._host, args[1]) + + +def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + +def test_update_security_marks_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SecurityCenterClient( + 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 = SecurityCenterClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecurityCenterClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, +]) +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() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SecurityCenterClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecurityCenterGrpcTransport, + ) + +def test_security_center_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_security_center_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_source', + 'create_finding', + 'get_iam_policy', + 'get_organization_settings', + 'get_source', + 'group_assets', + 'group_findings', + 'list_assets', + 'list_findings', + 'list_sources', + 'run_asset_discovery', + 'set_finding_state', + 'set_iam_policy', + 'test_iam_permissions', + 'update_finding', + 'update_organization_settings', + 'update_source', + 'update_security_marks', + ) + 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_security_center_base_transport_with_credentials_file(): + # Instantiate the 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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + 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_security_center_base_transport_with_adc(): + # Test the default 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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +def test_security_center_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) + SecurityCenterClient() + 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_transport_auth_adc(transport_class): + # If 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, + ], +) +def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_security_center_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host 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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_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.SecurityCenterRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_security_center_rest_lro_client(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a 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 + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_no_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_with_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_security_center_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SecurityCenterClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SecurityCenterClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_source._session + session2 = client2.transport.create_source._session + assert session1 != session2 + session1 = client1.transport.create_finding._session + session2 = client2.transport.create_finding._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.get_organization_settings._session + session2 = client2.transport.get_organization_settings._session + assert session1 != session2 + session1 = client1.transport.get_source._session + session2 = client2.transport.get_source._session + assert session1 != session2 + session1 = client1.transport.group_assets._session + session2 = client2.transport.group_assets._session + assert session1 != session2 + session1 = client1.transport.group_findings._session + session2 = client2.transport.group_findings._session + assert session1 != session2 + session1 = client1.transport.list_assets._session + session2 = client2.transport.list_assets._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_sources._session + session2 = client2.transport.list_sources._session + assert session1 != session2 + session1 = client1.transport.run_asset_discovery._session + session2 = client2.transport.run_asset_discovery._session + assert session1 != session2 + session1 = client1.transport.set_finding_state._session + session2 = client2.transport.set_finding_state._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 + session1 = client1.transport.update_finding._session + session2 = client2.transport.update_finding._session + assert session1 != session2 + session1 = client1.transport.update_organization_settings._session + session2 = client2.transport.update_organization_settings._session + assert session1 != session2 + session1 = client1.transport.update_source._session + session2 = client2.transport.update_source._session + assert session1 != session2 + session1 = client1.transport.update_security_marks._session + session2 = client2.transport.update_security_marks._session + assert session1 != session2 +def test_security_center_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcTransport( + 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_security_center_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcAsyncIOTransport( + 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(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_security_center_grpc_lro_client(): + client = SecurityCenterClient( + 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_security_center_grpc_lro_async_client(): + client = SecurityCenterAsyncClient( + 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_asset_path(): + organization = "squid" + asset = "clam" + expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.asset_path(organization, asset) + assert expected == actual + + +def test_parse_asset_path(): + expected = { + "organization": "whelk", + "asset": "octopus", + } + path = SecurityCenterClient.asset_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_asset_path(path) + assert expected == actual + +def test_finding_path(): + organization = "oyster" + source = "nudibranch" + finding = "cuttlefish" + expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + actual = SecurityCenterClient.finding_path(organization, source, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "organization": "mussel", + "source": "winkle", + "finding": "nautilus", + } + path = SecurityCenterClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_finding_path(path) + assert expected == actual + +def test_organization_settings_path(): + organization = "scallop" + expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) + actual = SecurityCenterClient.organization_settings_path(organization) + assert expected == actual + + +def test_parse_organization_settings_path(): + expected = { + "organization": "abalone", + } + path = SecurityCenterClient.organization_settings_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_organization_settings_path(path) + assert expected == actual + +def test_security_marks_path(): + organization = "squid" + asset = "clam" + expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.security_marks_path(organization, asset) + assert expected == actual + + +def test_parse_security_marks_path(): + expected = { + "organization": "whelk", + "asset": "octopus", + } + path = SecurityCenterClient.security_marks_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_marks_path(path) + assert expected == actual + +def test_source_path(): + organization = "oyster" + source = "nudibranch" + expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + actual = SecurityCenterClient.source_path(organization, source) + assert expected == actual + + +def test_parse_source_path(): + expected = { + "organization": "cuttlefish", + "source": "mussel", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SecurityCenterClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = SecurityCenterClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = SecurityCenterClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = SecurityCenterClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SecurityCenterClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = SecurityCenterClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = SecurityCenterClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = SecurityCenterClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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 = SecurityCenterClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = SecurityCenterClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + transport_class = SecurityCenterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), +]) +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-securitycenter/v1p1beta1/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.coveragerc new file mode 100644 index 000000000000..45cb273f8f7c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/securitycenter/__init__.py + google/cloud/securitycenter/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-securitycenter/v1p1beta1/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.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-securitycenter/v1p1beta1/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/MANIFEST.in new file mode 100644 index 000000000000..57b563bd1a48 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/securitycenter *.py +recursive-include google/cloud/securitycenter_v1p1beta1 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst new file mode 100644 index 000000000000..f8c63f4cb48a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v1p1beta1/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/conf.py new file mode 100644 index 000000000000..8e92d2319721 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter 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-securitycenter" +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-securitycenter-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-securitycenter.tex", + u"google-cloud-securitycenter 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-securitycenter", + u"Google Cloud Securitycenter 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-securitycenter", + u"google-cloud-securitycenter Documentation", + author, + "google-cloud-securitycenter", + "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v1p1beta1/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/index.rst new file mode 100644 index 000000000000..45263147b433 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + securitycenter_v1p1beta1/services + securitycenter_v1p1beta1/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst new file mode 100644 index 000000000000..adab7f4a5e87 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst @@ -0,0 +1,10 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center + :members: + :inherited-members: + +.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst new file mode 100644 index 000000000000..7f537e851e63 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v1p1beta1 API +====================================================== +.. toctree:: + :maxdepth: 2 + + security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst new file mode 100644 index 000000000000..a68ac5c68cff --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Securitycenter v1p1beta1 API +=================================================== + +.. automodule:: google.cloud.securitycenter_v1p1beta1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py new file mode 100644 index 000000000000..fe0af04fb73b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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.securitycenter import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.securitycenter_v1p1beta1.services.security_center.client import SecurityCenterClient +from google.cloud.securitycenter_v1p1beta1.services.security_center.async_client import SecurityCenterAsyncClient + +from google.cloud.securitycenter_v1p1beta1.types.asset import Asset +from google.cloud.securitycenter_v1p1beta1.types.finding import Finding +from google.cloud.securitycenter_v1p1beta1.types.folder import Folder +from google.cloud.securitycenter_v1p1beta1.types.notification_config import NotificationConfig +from google.cloud.securitycenter_v1p1beta1.types.notification_message import NotificationMessage +from google.cloud.securitycenter_v1p1beta1.types.organization_settings import OrganizationSettings +from google.cloud.securitycenter_v1p1beta1.types.resource import Resource +from google.cloud.securitycenter_v1p1beta1.types.run_asset_discovery_response import RunAssetDiscoveryResponse +from google.cloud.securitycenter_v1p1beta1.types.security_marks import SecurityMarks +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateFindingRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateNotificationConfigRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateSourceRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import DeleteNotificationConfigRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetNotificationConfigRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetOrganizationSettingsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetSourceRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupAssetsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupAssetsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupFindingsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupFindingsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupResult +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListAssetsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListAssetsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListFindingsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListFindingsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListNotificationConfigsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListNotificationConfigsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListSourcesRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListSourcesResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import RunAssetDiscoveryRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import SetFindingStateRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateFindingRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateNotificationConfigRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateOrganizationSettingsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateSecurityMarksRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateSourceRequest +from google.cloud.securitycenter_v1p1beta1.types.source import Source + +__all__ = ('SecurityCenterClient', + 'SecurityCenterAsyncClient', + 'Asset', + 'Finding', + 'Folder', + 'NotificationConfig', + 'NotificationMessage', + 'OrganizationSettings', + 'Resource', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateNotificationConfigRequest', + 'CreateSourceRequest', + 'DeleteNotificationConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/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-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py new file mode 100644 index 000000000000..84391a72a3b7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__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 google.cloud.securitycenter_v1p1beta1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + +from .types.asset import Asset +from .types.finding import Finding +from .types.folder import Folder +from .types.notification_config import NotificationConfig +from .types.notification_message import NotificationMessage +from .types.organization_settings import OrganizationSettings +from .types.resource import Resource +from .types.run_asset_discovery_response import RunAssetDiscoveryResponse +from .types.security_marks import SecurityMarks +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateNotificationConfigRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import DeleteNotificationConfigRequest +from .types.securitycenter_service import GetNotificationConfigRequest +from .types.securitycenter_service import GetOrganizationSettingsRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GroupAssetsRequest +from .types.securitycenter_service import GroupAssetsResponse +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAssetsRequest +from .types.securitycenter_service import ListAssetsResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListNotificationConfigsRequest +from .types.securitycenter_service import ListNotificationConfigsResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import RunAssetDiscoveryRequest +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateNotificationConfigRequest +from .types.securitycenter_service import UpdateOrganizationSettingsRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.source import Source + +__all__ = ( + 'SecurityCenterAsyncClient', +'Asset', +'CreateFindingRequest', +'CreateNotificationConfigRequest', +'CreateSourceRequest', +'DeleteNotificationConfigRequest', +'Finding', +'Folder', +'GetNotificationConfigRequest', +'GetOrganizationSettingsRequest', +'GetSourceRequest', +'GroupAssetsRequest', +'GroupAssetsResponse', +'GroupFindingsRequest', +'GroupFindingsResponse', +'GroupResult', +'ListAssetsRequest', +'ListAssetsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListNotificationConfigsRequest', +'ListNotificationConfigsResponse', +'ListSourcesRequest', +'ListSourcesResponse', +'NotificationConfig', +'NotificationMessage', +'OrganizationSettings', +'Resource', +'RunAssetDiscoveryRequest', +'RunAssetDiscoveryResponse', +'SecurityCenterClient', +'SecurityMarks', +'SetFindingStateRequest', +'Source', +'UpdateFindingRequest', +'UpdateNotificationConfigRequest', +'UpdateOrganizationSettingsRequest', +'UpdateSecurityMarksRequest', +'UpdateSourceRequest', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json new file mode 100644 index 000000000000..892a85e5f9fd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json @@ -0,0 +1,373 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v1p1beta1", + "protoPackage": "google.cloud.securitycenter.v1p1beta1", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "rest": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py new file mode 100644 index 000000000000..bffcff5da306 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + 'SecurityCenterClient', + 'SecurityCenterAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py new file mode 100644 index 000000000000..a996989322a3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py @@ -0,0 +1,3039 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.securitycenter_v1p1beta1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.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.securitycenter_v1p1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1p1beta1.types import security_marks +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_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 SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V1p1Beta1 APIs for Security Center service.""" + + _client: SecurityCenterClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE + + asset_path = staticmethod(SecurityCenterClient.asset_path) + parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) + parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) + notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) + parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) + organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) + parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) + source_path = staticmethod(SecurityCenterClient.source_path) + parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) + topic_path = staticmethod(SecurityCenterClient.topic_path) + parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) + common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) + parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) + common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) + parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) + common_project_path = staticmethod(SecurityCenterClient.common_project_path) + parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) + common_location_path = staticmethod(SecurityCenterClient.common_location_path) + parse_common_location_path = staticmethod(SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v1p1beta1 + + async def sample_create_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest, dict]]): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = 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_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding_id: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_create_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest, dict]]): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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 create_notification_config(self, + request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + config_id: Optional[str] = None, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_create_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest, dict]]): + The request object. Request message for creating a + notification config. + parent (:class:`str`): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be between 1 and 128 characters, + and contains alphanumeric characters, + underscores or hyphens only. + + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_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.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_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_notification_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_notification_config(self, + request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest, dict]]): + The request object. Request message for deleting a + notification config. + name (:class:`str`): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1p1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 get_notification_config(self, + request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_get_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest, dict]]): + The request object. Request message for getting a + notification config. + name (:class:`str`): + Required. Name of the notification config to get. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 get_organization_settings(self, + request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest, dict]]): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_organization_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 get_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v1p1beta1 + + async def sample_get_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest, dict]]): + The request object. Request message for getting a source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 group_assets(self, + request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsAsyncPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_group_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest, dict]]): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsAsyncPager: + Response message for grouping by + assets. + 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, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.GroupAssetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_group_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest, dict]]): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + The following fields are supported when compare_duration + is set: + + - state_change + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets(self, + request: Optional[Union[securitycenter_service.ListAssetsRequest, 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.ListAssetsAsyncPager: + r"""Lists an organization's assets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_list_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest, dict]]): + The request object. Request message for listing assets. + parent (:class:`str`): + Required. Name of the organization assets should belong + to. Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsAsyncPager: + Response message for listing assets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListAssetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings(self, + request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsAsyncPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_list_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListFindingsRequest( + parent="parent_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.securitycenter_v1p1beta1.types.ListFindingsRequest, dict]]): + The request object. Request message for listing findings. + parent (:class:`str`): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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_notification_configs(self, + request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsAsyncPager: + r"""Lists notification configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest, dict]]): + The request object. Request message for listing + notification configs. + parent (:class:`str`): + Required. Name of the organization to list notification + configs. Its format is + "organizations/[organization_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsAsyncPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListNotificationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_list_sources(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest, dict]]): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id], folders/[folder_id], + or projects/[project_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesAsyncPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_asset_discovery(self, + request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS 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 securitycenter_v1p1beta1 + + async def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest, dict]]): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` + Response of asset discovery run + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.run_asset_discovery] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + start_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of 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 securitycenter_v1p1beta1 + + async def sample_set_finding_state(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest, dict]]): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding.State`): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1p1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v1p1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 update_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + update_mask: 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]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_update_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest, dict]]): + The request object. Request message for updating or + creating a finding. + finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + + 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.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + 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_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe domain. + self._client._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_config(self, + request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, + *, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + update_mask: 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_update_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest, dict]]): + The request object. Request message for updating a + notification config. + notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the notification config. + If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_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 update_organization_settings(self, + request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, + *, + organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = await client.update_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest, dict]]): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings`): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_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 update_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + update_mask: 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]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v1p1beta1 + + async def sample_update_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest, dict]]): + The request object. Request message for updating a + source. + source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): + Required. The source resource to + update. + + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the source resource. + If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = 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_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + update_mask: 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]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + async def sample_update_security_marks(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest, dict]]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`google.cloud.securitycenter_v1p1beta1.types.SecurityMarks`): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + + 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.securitycenter_v1p1beta1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + 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_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe domain. + self._client._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) -> "SecurityCenterAsyncClient": + 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__ = ( + "SecurityCenterAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py new file mode 100644 index 000000000000..caeded73d36f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py @@ -0,0 +1,3441 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_v1p1beta1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from 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.securitycenter_v1p1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1p1beta1.types import security_marks +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_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 SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .transports.rest import SecurityCenterRestTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + _transport_registry["rest"] = SecurityCenterRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SecurityCenterTransport]: + """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V1p1Beta1 APIs for Security Center 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 = "securitycenter.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: + SecurityCenterClient: 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: + SecurityCenterClient: 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) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def asset_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified asset string.""" + return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_asset_path(path: str) -> Dict[str,str]: + """Parses a asset path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def finding_path(organization: str,source: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def notification_config_path(organization: str,notification_config: str,) -> str: + """Returns a fully-qualified notification_config string.""" + return "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) + + @staticmethod + def parse_notification_config_path(path: str) -> Dict[str,str]: + """Parses a notification_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def organization_settings_path(organization: str,) -> str: + """Returns a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format(organization=organization, ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str,str]: + """Parses a organization_settings path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str,str]: + """Parses a security_marks path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str,source: str,) -> str: + """Returns a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str,str]: + """Parses a source path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def topic_path(project: str,topic: str,) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str,str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 + SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient._read_environment_variables() + self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) + if transport_provided: + # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SecurityCenterTransport], 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_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v1p1beta1 + + def sample_create_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest, dict]): + The request object. Request message for creating a + source. + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (google.cloud.securitycenter_v1p1beta1.types.Source): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding_id: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_create_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest, dict]): + The request object. Request message for creating a + finding. + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (str): + Required. Unique identifier provided + by the client within the parent scope. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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 create_notification_config(self, + request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + config_id: Optional[str] = None, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_create_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest, dict]): + The request object. Request message for creating a + notification config. + parent (str): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must be between 1 and 128 characters, + and contains alphanumeric characters, + underscores or hyphens only. + + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_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.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_notification_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_notification_config(self, + request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest, dict]): + The request object. Request message for deleting a + notification config. + name (str): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1p1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 get_notification_config(self, + request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_get_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest, dict]): + The request object. Request message for getting a + notification config. + name (str): + Required. Name of the notification config to get. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 get_organization_settings(self, + request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest, dict]): + The request object. Request message for getting + organization settings. + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_organization_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 get_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v1p1beta1 + + def sample_get_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest, dict]): + The request object. Request message for getting a source. + name (str): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 group_assets(self, + request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_group_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest, dict]): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsPager: + Response message for grouping by + assets. + 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, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.GroupAssetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_group_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest, dict]): + The request object. Request message for grouping by + findings. + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (str): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + The following fields are supported when compare_duration + is set: + + - state_change + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets(self, + request: Optional[Union[securitycenter_service.ListAssetsRequest, 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.ListAssetsPager: + r"""Lists an organization's assets. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_list_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest, dict]): + The request object. Request message for listing assets. + parent (str): + Required. Name of the organization assets should belong + to. Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsPager: + Response message for listing assets. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListAssetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings(self, + request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_list_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListFindingsRequest( + parent="parent_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.securitycenter_v1p1beta1.types.ListFindingsRequest, dict]): + The request object. Request message for listing findings. + parent (str): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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_notification_configs(self, + request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsPager: + r"""Lists notification configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest, dict]): + The request object. Request message for listing + notification configs. + parent (str): + Required. Name of the organization to list notification + configs. Its format is + "organizations/[organization_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListNotificationConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_list_sources(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest, dict]): + The request object. Request message for listing sources. + parent (str): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id], folders/[folder_id], + or projects/[project_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_asset_discovery(self, + request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), + ) -> operation.Operation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS 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 securitycenter_v1p1beta1 + + def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest, dict]): + The request object. Request message for running asset + discovery for an organization. + parent (str): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` + Response of asset discovery run + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.run_asset_discovery] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + start_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of 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 securitycenter_v1p1beta1 + + def sample_set_finding_state(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest, dict]): + The request object. Request message for updating a + finding's state. + name (str): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v1p1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v1p1beta1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # 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 + + def update_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + update_mask: 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]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_update_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest, dict]): + The request object. Request message for updating or + creating a finding. + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + + 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.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + 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_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe 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_config(self, + request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, + *, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + update_mask: 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_update_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest, dict]): + The request object. Request message for updating a + notification config. + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the notification config. + If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_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 update_organization_settings(self, + request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, + *, + organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = client.update_organization_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest, dict]): + The request object. Request message for updating an + organization's settings. + organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_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 update_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + update_mask: 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]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v1p1beta1 + + def sample_update_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest, dict]): + The request object. Request message for updating a + source. + source (google.cloud.securitycenter_v1p1beta1.types.Source): + Required. The source resource to + update. + + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the source resource. + If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = 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_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + update_mask: 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]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v1p1beta1 + + def sample_update_security_marks(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest, dict]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + + 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.securitycenter_v1p1beta1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + 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_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe 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) -> "SecurityCenterClient": + 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__ = ( + "SecurityCenterClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py new file mode 100644 index 000000000000..ddad1b803817 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py @@ -0,0 +1,839 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from 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.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source + + +class GroupAssetsPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupAssetsResponse], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1p1beta1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + 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[securitycenter_service.GroupAssetsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupAssetsAsyncPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` + attributes are available on the 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[securitycenter_service.GroupAssetsResponse]], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1p1beta1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + 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[securitycenter_service.GroupAssetsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1p1beta1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` + attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1p1beta1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListAssetsResponse], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + 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[securitycenter_service.ListAssetsResponse]: + 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + for page in self.pages: + yield from page.list_assets_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` + attributes are available on the 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[securitycenter_service.ListAssetsResponse]], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + 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[securitycenter_service.ListAssetsResponse]: + 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_assets_results: + 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.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.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[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v1p1beta1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + for page in self.pages: + yield from page.list_findings_results + + 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.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.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[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v1p1beta1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_findings_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + 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[securitycenter_service.ListNotificationConfigsResponse]: + 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[notification_config.NotificationConfig]: + for page in self.pages: + yield from page.notification_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsAsyncPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` + attributes are available on the 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[securitycenter_service.ListNotificationConfigsResponse]], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + 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[securitycenter_service.ListNotificationConfigsResponse]: + 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[notification_config.NotificationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.notification_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1p1beta1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` + attributes are available on the 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[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1p1beta1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.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-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py new file mode 100644 index 000000000000..9d36139c1a9b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/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 SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .rest import SecurityCenterRestTransport +from .rest import SecurityCenterRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry['grpc'] = SecurityCenterGrpcTransport +_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport +_transport_registry['rest'] = SecurityCenterRestTransport + +__all__ = ( + 'SecurityCenterTransport', + 'SecurityCenterGrpcTransport', + 'SecurityCenterGrpcAsyncIOTransport', + 'SecurityCenterRestTransport', + 'SecurityCenterRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py new file mode 100644 index 000000000000..00cffef9c86f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.securitycenter_v1p1beta1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +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.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +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 empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'securitycenter.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.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: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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_source: gapic_v1.method.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method.wrap_method( + self.create_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method.wrap_method( + self.delete_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_notification_config: gapic_v1.method.wrap_method( + self.get_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_settings: gapic_v1.method.wrap_method( + self.get_organization_settings, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_source: gapic_v1.method.wrap_method( + self.get_source, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.group_assets: gapic_v1.method.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method.wrap_method( + self.list_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_sources: gapic_v1.method.wrap_method( + self.list_sources, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.run_asset_discovery: gapic_v1.method.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_finding: gapic_v1.method.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method.wrap_method( + self.update_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=480.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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + 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 get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Union[ + notification_config.NotificationConfig, + Awaitable[notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Union[ + organization_settings.OrganizationSettings, + Awaitable[organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Union[ + source.Source, + Awaitable[source.Source] + ]]: + raise NotImplementedError() + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Union[ + securitycenter_service.GroupAssetsResponse, + Awaitable[securitycenter_service.GroupAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Union[ + securitycenter_service.GroupFindingsResponse, + Awaitable[securitycenter_service.GroupFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Union[ + securitycenter_service.ListAssetsResponse, + Awaitable[securitycenter_service.ListAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Union[ + securitycenter_service.ListFindingsResponse, + Awaitable[securitycenter_service.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Union[ + securitycenter_service.ListNotificationConfigsResponse, + Awaitable[securitycenter_service.ListNotificationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Union[ + securitycenter_service.ListSourcesResponse, + Awaitable[securitycenter_service.ListSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + 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 test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Union[ + gcs_organization_settings.OrganizationSettings, + Awaitable[gcs_organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Union[ + gcs_security_marks.SecurityMarks, + Awaitable[gcs_security_marks.SecurityMarks] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SecurityCenterTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py new file mode 100644 index 000000000000..a2a5e40ef1f0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py @@ -0,0 +1,895 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import 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.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +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 empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V1p1Beta1 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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 create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + ~.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_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + ~.GroupAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + 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.securitycenter.v1p1beta1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + ~.ListNotificationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + operations_pb2.Operation]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + ~.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 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + ~.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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SecurityCenterGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 000000000000..0743b78ddbd6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,1125 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +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 empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V1p1Beta1 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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._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 create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + 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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + 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_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Awaitable[notification_config.NotificationConfig]]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Awaitable[organization_settings.OrganizationSettings]]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Awaitable[securitycenter_service.GroupAssetsResponse]]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + Awaitable[~.GroupAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse]]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Awaitable[securitycenter_service.ListAssetsResponse]]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + 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.securitycenter.v1p1beta1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + Awaitable[~.ListNotificationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse]]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + 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 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + 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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.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.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + 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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Awaitable[gcs_organization_settings.OrganizationSettings]]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks]]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + 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_source: gapic_v1.method_async.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method_async.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method_async.wrap_method( + self.create_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method_async.wrap_method( + self.delete_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_notification_config: gapic_v1.method_async.wrap_method( + self.get_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_organization_settings: gapic_v1.method_async.wrap_method( + self.get_organization_settings, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_source: gapic_v1.method_async.wrap_method( + self.get_source, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.group_assets: gapic_v1.method_async.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method_async.wrap_method( + self.group_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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method_async.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method_async.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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method_async.wrap_method( + self.list_notification_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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_sources: gapic_v1.method_async.wrap_method( + self.list_sources, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.run_asset_discovery: gapic_v1.method_async.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method_async.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions, + 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=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_finding: gapic_v1.method_async.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method_async.wrap_method( + self.update_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method_async.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method_async.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method_async.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py new file mode 100644 index 000000000000..ea67cf703231 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py @@ -0,0 +1,3197 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # 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 path_template +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 +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SecurityCenterRestInterceptor: + """Interceptor for SecurityCenter. + + 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 SecurityCenterRestTransport. + + .. code-block:: python + class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): + def pre_create_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_organization_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_organization_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_assets(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_notification_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_notification_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_run_asset_discovery(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_asset_discovery(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_finding_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_finding_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_organization_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_organization_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_security_marks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_security_marks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_source(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) + client = SecurityCenterClient(transport=transport) + + + """ + def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for create_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_notification_config(self, request: securitycenter_service.CreateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for create_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_delete_notification_config(self, request: securitycenter_service.DeleteNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_notification_config(self, request: securitycenter_service.GetNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_notification_config(self, response: notification_config.NotificationConfig) -> notification_config.NotificationConfig: + """Post-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_organization_settings(self, request: securitycenter_service.GetOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_organization_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_organization_settings(self, response: organization_settings.OrganizationSettings) -> organization_settings.OrganizationSettings: + """Post-rpc interceptor for get_organization_settings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_source(self, response: source.Source) -> source.Source: + """Post-rpc interceptor for get_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_assets(self, request: securitycenter_service.GroupAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_assets(self, response: securitycenter_service.GroupAssetsResponse) -> securitycenter_service.GroupAssetsResponse: + """Post-rpc interceptor for group_assets + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: + """Post-rpc interceptor for group_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_assets(self, request: securitycenter_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_assets(self, response: securitycenter_service.ListAssetsResponse) -> securitycenter_service.ListAssetsResponse: + """Post-rpc interceptor for list_assets + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. + """ + return request, metadata + + def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_notification_configs(self, request: securitycenter_service.ListNotificationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListNotificationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_notification_configs(self, response: securitycenter_service.ListNotificationConfigsResponse) -> securitycenter_service.ListNotificationConfigsResponse: + """Post-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_sources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: + """Post-rpc interceptor for list_sources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_run_asset_discovery(self, request: securitycenter_service.RunAssetDiscoveryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.RunAssetDiscoveryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for run_asset_discovery + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_run_asset_discovery(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for run_asset_discovery + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for update_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_notification_config(self, request: securitycenter_service.UpdateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_organization_settings(self, request: securitycenter_service.UpdateOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_organization_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_organization_settings(self, response: gcs_organization_settings.OrganizationSettings) -> gcs_organization_settings.OrganizationSettings: + """Post-rpc interceptor for update_organization_settings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: + """Post-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for update_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SecurityCenterRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SecurityCenterRestInterceptor + + +class SecurityCenterRestTransport(SecurityCenterTransport): + """REST backend transport for SecurityCenter. + + V1p1Beta1 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[SecurityCenterRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 + 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 + ) + 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 SecurityCenterRestInterceptor() + 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': '/v1p1beta1/{name=organizations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1p1beta1/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1p1beta1/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1p1beta1/{name=organizations/*/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="v1p1beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "findingId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the create finding method over HTTP. + + Args: + request (~.securitycenter_service.CreateFindingRequest): + The request object. Request message for creating a + finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=organizations/*/sources/*}/findings', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_create_finding(request, metadata) + pb_request = securitycenter_service.CreateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_finding(resp) + return resp + + class _CreateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "configId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the create notification + config method over HTTP. + + Args: + request (~.securitycenter_service.CreateNotificationConfigRequest): + The request object. Request message for creating a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=organizations/*}/notificationConfigs', + 'body': 'notification_config', + }, + ] + request, metadata = self._interceptor.pre_create_notification_config(request, metadata) + pb_request = securitycenter_service.CreateNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_notification_config(resp) + return resp + + class _CreateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the create source method over HTTP. + + Args: + request (~.securitycenter_service.CreateSourceRequest): + The request object. Request message for creating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=organizations/*}/sources', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_create_source(request, metadata) + pb_request = securitycenter_service.CreateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_source(resp) + return resp + + class _DeleteNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete notification + config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteNotificationConfigRequest): + The request object. Request message for deleting a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1p1beta1/{name=organizations/*/notificationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_notification_config(request, metadata) + pb_request = securitycenter_service.DeleteNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _GetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{resource=organizations/*/sources/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> notification_config.NotificationConfig: + r"""Call the get notification config method over HTTP. + + Args: + request (~.securitycenter_service.GetNotificationConfigRequest): + The request object. Request message for getting a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.notification_config.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{name=organizations/*/notificationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_notification_config(request, metadata) + pb_request = securitycenter_service.GetNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = notification_config.NotificationConfig() + pb_resp = notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_notification_config(resp) + return resp + + class _GetOrganizationSettings(SecurityCenterRestStub): + def __hash__(self): + return hash("GetOrganizationSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetOrganizationSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> organization_settings.OrganizationSettings: + r"""Call the get organization settings method over HTTP. + + Args: + request (~.securitycenter_service.GetOrganizationSettingsRequest): + The request object. Request message for getting + organization 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: + ~.organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{name=organizations/*/organizationSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_organization_settings(request, metadata) + pb_request = securitycenter_service.GetOrganizationSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = organization_settings.OrganizationSettings() + pb_resp = organization_settings.OrganizationSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_organization_settings(resp) + return resp + + class _GetSource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> source.Source: + r"""Call the get source method over HTTP. + + Args: + request (~.securitycenter_service.GetSourceRequest): + The request object. Request message for getting a source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{name=organizations/*/sources/*}', + }, + ] + request, metadata = self._interceptor.pre_get_source(request, metadata) + pb_request = securitycenter_service.GetSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = source.Source() + pb_resp = source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_source(resp) + return resp + + class _GroupAssets(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupAssetsResponse: + r"""Call the group assets method over HTTP. + + Args: + request (~.securitycenter_service.GroupAssetsRequest): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupAssetsResponse: + Response message for grouping by + assets. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=organizations/*}/assets:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=folders/*}/assets:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=projects/*}/assets:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_assets(request, metadata) + pb_request = securitycenter_service.GroupAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupAssetsResponse() + pb_resp = securitycenter_service.GroupAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_assets(resp) + return resp + + class _GroupFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupFindingsResponse: + r"""Call the group findings method over HTTP. + + Args: + request (~.securitycenter_service.GroupFindingsRequest): + The request object. Request message for grouping by + findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupFindingsResponse: + Response message for group by + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=organizations/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=folders/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=projects/*/sources/*}/findings:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_findings(request, metadata) + pb_request = securitycenter_service.GroupFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupFindingsResponse() + pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_findings(resp) + return resp + + class _ListAssets(SecurityCenterRestStub): + def __hash__(self): + return hash("ListAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListAssetsResponse: + r"""Call the list assets method over HTTP. + + Args: + request (~.securitycenter_service.ListAssetsRequest): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListAssetsResponse: + Response message for listing assets. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=organizations/*}/assets', + }, +{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=folders/*}/assets', + }, +{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=projects/*}/assets', + }, + ] + request, metadata = self._interceptor.pre_list_assets(request, metadata) + pb_request = securitycenter_service.ListAssetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListAssetsResponse() + pb_resp = securitycenter_service.ListAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_assets(resp) + return resp + + class _ListFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("ListFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.securitycenter_service.ListFindingsRequest): + The request object. Request message for listing findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListFindingsResponse: + Response message for listing + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=organizations/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=folders/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=projects/*/sources/*}/findings', + }, + ] + request, metadata = self._interceptor.pre_list_findings(request, metadata) + pb_request = securitycenter_service.ListFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListFindingsResponse() + pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListNotificationConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListNotificationConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListNotificationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListNotificationConfigsResponse: + r"""Call the list notification configs method over HTTP. + + Args: + request (~.securitycenter_service.ListNotificationConfigsRequest): + The request object. Request message for listing + notification configs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListNotificationConfigsResponse: + Response message for listing + notification configs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=organizations/*}/notificationConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_notification_configs(request, metadata) + pb_request = securitycenter_service.ListNotificationConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListNotificationConfigsResponse() + pb_resp = securitycenter_service.ListNotificationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_notification_configs(resp) + return resp + + class _ListSources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListSources") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListSourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListSourcesResponse: + r"""Call the list sources method over HTTP. + + Args: + request (~.securitycenter_service.ListSourcesRequest): + The request object. Request message for listing sources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListSourcesResponse: + Response message for listing sources. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=organizations/*}/sources', + }, +{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=folders/*}/sources', + }, +{ + 'method': 'get', + 'uri': '/v1p1beta1/{parent=projects/*}/sources', + }, + ] + request, metadata = self._interceptor.pre_list_sources(request, metadata) + pb_request = securitycenter_service.ListSourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListSourcesResponse() + pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sources(resp) + return resp + + class _RunAssetDiscovery(SecurityCenterRestStub): + def __hash__(self): + return hash("RunAssetDiscovery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.RunAssetDiscoveryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the run asset discovery method over HTTP. + + Args: + request (~.securitycenter_service.RunAssetDiscoveryRequest): + The request object. Request message for running asset + discovery for an organization. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{parent=organizations/*}/assets:runDiscovery', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_run_asset_discovery(request, metadata) + pb_request = securitycenter_service.RunAssetDiscoveryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_run_asset_discovery(resp) + return resp + + class _SetFindingState(SecurityCenterRestStub): + def __hash__(self): + return hash("SetFindingState") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SetFindingStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the set finding state method over HTTP. + + Args: + request (~.securitycenter_service.SetFindingStateRequest): + The request object. Request message for updating a + finding's state. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{name=organizations/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1p1beta1/{name=folders/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1p1beta1/{name=projects/*/sources/*/findings/*}:setState', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_finding_state(request, metadata) + pb_request = securitycenter_service.SetFindingStateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_set_finding_state(resp) + return resp + + class _SetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{resource=organizations/*/sources/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _TestIamPermissions(SecurityCenterRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p1beta1/{resource=organizations/*/sources/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UpdateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the update finding method over HTTP. + + Args: + request (~.securitycenter_service.UpdateFindingRequest): + The request object. Request message for updating or + creating a finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p1beta1/{finding.name=organizations/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{finding.name=folders/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{finding.name=projects/*/sources/*/findings/*}', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_update_finding(request, metadata) + pb_request = securitycenter_service.UpdateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_finding(resp) + return resp + + class _UpdateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the update notification + config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateNotificationConfigRequest): + The request object. Request message for updating a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p1beta1/{notification_config.name=organizations/*/notificationConfigs/*}', + 'body': 'notification_config', + }, + ] + request, metadata = self._interceptor.pre_update_notification_config(request, metadata) + pb_request = securitycenter_service.UpdateNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_notification_config(resp) + return resp + + class _UpdateOrganizationSettings(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateOrganizationSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateOrganizationSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Call the update organization + settings method over HTTP. + + Args: + request (~.securitycenter_service.UpdateOrganizationSettingsRequest): + The request object. Request message for updating an + organization's 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: + ~.gcs_organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p1beta1/{organization_settings.name=organizations/*/organizationSettings}', + 'body': 'organization_settings', + }, + ] + request, metadata = self._interceptor.pre_update_organization_settings(request, metadata) + pb_request = securitycenter_service.UpdateOrganizationSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_organization_settings.OrganizationSettings() + pb_resp = gcs_organization_settings.OrganizationSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_organization_settings(resp) + return resp + + class _UpdateSecurityMarks(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSecurityMarks") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSecurityMarksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_security_marks.SecurityMarks: + r"""Call the update security marks method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSecurityMarksRequest): + The request object. Request message for updating a + SecurityMarks resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{security_marks.name=folders/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{security_marks.name=projects/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v1p1beta1/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, + ] + request, metadata = self._interceptor.pre_update_security_marks(request, metadata) + pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_security_marks.SecurityMarks() + pb_resp = gcs_security_marks.SecurityMarks.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_security_marks(resp) + return resp + + class _UpdateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the update source method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSourceRequest): + The request object. Request message for updating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p1beta1/{source.name=organizations/*/sources/*}', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_update_source(request, metadata) + pb_request = securitycenter_service.UpdateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_source(resp) + return resp + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + 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._DeleteNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.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_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListNotificationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + 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._RunAssetDiscovery(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SecurityCenterRestTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py new file mode 100644 index 000000000000..9f0c2b8e8129 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__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 .asset import ( + Asset, +) +from .finding import ( + Finding, +) +from .folder import ( + Folder, +) +from .notification_config import ( + NotificationConfig, +) +from .notification_message import ( + NotificationMessage, +) +from .organization_settings import ( + OrganizationSettings, +) +from .resource import ( + Resource, +) +from .run_asset_discovery_response import ( + RunAssetDiscoveryResponse, +) +from .security_marks import ( + SecurityMarks, +) +from .securitycenter_service import ( + CreateFindingRequest, + CreateNotificationConfigRequest, + CreateSourceRequest, + DeleteNotificationConfigRequest, + GetNotificationConfigRequest, + GetOrganizationSettingsRequest, + GetSourceRequest, + GroupAssetsRequest, + GroupAssetsResponse, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListAssetsRequest, + ListAssetsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListSourcesRequest, + ListSourcesResponse, + RunAssetDiscoveryRequest, + SetFindingStateRequest, + UpdateFindingRequest, + UpdateNotificationConfigRequest, + UpdateOrganizationSettingsRequest, + UpdateSecurityMarksRequest, + UpdateSourceRequest, +) +from .source import ( + Source, +) + +__all__ = ( + 'Asset', + 'Finding', + 'Folder', + 'NotificationConfig', + 'NotificationMessage', + 'OrganizationSettings', + 'Resource', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateNotificationConfigRequest', + 'CreateSourceRequest', + 'DeleteNotificationConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py new file mode 100644 index 000000000000..2250330a504d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py @@ -0,0 +1,227 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1p1beta1.types import folder +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'Asset', + }, +) + + +class Asset(proto.Message): + r"""Security Command Center representation of a Google Cloud + resource. + + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All + modifications to an Asset are only within the context of + Security Command Center and don't affect the referenced Google + Cloud resource. + + Attributes: + name (str): + The relative resource name of this asset. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/assets/{asset_id}". + security_center_properties (google.cloud.securitycenter_v1p1beta1.types.Asset.SecurityCenterProperties): + Security Command Center managed properties. + These properties are managed by Security Command + Center and cannot be modified by the user. + resource_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Resource managed properties. These properties + are managed and defined by the Google Cloud + resource and cannot be modified by the user. + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): + User specified security marks. These marks + are entirely managed by the user and come from + the SecurityMarks resource that belongs to the + asset. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was last updated + or added in Cloud SCC. + iam_policy (google.cloud.securitycenter_v1p1beta1.types.Asset.IamPolicy): + Cloud IAM Policy information associated with + the Google Cloud resource described by the + Security Command Center asset. This information + is managed and defined by the Google Cloud + resource and cannot be modified by the user. + canonical_name (str): + The canonical name of the resource. It's either + "organizations/{organization_id}/assets/{asset_id}", + "folders/{folder_id}/assets/{asset_id}" or + "projects/{project_number}/assets/{asset_id}", depending on + the closest CRM ancestor of the resource. + """ + + class SecurityCenterProperties(proto.Message): + r"""Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified by + the user. + + Attributes: + resource_name (str): + The full resource name of the Google Cloud resource this + asset represents. This field is immutable after create time. + See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_type (str): + The type of the Google Cloud resource. + Examples include: APPLICATION, PROJECT, and + ORGANIZATION. This is a case insensitive field + defined by Security Command Center and/or the + producer of the resource and is immutable after + create time. + resource_parent (str): + The full resource name of the immediate parent of the + resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_project (str): + The full resource name of the project the resource belongs + to. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_owners (MutableSequence[str]): + Owners of the Google Cloud resource. + resource_display_name (str): + The user defined display name for this + resource. + resource_parent_display_name (str): + The user defined display name for the parent + of this resource. + resource_project_display_name (str): + The user defined display name for the project + of this resource. + folders (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. + """ + + resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + resource_parent: str = proto.Field( + proto.STRING, + number=3, + ) + resource_project: str = proto.Field( + proto.STRING, + number=4, + ) + resource_owners: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + resource_display_name: str = proto.Field( + proto.STRING, + number=6, + ) + resource_parent_display_name: str = proto.Field( + proto.STRING, + number=7, + ) + resource_project_display_name: str = proto.Field( + proto.STRING, + number=8, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=folder.Folder, + ) + + class IamPolicy(proto.Message): + r"""Cloud IAM Policy information associated with the Google Cloud + resource described by the Security Command Center asset. This + information is managed and defined by the Google Cloud resource + and cannot be modified by the user. + + Attributes: + policy_blob (str): + The JSON representation of the Policy + associated with the asset. See + https://cloud.google.com/iam/docs/reference/rest/v1/Policy + for format details. + """ + + policy_blob: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + security_center_properties: SecurityCenterProperties = proto.Field( + proto.MESSAGE, + number=2, + message=SecurityCenterProperties, + ) + resource_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + iam_policy: IamPolicy = proto.Field( + proto.MESSAGE, + number=11, + message=IamPolicy, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=13, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py new file mode 100644 index 000000000000..8fe9a48e3cfb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + + A finding is a record of assessment data (security, risk, health + or privacy) ingested into Security Command Center for + presentation, notification, analysis, policy testing, and + enforcement. For example, an XSS vulnerability in an App Engine + application is a finding. + + Attributes: + name (str): + The relative resource name of this finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". + parent (str): + The relative resource name of the source the finding belongs + to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. For example: + "organizations/{organization_id}/sources/{source_id}". + resource_name (str): + For findings on Google Cloud resources, the full resource + name of the Google Cloud resource this finding is for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + This field is immutable after creation time. + state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): + The state of the finding. + category (str): + The additional taxonomy group within findings from a given + source. This field is immutable after creation time. + Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the event took place, or + when an update to the finding occurred. For + example, if the finding represents an open + firewall it would capture the time the detector + believes the firewall became open. The accuracy + is determined by the detector. If the finding + were to be resolved afterward, this time would + reflect when the finding was resolved. Must not + be set to a value greater than the current + timestamp. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the finding was created in + Security Command Center. + severity (google.cloud.securitycenter_v1p1beta1.types.Finding.Severity): + The severity of the finding. This field is + managed by the source that writes the finding. + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" + or + "projects/{project_number}/sources/{source_id}/findings/{finding_id}", + depending on the closest CRM ancestor of the resource + associated with the finding. + """ + class State(proto.Enum): + r"""The state of the finding. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + ACTIVE (1): + The finding requires attention and has not + been addressed yet. + INACTIVE (2): + The finding has been fixed, triaged as a + non-issue or otherwise addressed and is no + longer active. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + class Severity(proto.Enum): + r"""The severity of the finding. This field is managed by the + source that writes the finding. + + 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, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + resource_name: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + category: str = proto.Field( + proto.STRING, + number=5, + ) + external_uri: str = proto.Field( + proto.STRING, + number=6, + ) + source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=13, + enum=Severity, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=14, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py new file mode 100644 index 000000000000..17d1a3c450ed --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.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.securitycenter.v1p1beta1', + manifest={ + 'Folder', + }, +) + + +class Folder(proto.Message): + r"""Message that contains the resource name and display name of a + folder resource. + + Attributes: + resource_folder (str): + Full resource name of this folder. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_folder_display_name (str): + The user defined display name for this + folder. + """ + + resource_folder: str = proto.Field( + proto.STRING, + number=1, + ) + resource_folder_display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py new file mode 100644 index 000000000000..8b92401c657b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'NotificationConfig', + }, +) + + +class NotificationConfig(proto.Message): + r"""Security Command Center notification configs. + + A notification config is a Security Command Center resource that + contains the configuration to send notifications for + create/update events of findings, assets and etc. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The relative resource name of this notification config. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/notificationConfigs/notify_public_bucket". + description (str): + The description of the notification config + (max of 1024 characters). + event_type (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.EventType): + The type of events the config is for, e.g. + FINDING. + pubsub_topic (str): + The Pub/Sub topic to send notifications to. Its format is + "projects/[project_id]/topics/[topic]". + service_account (str): + Output only. The service account that needs + "pubsub.topics.publish" permission to publish to + the Pub/Sub topic. + streaming_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.StreamingConfig): + The config for triggering streaming-based + notifications. + + This field is a member of `oneof`_ ``notify_config``. + """ + class EventType(proto.Enum): + r"""The type of events. + + Values: + EVENT_TYPE_UNSPECIFIED (0): + Unspecified event type. + FINDING (1): + Events for findings. + """ + EVENT_TYPE_UNSPECIFIED = 0 + FINDING = 1 + + class StreamingConfig(proto.Message): + r"""The config for streaming-based notifications, which send each + event as soon as it is detected. + + Attributes: + filter (str): + Expression that defines the filter to apply across + create/update events of assets or findings as specified by + the event type. The expression is a list of zero or more + restrictions combined via logical operators ``AND`` and + ``OR``. Parentheses are supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + """ + + filter: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + event_type: EventType = proto.Field( + proto.ENUM, + number=3, + enum=EventType, + ) + pubsub_topic: str = proto.Field( + proto.STRING, + number=4, + ) + service_account: str = proto.Field( + proto.STRING, + number=5, + ) + streaming_config: StreamingConfig = proto.Field( + proto.MESSAGE, + number=6, + oneof='notify_config', + message=StreamingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py new file mode 100644 index 000000000000..5572db1a6d80 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.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.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import resource as gcs_resource + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'NotificationMessage', + }, +) + + +class NotificationMessage(proto.Message): + r"""Security Command Center's Notification + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + notification_config_name (str): + Name of the notification config that + generated current notification. + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + If it's a Finding based notification config, + this field will be populated. + + This field is a member of `oneof`_ ``event``. + resource (google.cloud.securitycenter_v1p1beta1.types.Resource): + The Cloud resource tied to the notification. + """ + + notification_config_name: str = proto.Field( + proto.STRING, + number=1, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=2, + oneof='event', + message=gcs_finding.Finding, + ) + resource: gcs_resource.Resource = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_resource.Resource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py new file mode 100644 index 000000000000..e8a49050b4aa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'OrganizationSettings', + }, +) + + +class OrganizationSettings(proto.Message): + r"""User specified settings that are attached to the Security + Command Center organization. + + Attributes: + name (str): + The relative resource name of the settings. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/organizationSettings". + enable_asset_discovery (bool): + A flag that indicates if Asset Discovery should be enabled. + If the flag is set to ``true``, then discovery of assets + will occur. If it is set to \`false, all historical assets + will remain, but discovery of future assets will not occur. + asset_discovery_config (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig): + The configuration used for Asset Discovery + runs. + """ + + class AssetDiscoveryConfig(proto.Message): + r"""The configuration used for Asset Discovery runs. + + Attributes: + project_ids (MutableSequence[str]): + The project ids to use for filtering asset + discovery. + inclusion_mode (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + The mode to use for filtering asset + discovery. + folder_ids (MutableSequence[str]): + The folder ids to use for filtering asset + discovery. It consists of only digits, e.g., + 756619654966. + """ + class InclusionMode(proto.Enum): + r"""The mode of inclusion when running Asset Discovery. Asset discovery + can be limited by explicitly identifying projects to be included or + excluded. If INCLUDE_ONLY is set, then only those projects within + the organization and their children are discovered during asset + discovery. If EXCLUDE is set, then projects that don't match those + projects are discovered during asset discovery. If neither are set, + then all projects within the organization are discovered during + asset discovery. + + Values: + INCLUSION_MODE_UNSPECIFIED (0): + Unspecified. Setting the mode with this value + will disable inclusion/exclusion filtering for + Asset Discovery. + INCLUDE_ONLY (1): + Asset Discovery will capture only the + resources within the projects specified. All + other resources will be ignored. + EXCLUDE (2): + Asset Discovery will ignore all resources + under the projects specified. All other + resources will be retrieved. + """ + INCLUSION_MODE_UNSPECIFIED = 0 + INCLUDE_ONLY = 1 + EXCLUDE = 2 + + project_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + inclusion_mode: 'OrganizationSettings.AssetDiscoveryConfig.InclusionMode' = proto.Field( + proto.ENUM, + number=2, + enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', + ) + folder_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + enable_asset_discovery: bool = proto.Field( + proto.BOOL, + number=2, + ) + asset_discovery_config: AssetDiscoveryConfig = proto.Field( + proto.MESSAGE, + number=3, + message=AssetDiscoveryConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py new file mode 100644 index 000000000000..2fd5e7836be1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1p1beta1.types import folder + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'Resource', + }, +) + + +class Resource(proto.Message): + r"""Information related to the Google Cloud resource. + + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + project (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The human readable name of project that the + resource belongs to. + parent (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): + Output only. Contains a Folder message for + each folder in the assets ancestry. The first + folder is the deepest nested folder, and the + last folder is the folder directly under the + Organization. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + project: str = proto.Field( + proto.STRING, + number=2, + ) + project_display_name: str = proto.Field( + proto.STRING, + number=3, + ) + parent: str = proto.Field( + proto.STRING, + number=4, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=5, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=folder.Folder, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py new file mode 100644 index 000000000000..10769c100399 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.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 + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'RunAssetDiscoveryResponse', + }, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + + Attributes: + state (google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (google.protobuf.duration_pb2.Duration): + The duration between asset discovery run + start and end + """ + class State(proto.Enum): + r"""The state of an asset discovery run. + + Values: + STATE_UNSPECIFIED (0): + Asset discovery run state was unspecified. + COMPLETED (1): + Asset discovery run completed successfully. + SUPERSEDED (2): + Asset discovery run was cancelled with tasks + still pending, as another run for the same + organization was started with a higher priority. + TERMINATED (3): + Asset discovery run was killed and + terminated. + """ + STATE_UNSPECIFIED = 0 + COMPLETED = 1 + SUPERSEDED = 2 + TERMINATED = 3 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py new file mode 100644 index 000000000000..8473d65602f2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'SecurityMarks', + }, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". + marks (MutableMapping[str, str]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + canonical_name (str): + The canonical name of the marks. Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "folders/{folder_id}/assets/{asset_id}/securityMarks" + "projects/{project_number}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + marks: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py new file mode 100644 index 000000000000..42ec8bf37842 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py @@ -0,0 +1,1641 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v1p1beta1.types import asset as gcs_asset +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import folder +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'CreateFindingRequest', + 'CreateNotificationConfigRequest', + 'CreateSourceRequest', + 'DeleteNotificationConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'SetFindingStateRequest', + 'RunAssetDiscoveryRequest', + 'UpdateFindingRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSourceRequest', + 'UpdateSecurityMarksRequest', + }, +) + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + + Attributes: + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + finding_id: str = proto.Field( + proto.STRING, + number=2, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_finding.Finding, + ) + + +class CreateNotificationConfigRequest(proto.Message): + r"""Request message for creating a notification config. + + Attributes: + parent (str): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + config_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + between 1 and 128 characters, and contains + alphanumeric characters, underscores or hyphens + only. + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): + Required. The notification config being + created. The name and the service account will + be ignored as they are both output only fields + on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + config_id: str = proto.Field( + proto.STRING, + number=2, + ) + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_notification_config.NotificationConfig, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + source (google.cloud.securitycenter_v1p1beta1.types.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_source.Source, + ) + + +class DeleteNotificationConfigRequest(proto.Message): + r"""Request message for deleting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetNotificationConfigRequest(proto.Message): + r"""Request message for getting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to get. Its format + is + "organizations/[organization_id]/notificationConfigs/[config_id]". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetOrganizationSettingsRequest(proto.Message): + r"""Request message for getting organization settings. + + Attributes: + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is "organizations/[organization_id]/source/[source_id]". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GroupAssetsRequest(proto.Message): + r"""Request message for grouping by assets. + + Attributes: + parent (str): + Required. Name of the organization to groupBy. Its format is + "organizations/[organization_id], folders/[folder_id], or + projects/[project_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_name_display_name: + ``=``, ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is + not set: + + - security_center_properties.resource_project + - security_center_properties.resource_project_display_name + - security_center_properties.resource_type + - security_center_properties.resource_parent + - security_center_properties.resource_parent_display_name + + The following fields are supported when compare_duration is + set: + + - security_center_properties.resource_type + - security_center_properties.resource_project_display_name + - security_center_properties.resource_parent_display_name + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the GroupResult's + "state_change" property is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at + reference_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and reference_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupAssetsResponse``; + indicates that this is a continuation of a prior + ``GroupAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupAssetsResponse(proto.Message): + r"""Response message for grouping by assets. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + + Attributes: + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + - severity: ``=``, ``:`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping (including ``state_change``). The string value + should follow SQL syntax: comma separated list of fields. + For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + The following fields are supported when compare_duration is + set: + + - state_change + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the GroupResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=struct_pb2.Value, + ) + count: int = proto.Field( + proto.INT64, + number=2, + ) + + +class ListNotificationConfigsRequest(proto.Message): + r"""Request message for listing notification configs. + + Attributes: + parent (str): + Required. Name of the organization to list notification + configs. Its format is "organizations/[organization_id]". + page_token (str): + The value returned by the last + ``ListNotificationConfigsResponse``; indicates that this is + a continuation of a prior ``ListNotificationConfigs`` call, + and that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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 ListNotificationConfigsResponse(proto.Message): + r"""Response message for listing notification configs. + + Attributes: + notification_configs (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.NotificationConfig]): + Notification configs belonging to the + requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + notification_configs: MutableSequence[gcs_notification_config.NotificationConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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=7, + ) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAssetsRequest(proto.Message): + r"""Request message for listing assets. + + Attributes: + parent (str): + Required. Name of the organization assets should belong to. + Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following are the allowed field and operator + combinations: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, + ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,resource_properties.a_property". + Redundant space characters in the syntax are insignificant. + "name desc,resource_properties.a_property" and " name desc , + resource_properties.a_property " are equivalent. + + The following fields are supported: name update_time + resource_properties security_marks.marks + security_center_properties.resource_name + security_center_properties.resource_display_name + security_center_properties.resource_parent + security_center_properties.resource_parent_display_name + security_center_properties.resource_project + security_center_properties.resource_project_display_name + security_center_properties.resource_type + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListAssetsResult's + "state_change" attribute is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at read_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at read_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the ListAssetsResult + fields to be listed in the response. + An empty field mask will list all fields. + page_token (str): + The value returned by the last ``ListAssetsResponse``; + indicates that this is a continuation of a prior + ``ListAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=9, + ) + + +class ListAssetsResponse(proto.Message): + r"""Response message for listing assets. + + Attributes: + list_assets_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of assets matching the + query. + """ + + class ListAssetsResult(proto.Message): + r"""Result containing the Asset and its State. + + Attributes: + asset (google.cloud.securitycenter_v1p1beta1.types.Asset): + Asset matching the search request. + state_change (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult.StateChange): + State change of the asset between the points + in time. + """ + class StateChange(proto.Enum): + r"""The change in state of the asset. + + When querying across two points in time this describes the change + between the two points: ADDED, REMOVED, or ACTIVE. If there was no + compare_duration supplied in the request the state change will be: + UNUSED + + Values: + UNUSED (0): + State change is unused, this is the canonical + default for this enum. + ADDED (1): + Asset was added between the points in time. + REMOVED (2): + Asset was removed between the points in time. + ACTIVE (3): + Asset was present at both point(s) in time. + """ + UNUSED = 0 + ADDED = 1 + REMOVED = 2 + ACTIVE = 3 + + asset: gcs_asset.Asset = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_asset.Asset, + ) + state_change: 'ListAssetsResponse.ListAssetsResult.StateChange' = proto.Field( + proto.ENUM, + number=2, + enum='ListAssetsResponse.ListAssetsResult.StateChange', + ) + + @property + def raw_page(self): + return self + + list_assets_results: MutableSequence[ListAssetsResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListAssetsResult, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + + Attributes: + parent (str): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + - severity: ``=``, ``:`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + security_marks.marks: ``=``, ``:`` source_properties: ``=``, + ``:``, ``>``, ``<``, ``>=``, ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,source_properties.a_property". Redundant + space characters in the syntax are insignificant. "name + desc,source_properties.a_property" and " name desc , + source_properties.a_property " are equivalent. + + The following fields are supported: name parent state + category resource_name event_time source_properties + security_marks.marks + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListFindingsResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added in any state during + the compare_duration period of time that precedes the + read_time. This is the time between (read_time - + compare_duration) and read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the Finding fields to + be listed in the response. An empty field mask + will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=9, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + + Attributes: + list_findings_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult]): + Findings matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + class ListFindingsResult(proto.Message): + r"""Result containing the Finding and its StateChange. + + Attributes: + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Finding matching the search request. + state_change (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.StateChange): + State change of the finding between the + points in time. + resource (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.Resource): + Output only. Resource that is associated with + this finding. + """ + class StateChange(proto.Enum): + r"""The change in state of the finding. + + When querying across two points in time this describes the change in + the finding between the two points: CHANGED, UNCHANGED, ADDED, or + REMOVED. Findings can not be deleted, so REMOVED implies that the + finding at timestamp does not match the filter specified, but it did + at timestamp - compare_duration. If there was no compare_duration + supplied in the request the state change will be: UNUSED + + Values: + UNUSED (0): + State change is unused, this is the canonical + default for this enum. + CHANGED (1): + The finding has changed state in some way + between the points in time and existed at both + points. + UNCHANGED (2): + The finding has not changed state between the + points in time and existed at both points. + ADDED (3): + The finding was created between the points in + time. + REMOVED (4): + The finding at timestamp does not match the filter + specified, but it did at timestamp - compare_duration. + """ + UNUSED = 0 + CHANGED = 1 + UNCHANGED = 2 + ADDED = 3 + REMOVED = 4 + + class Resource(proto.Message): + r"""Information related to the Google Cloud resource that is + associated with this finding. + + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + project_name (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The human readable name of project that the + resource belongs to. + parent_name (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + project_name: str = proto.Field( + proto.STRING, + number=2, + ) + project_display_name: str = proto.Field( + proto.STRING, + number=3, + ) + parent_name: str = proto.Field( + proto.STRING, + number=4, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=5, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=folder.Folder, + ) + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + state_change: 'ListFindingsResponse.ListFindingsResult.StateChange' = proto.Field( + proto.ENUM, + number=2, + enum='ListFindingsResponse.ListFindingsResult.StateChange', + ) + resource: 'ListFindingsResponse.ListFindingsResult.Resource' = proto.Field( + proto.MESSAGE, + number=3, + message='ListFindingsResponse.ListFindingsResult.Resource', + ) + + @property + def raw_page(self): + return self + + list_findings_results: MutableSequence[ListFindingsResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListFindingsResult, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + + Attributes: + name (str): + Required. The relative resource name of the finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): + Required. The desired State of the finding. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the updated state + takes effect. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: gcs_finding.Finding.State = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.State, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class RunAssetDiscoveryRequest(proto.Message): + r"""Request message for running asset discovery for an + organization. + + Attributes: + parent (str): + Required. Name of the organization to run asset discovery + for. Its format is "organizations/[organization_id]". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + + Attributes: + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must be alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing source_properties. + Individual source_properties can be added/updated by using + "source_properties." in the field mask. + """ + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateNotificationConfigRequest(proto.Message): + r"""Request message for updating a notification config. + + Attributes: + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): + Required. The notification config to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + notification config. + If empty all mutable fields will be updated. + """ + + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + + Attributes: + organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + settings resource. + If empty all mutable fields will be updated. + """ + + organization_settings: gcs_organization_settings.OrganizationSettings = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_organization_settings.OrganizationSettings, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (google.cloud.securitycenter_v1p1beta1.types.Source): + Required. The source resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the source + resource. + If empty all mutable fields will be updated. + """ + + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): + Required. The security marks resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If empty + or set to "marks", all marks will be replaced. Individual + marks can be updated using "marks.". + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the updated SecurityMarks + take effect. If not set uses current server + time. Updates will be applied to the + SecurityMarks that are active immediately + preceding this time. + """ + + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_marks.SecurityMarks, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + start_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-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py new file mode 100644 index 000000000000..53b3d04fda40 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'Source', + }, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, etc. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and + outdated/insecure libraries.". + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}", + "folders/{folder_id}/sources/{source_id}" or + "projects/{project_number}/sources/{source_id}", depending + on the closest CRM ancestor of the resource associated with + the finding. + """ + + 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, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=14, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/noxfile.py new file mode 100644 index 000000000000..32b130e85f33 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-securitycenter' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +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"): + 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/securitycenter_v1p1beta1/', + '--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"): + 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", + "grpcio", + "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/securitycenter_v1p1beta1/', + '--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( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): + # Ignore release of mypy 1.11.0 which may have a regression + 'mypy!=1.11.0', + '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-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_async.py new file mode 100644 index 000000000000..9609719bb2ab --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_create_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py new file mode 100644 index 000000000000..a908f103062d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_create_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py new file mode 100644 index 000000000000..ce18ebfeab2a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_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 CreateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_create_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py new file mode 100644 index 000000000000..ec4621a56f92 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_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 CreateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_create_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_async.py new file mode 100644 index 000000000000..a05525b26ae5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_create_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_sync.py new file mode 100644 index 000000000000..53a2606db659 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_create_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py new file mode 100644 index 000000000000..77696925a3b2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_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 DeleteNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py new file mode 100644 index 000000000000..697bd5dc58b7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_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 DeleteNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_delete_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py new file mode 100644 index 000000000000..0143835b3615 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py new file mode 100644 index 000000000000..fc6a2f9ecd38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py new file mode 100644 index 000000000000..beffb7197acc --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_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 GetNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_get_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py new file mode 100644 index 000000000000..e0bf761c0629 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_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 GetNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_get_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py new file mode 100644 index 000000000000..25b7d03ebdb4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_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 GetOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py new file mode 100644 index 000000000000..94cd60452455 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_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 GetOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_get_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_async.py new file mode 100644 index 000000000000..1210ba0c3e4e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_get_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_sync.py new file mode 100644 index 000000000000..942cc4b79272 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_get_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_async.py new file mode 100644 index 000000000000..a487bea8e359 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_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 GroupAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_group_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py new file mode 100644 index 000000000000..c99f19c6389b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_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 GroupAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_group_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupAssetsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_async.py new file mode 100644 index 000000000000..3f65d770b14b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_group_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py new file mode 100644 index 000000000000..f70d29e29a1d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_group_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_async.py new file mode 100644 index 000000000000..55dec3edae30 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_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 ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_list_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py new file mode 100644 index 000000000000..150f9240dedb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_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 ListAssets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_list_assets(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_async.py new file mode 100644 index 000000000000..6b7785c3b4f1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_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 securitycenter_v1p1beta1 + + +async def sample_list_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py new file mode 100644 index 000000000000..5a8b07c8466d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_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 securitycenter_v1p1beta1 + + +def sample_list_findings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py new file mode 100644 index 000000000000..41cdb54d0669 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_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 ListNotificationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py new file mode 100644 index 000000000000..8d8286a62581 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_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 ListNotificationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_list_notification_configs(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_async.py new file mode 100644 index 000000000000..261f3b9fcb73 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_list_sources(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py new file mode 100644 index 000000000000..847e73dd0797 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_list_sources(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py new file mode 100644 index 000000000000..47e5c5bb61d7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py new file mode 100644 index 000000000000..fa965b321439 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_run_asset_discovery(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( + parent="parent_value", + ) + + # Make the request + operation = client.run_asset_discovery(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py new file mode 100644 index 000000000000..4d10d033f247 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_set_finding_state(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py new file mode 100644 index 000000000000..a77fb9ce8347 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_set_finding_state(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py new file mode 100644 index 000000000000..3cd28543769f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py new file mode 100644 index 000000000000..29ba6d93636e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py new file mode 100644 index 000000000000..8b663d640a2f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py new file mode 100644 index 000000000000..b484fc5c8e69 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_async.py new file mode 100644 index 000000000000..6fbcfd65b541 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_update_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py new file mode 100644 index 000000000000..11a3b6e7fac8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_update_finding(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py new file mode 100644 index 000000000000..cc60d07059d3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_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 UpdateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_update_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py new file mode 100644 index 000000000000..1ad9f8ee9c1c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_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 UpdateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_update_notification_config(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py new file mode 100644 index 000000000000..962efe30b0e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = await client.update_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py new file mode 100644 index 000000000000..007047607a2f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_update_organization_settings(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( + ) + + # Make the request + response = client.update_organization_settings(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py new file mode 100644 index 000000000000..6f9484b9d009 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_update_security_marks(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py new file mode 100644 index 000000000000..091847a4ef33 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_update_security_marks(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_async.py new file mode 100644 index 000000000000..559623a451be --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +async def sample_update_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_sync.py new file mode 100644 index 000000000000..5f72d8dd2b64 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v1p1beta1 + + +def sample_update_source(): + # Create a client + client = securitycenter_v1p1beta1.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v1p1beta1.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json new file mode 100644 index 000000000000..774592ce11f7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json @@ -0,0 +1,3808 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.securitycenter.v1p1beta1", + "version": "v1p1beta1" + } + ], + "language": "PYTHON", + "name": "google-cloud-securitycenter", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v1p1beta1_generated_security_center_create_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1p1beta1_generated_security_center_create_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "config_id", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "config_id", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1p1beta1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v1p1beta1_generated_security_center_create_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_create_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1p1beta1.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v1p1beta1_generated_security_center_create_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_create_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest" + }, + { + "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_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest" + }, + { + "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_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v1p1beta1.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v1p1beta1.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest" + }, + { + "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.securitycenter_v1p1beta1.types.OrganizationSettings", + "shortName": "get_organization_settings" + }, + "description": "Sample for GetOrganizationSettings", + "file": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest" + }, + { + "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.securitycenter_v1p1beta1.types.OrganizationSettings", + "shortName": "get_organization_settings" + }, + "description": "Sample for GetOrganizationSettings", + "file": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest" + }, + { + "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.securitycenter_v1p1beta1.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v1p1beta1_generated_security_center_get_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest" + }, + { + "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.securitycenter_v1p1beta1.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v1p1beta1_generated_security_center_get_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_get_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.group_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsAsyncPager", + "shortName": "group_assets" + }, + "description": "Sample for GroupAssets", + "file": "securitycenter_v1p1beta1_generated_security_center_group_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1p1beta1_generated_security_center_group_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.group_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsPager", + "shortName": "group_assets" + }, + "description": "Sample for GroupAssets", + "file": "securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsAsyncPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v1p1beta1_generated_security_center_group_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1p1beta1_generated_security_center_group_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsAsyncPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "securitycenter_v1p1beta1_generated_security_center_list_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1p1beta1_generated_security_center_list_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_assets", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListAssets", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsAsyncPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v1p1beta1_generated_security_center_list_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1p1beta1_generated_security_center_list_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsAsyncPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesAsyncPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v1p1beta1_generated_security_center_list_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1p1beta1_generated_security_center_list_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest" + }, + { + "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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.run_asset_discovery", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.RunAssetDiscovery", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "RunAssetDiscovery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "run_asset_discovery" + }, + "description": "Sample for RunAssetDiscovery", + "file": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.run_asset_discovery", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.RunAssetDiscovery", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "RunAssetDiscovery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "run_asset_discovery" + }, + "description": "Sample for RunAssetDiscovery", + "file": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v1p1beta1.types.Finding.State" + }, + { + "name": "start_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v1p1beta1.types.Finding.State" + }, + { + "name": "start_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" + }, + { + "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.securitycenter_v1p1beta1.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v1p1beta1_generated_security_center_update_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1p1beta1_generated_security_center_update_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" + }, + { + "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.securitycenter_v1p1beta1.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" + }, + { + "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.securitycenter_v1p1beta1.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" + }, + { + "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.securitycenter_v1p1beta1.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest" + }, + { + "name": "organization_settings", + "type": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings", + "shortName": "update_organization_settings" + }, + "description": "Sample for UpdateOrganizationSettings", + "file": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_organization_settings", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateOrganizationSettings", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateOrganizationSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest" + }, + { + "name": "organization_settings", + "type": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings", + "shortName": "update_organization_settings" + }, + "description": "Sample for UpdateOrganizationSettings", + "file": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v1p1beta1.types.SecurityMarks" + }, + { + "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.securitycenter_v1p1beta1.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v1p1beta1.types.SecurityMarks" + }, + { + "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.securitycenter_v1p1beta1.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1p1beta1.types.Source" + }, + { + "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.securitycenter_v1p1beta1.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v1p1beta1_generated_security_center_update_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1p1beta1_generated_security_center_update_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v1p1beta1.types.Source" + }, + { + "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.securitycenter_v1p1beta1.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v1p1beta1_generated_security_center_update_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1p1beta1_generated_security_center_update_source_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py new file mode 100644 index 000000000000..51a5e411dcfb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py @@ -0,0 +1,198 @@ +#! /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 securitycenterCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_notification_config': ('parent', 'config_id', 'notification_config', ), + 'create_source': ('parent', 'source', ), + 'delete_notification_config': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_notification_config': ('name', ), + 'get_organization_settings': ('name', ), + 'get_source': ('name', ), + 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), + 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), + 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_notification_configs': ('parent', 'page_token', 'page_size', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'run_asset_discovery': ('parent', ), + 'set_finding_state': ('name', 'state', 'start_time', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_notification_config': ('notification_config', 'update_mask', ), + 'update_organization_settings': ('organization_settings', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), + 'update_source': ('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=securitycenterCallTransformer(), +): + """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 securitycenter 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-securitycenter/v1p1beta1/setup.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/setup.py new file mode 100644 index 000000000000..c4538ec101f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/setup.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. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-securitycenter' + + +description = "Google Cloud Securitycenter API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/securitycenter/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", + "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", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__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-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py new file mode 100644 index 000000000000..8de42633a7ea --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py @@ -0,0 +1,18405 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +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 + +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.securitycenter_v1p1beta1.services.security_center import SecurityCenterAsyncClient +from google.cloud.securitycenter_v1p1beta1.services.security_center import SecurityCenterClient +from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1p1beta1.services.security_center import transports +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1p1beta1.types import security_marks +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +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 duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None + assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SecurityCenterClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SecurityCenterGrpcTransport, "grpc"), + (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + 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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + available_transports = [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterRestTransport, + ] + assert transport in available_transports + + transport = SecurityCenterClient.get_transport_class("grpc") + assert transport == transports.SecurityCenterGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, 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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), +]) +def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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_security_center_client_client_options_from_dict(): + with mock.patch('google.cloud.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_create_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object + + request = {} + await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_create_source_async_from_dict(): + await test_create_source_async(request_type=dict) + + +def test_create_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.create_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.create_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + + +def test_create_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + response = client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +def test_create_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.create_finding] = mock_rpc + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object + + request = {} + await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_create_finding_async_from_dict(): + await test_create_finding_async(request_type=dict) + + +def test_create_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + arg = args[0].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + + +def test_create_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + arg = args[0].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateNotificationConfigRequest, + dict, +]) +def test_create_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_create_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateNotificationConfigRequest( + parent='parent_value', + config_id='config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest( + parent='parent_value', + config_id='config_id_value', + ) + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_create_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_notification_config] = mock_object + + request = {} + await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_create_notification_config_async_from_dict(): + await test_create_notification_config_async(request_type=dict) + + +def test_create_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.create_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.create_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_notification_config( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + # Establish that the 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].config_id + mock_val = 'config_id_value' + assert arg == mock_val + arg = args[0].notification_config + mock_val = gcs_notification_config.NotificationConfig(name='name_value') + assert arg == mock_val + + +def test_create_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_notification_config( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + # Establish that 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].config_id + mock_val = 'config_id_value' + assert arg == mock_val + arg = args[0].notification_config + mock_val = gcs_notification_config.NotificationConfig(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_notification_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, +]) +def test_delete_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteNotificationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest( + name='name_value', + ) + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_delete_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_notification_config] = mock_object + + request = {} + await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteNotificationConfigRequest() + 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_config_async_from_dict(): + await test_delete_notification_config_async(request_type=dict) + + +def test_delete_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = None + client.delete_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_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_notification_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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_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_notification_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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_notification_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.GetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest( + resource='resource_value', + ) + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object + + request = {} + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetNotificationConfigRequest, + dict, +]) +def test_get_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_get_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetNotificationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest( + name='name_value', + ) + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_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_notification_config] = mock_rpc + request = {} + client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_get_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_notification_config] = mock_object + + request = {} + await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_get_notification_config_async_from_dict(): + await test_get_notification_config_async(request_type=dict) + + +def test_get_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = notification_config.NotificationConfig() + client.get_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + await client.get_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_notification_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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_notification_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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_notification_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetOrganizationSettingsRequest, + dict, +]) +def test_get_organization_settings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_get_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetOrganizationSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_organization_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest( + name='name_value', + ) + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_organization_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_organization_settings] = mock_rpc + request = {} + client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_organization_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_organization_settings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + +@pytest.mark.asyncio +async def test_get_organization_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_organization_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_organization_settings] = mock_object + + request = {} + await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_organization_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_get_organization_settings_async_from_dict(): + await test_get_organization_settings_async(request_type=dict) + + +def test_get_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = organization_settings.OrganizationSettings() + client.get_organization_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_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + await client.get_organization_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_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_organization_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_organization_settings_flattened_error(): + client = SecurityCenterClient( + credentials=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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_organization_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_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_get_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest( + name='name_value', + ) + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + +@pytest.mark.asyncio +async def test_get_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object + + request = {} + await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_get_source_async_from_dict(): + await test_get_source_async(request_type=dict) + + +def test_get_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = source.Source() + client.get_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + await client.get_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_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_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupAssetsRequest, + dict, +]) +def test_group_assets(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_assets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + +def test_group_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupAssetsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc + request = {} + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_group_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + +@pytest.mark.asyncio +async def test_group_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_assets] = mock_object + + request = {} + await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_assets_async_from_dict(): + await test_group_assets_async(request_type=dict) + + +def test_group_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = securitycenter_service.GroupAssetsResponse() + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_group_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) + await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_group_assets_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_assets(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, securitycenter_service.GroupResult) + for i in results) +def test_group_assets_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_assets(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_group_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_assets(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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_assets(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", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + +@pytest.mark.asyncio +async def test_group_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_findings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object + + request = {} + await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_findings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_findings_async_from_dict(): + await test_group_findings_async(request_type=dict) + + +def test_group_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = securitycenter_service.GroupFindingsResponse() + client.group_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_group_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + await client.group_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_group_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that the 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + + +def test_group_findings_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + +@pytest.mark.asyncio +async def test_group_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_group_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_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, securitycenter_service.GroupResult) + for i in results) +def test_group_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_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_group_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_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", [ + securitycenter_service.ListAssetsRequest, + dict, +]) +def test_list_assets(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_assets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + +def test_list_assets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListAssetsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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_assets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_assets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_value', + page_token='page_token_value', + ) + +def test_list_assets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + +@pytest.mark.asyncio +async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_assets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object + + request = {} + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAssetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + + +def test_list_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = securitycenter_service.ListAssetsResponse() + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_assets_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_assets( + 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_assets_flattened_error(): + client = SecurityCenterClient( + credentials=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_assets( + securitycenter_service.ListAssetsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_assets_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_assets( + 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_assets_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_assets( + securitycenter_service.ListAssetsRequest(), + parent='parent_value', + ) + + +def test_list_assets_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) +def test_list_assets_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(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_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + 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_assets(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", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +def test_list_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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] == securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + +@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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object + + request = {} + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +@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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( + 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 = securitycenter_service.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', + ) + + # Establish that the 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_findings_flattened_error(): + client = SecurityCenterClient( + credentials=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( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_findings_flattened_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.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', + ) + + # Establish that 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_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_findings( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + + +def test_list_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in results) +def test_list_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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 = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_findings_async_pages(): + client = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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", [ + securitycenter_service.ListNotificationConfigsRequest, + dict, +]) +def test_list_notification_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListNotificationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_notification_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListNotificationConfigsRequest( + 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_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notification_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_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_notification_configs] = mock_rpc + request = {} + client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_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_notification_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + +@pytest.mark.asyncio +async def test_list_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_notification_configs] = mock_object + + request = {} + await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_notification_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListNotificationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_from_dict(): + await test_list_notification_configs_async(request_type=dict) + + +def test_list_notification_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + 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_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + client.list_notification_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_notification_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + 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_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + await client.list_notification_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_notification_configs_flattened(): + client = SecurityCenterClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_notification_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_notification_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_notification_configs_flattened_async(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_notification_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_notification_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_notification_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + 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_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, notification_config.NotificationConfig) + for i in results) +def test_list_notification_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_notification_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_notification_configs_async_pager(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_notification_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, notification_config.NotificationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_pages(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + 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_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", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListSourcesRequest( + 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_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + +@pytest.mark.asyncio +async def test_list_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_sources in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object + + request = {} + await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_sources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sources_async_from_dict(): + await test_list_sources_async(request_type=dict) + + +def test_list_sources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = securitycenter_service.ListSourcesResponse() + client.list_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_sources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + await client.list_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_sources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_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_sources_flattened_error(): + client = SecurityCenterClient( + credentials=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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_sources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_sources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_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, source.Source) + for i in results) +def test_list_sources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = list(client.list_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_sources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_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, source.Source) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_sources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + 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_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", [ + securitycenter_service.RunAssetDiscoveryRequest, + dict, +]) +def test_run_asset_discovery(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.RunAssetDiscoveryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_asset_discovery_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + +def test_run_asset_discovery_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.RunAssetDiscoveryRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_asset_discovery(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest( + parent='parent_value', + ) + +def test_run_asset_discovery_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_asset_discovery in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc + request = {} + client.run_asset_discovery(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.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_run_asset_discovery_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + +@pytest.mark.asyncio +async def test_run_asset_discovery_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.run_asset_discovery in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.run_asset_discovery] = mock_object + + request = {} + await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.RunAssetDiscoveryRequest() + 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_run_asset_discovery_async_from_dict(): + await test_run_asset_discovery_async(request_type=dict) + + +def test_run_asset_discovery_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_asset_discovery_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_run_asset_discovery_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery( + 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_run_asset_discovery_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_run_asset_discovery_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__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.run_asset_discovery( + 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_run_asset_discovery_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + response = client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +def test_set_finding_state_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + +@pytest.mark.asyncio +async def test_set_finding_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object + + request = {} + await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_finding_state(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_set_finding_state_async_from_dict(): + await test_set_finding_state_async(request_type=dict) + + +def test_set_finding_state_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = finding.Finding() + client.set_finding_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_set_finding_state_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_finding_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_set_finding_state_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.SetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest( + resource='resource_value', + ) + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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( + version=774, + etag=b'etag_blob', + )) + response = await client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object + + request = {} + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = SecurityCenterClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.TestIamPermissionsRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( + resource='resource_value', + ) + +def test_test_iam_permissions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object + + request = {} + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + response = client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +def test_update_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateFindingRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.update_finding] = mock_rpc + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object + + request = {} + await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_finding_async_from_dict(): + await test_update_finding_async(request_type=dict) + + +def test_update_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +def test_update_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_finding( + finding=gcs_finding.Finding(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].finding + mock_val = gcs_finding.Finding(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_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_finding( + finding=gcs_finding.Finding(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].finding + mock_val = gcs_finding.Finding(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_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, +]) +def test_update_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_update_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateNotificationConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest( + ) + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_update_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_notification_config] = mock_object + + request = {} + await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_update_notification_config_async_from_dict(): + await test_update_notification_config_async(request_type=dict) + + +def test_update_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.update_notification_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', + 'notification_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.update_notification_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', + 'notification_config.name=name_value', + ) in kw['metadata'] + + +def test_update_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_notification_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateOrganizationSettingsRequest, + dict, +]) +def test_update_organization_settings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_update_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateOrganizationSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_organization_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest( + ) + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_organization_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_organization_settings] = mock_rpc + request = {} + client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_organization_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_organization_settings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + +@pytest.mark.asyncio +async def test_update_organization_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_organization_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_organization_settings] = mock_object + + request = {} + await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_organization_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateOrganizationSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_update_organization_settings_async_from_dict(): + await test_update_organization_settings_async(request_type=dict) + + +def test_update_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = gcs_organization_settings.OrganizationSettings() + client.update_organization_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', + 'organization_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + await client.update_organization_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', + 'organization_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].organization_settings + mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') + assert arg == mock_val + + +def test_update_organization_settings_flattened_error(): + client = SecurityCenterClient( + credentials=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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].organization_settings + mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSourceRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object + + request = {} + await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_source_async_from_dict(): + await test_update_source_async(request_type=dict) + + +def test_update_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +def test_update_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_source( + source=gcs_source.Source(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].source + mock_val = gcs_source.Source(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_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_source( + source=gcs_source.Source(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].source + mock_val = gcs_source.Source(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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + response = client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_security_marks_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + +def test_update_security_marks_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSecurityMarksRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( + ) + +def test_update_security_marks_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish that a new wrapper 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_security_marks_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + +@pytest.mark.asyncio +async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_marks in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object + + request = {} + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_security_marks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_security_marks_async_from_dict(): + await test_update_security_marks_async(request_type=dict) + + +def test_update_security_marks_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = gcs_security_marks.SecurityMarks() + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_marks_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +def test_update_security_marks_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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].security_marks + mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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].security_marks + mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.CreateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_source(request) + + +def test_create_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1p1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_create_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +def test_create_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request_init["finding"] = {'name': 'name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.create_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.create_finding] = mock_rpc + + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["finding_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 "findingId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "findingId" in jsonified_request + assert jsonified_request["findingId"] == request_init["finding_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["findingId"] = 'finding_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request + assert jsonified_request["findingId"] == 'finding_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.create_finding(request) + + expected_params = [ + ( + "findingId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.CreateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_finding(request) + + +def test_create_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(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 = gcs_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.create_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/v1p1beta1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) + + +def test_create_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_create_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateNotificationConfigRequest, + dict, +]) +def test_create_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["notification_config"] = {'name': 'name_value', 'description': 'description_value', 'event_type': 1, 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.CreateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.CreateNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["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 "configId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "configId" in jsonified_request + assert jsonified_request["configId"] == request_init["config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["configId"] = 'config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("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 "configId" in jsonified_request + assert jsonified_request["configId"] == 'config_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ( + "configId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("configId", )) & set(("parent", "configId", "notificationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateNotificationConfigRequest.pb(securitycenter_service.CreateNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) + + request = securitycenter_service.CreateNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.create_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_notification_config(request) + + +def test_create_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/v1p1beta1/{parent=organizations/*}/notificationConfigs" % client.transport._host, args[1]) + + +def test_create_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + +def test_create_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, +]) +def test_delete_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/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 = 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_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.DeleteNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_notification_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteNotificationConfigRequest.pb(securitycenter_service.DeleteNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_notification_config(request) + + +def test_delete_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/notificationConfigs/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_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/v1p1beta1/{name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +def test_delete_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.get_iam_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/v1p1beta1/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetNotificationConfigRequest, + dict, +]) +def test_get_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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_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_notification_config] = mock_rpc + + request = {} + client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.GetNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetNotificationConfigRequest.pb(securitycenter_service.GetNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = notification_config.NotificationConfig.to_json(notification_config.NotificationConfig()) + + request = securitycenter_service.GetNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = notification_config.NotificationConfig() + + client.get_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_notification_config(request) + + +def test_get_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig.pb(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_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/v1p1beta1/{name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_get_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +def test_get_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetOrganizationSettingsRequest, + dict, +]) +def test_get_organization_settings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/organizationSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + +def test_get_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_organization_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_organization_settings] = mock_rpc + + request = {} + client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.GetOrganizationSettingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_organization_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_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_organization_settings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_organization_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_organization_settings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_organization_settings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_organization_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetOrganizationSettingsRequest.pb(securitycenter_service.GetOrganizationSettingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = organization_settings.OrganizationSettings.to_json(organization_settings.OrganizationSettings()) + + request = securitycenter_service.GetOrganizationSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = organization_settings.OrganizationSettings() + + client.get_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/organizationSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_organization_settings(request) + + +def test_get_organization_settings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organization_settings.OrganizationSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/organizationSettings'} + + # get truthy value for each flattened field + mock_args = dict( + 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 = organization_settings.OrganizationSettings.pb(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_organization_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/v1p1beta1/{name=organizations/*/organizationSettings}" % client.transport._host, args[1]) + + +def test_get_organization_settings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +def test_get_organization_settings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/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 = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = source.Source.to_json(source.Source()) + + request = securitycenter_service.GetSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = source.Source() + + client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_source(request) + + +def test_get_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v1p1beta1/{name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_get_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +def test_get_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupAssetsRequest, + dict, +]) +def test_group_assets_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_group_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc + + request = {} + client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_assets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_group_assets_rest_required_fields(request_type=securitycenter_service.GroupAssetsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_assets_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_assets_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_assets") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupAssetsRequest.pb(securitycenter_service.GroupAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupAssetsResponse.to_json(securitycenter_service.GroupAssetsResponse()) + + request = securitycenter_service.GroupAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupAssetsResponse() + + client.group_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_assets(request) + + +def test_group_assets_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupAssetsResponse.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': 'organizations/sample1'} + + pager = client.group_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_findings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) + + request = securitycenter_service.GroupFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupFindingsResponse() + + client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_findings(request) + + +def test_group_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + group_by='group_by_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v1p1beta1/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) + + +def test_group_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} + + pager = client.group_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_findings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListAssetsRequest, + dict, +]) +def test_list_assets_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListAssetsResponse.pb(return_value) + 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_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_list_assets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_assets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc + + request = {} + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_assets(request) + + # Establish 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_assets_rest_required_fields(request_type=securitycenter_service.ListAssetsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_assets._get_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_assets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) + jsonified_request.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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAssetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListAssetsResponse.pb(return_value) + 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_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_assets_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_assets_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_assets") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListAssetsRequest.pb(securitycenter_service.ListAssetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListAssetsResponse.to_json(securitycenter_service.ListAssetsResponse()) + + request = securitycenter_service.ListAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListAssetsResponse() + + client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_assets(request) + + +def test_list_assets_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAssetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse.pb(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_assets(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1p1beta1/{parent=organizations/*}/assets" % client.transport._host, args[1]) + + +def test_list_assets_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_assets( + securitycenter_service.ListAssetsRequest(), + parent='parent_value', + ) + + +def test_list_assets_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListAssetsResponse.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': 'organizations/sample1'} + + pager = client.list_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) + + pages = list(client.list_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.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' + assert response.total_size == 1086 + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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=securitycenter_service.ListFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) + jsonified_request.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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.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 = securitycenter_service.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 = [ + ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) + + request = securitycenter_service.ListFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListFindingsResponse() + + client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_findings(request) + + +def test_list_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.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/v1p1beta1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) + + +def test_list_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + + +def test_list_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} + + pager = client.list_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) + 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 + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListNotificationConfigsRequest, + dict, +]) +def test_list_notification_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) + 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_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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_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_notification_configs] = mock_rpc + + request = {} + client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_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_notification_configs_rest_required_fields(request_type=securitycenter_service.ListNotificationConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListNotificationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) + 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_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_notification_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_notification_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_notification_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_notification_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_notification_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListNotificationConfigsRequest.pb(securitycenter_service.ListNotificationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListNotificationConfigsResponse.to_json(securitycenter_service.ListNotificationConfigsResponse()) + + request = securitycenter_service.ListNotificationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListNotificationConfigsResponse() + + client.list_notification_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_notification_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_notification_configs(request) + + +def test_list_notification_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListNotificationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse.pb(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_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/v1p1beta1/{parent=organizations/*}/notificationConfigs" % client.transport._host, args[1]) + + +def test_list_notification_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListNotificationConfigsResponse.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': 'organizations/sample1'} + + pager = client.list_notification_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, notification_config.NotificationConfig) + for i in results) + + pages = list(client.list_notification_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_sources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_sources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) + + request = securitycenter_service.ListSourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListSourcesResponse() + + client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_sources(request) + + +def test_list_sources_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v1p1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_list_sources_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} + + pager = client.list_sources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, source.Source) + for i in results) + + pages = list(client.list_sources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.RunAssetDiscoveryRequest, + dict, +]) +def test_run_asset_discovery_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') + + # 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 + response = client.run_asset_discovery(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_run_asset_discovery_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_asset_discovery in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc + + request = {} + client.run_asset_discovery(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.run_asset_discovery(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_run_asset_discovery_rest_required_fields(request_type=securitycenter_service.RunAssetDiscoveryRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_asset_discovery._get_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()).run_asset_discovery._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 = SecurityCenterClient( + 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.run_asset_discovery(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_run_asset_discovery_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.run_asset_discovery._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_asset_discovery_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_run_asset_discovery") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_run_asset_discovery") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.RunAssetDiscoveryRequest.pb(securitycenter_service.RunAssetDiscoveryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = securitycenter_service.RunAssetDiscoveryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.run_asset_discovery(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_asset_discovery_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.run_asset_discovery(request) + + +def test_run_asset_discovery_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.run_asset_discovery(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1p1beta1/{parent=organizations/*}/assets:runDiscovery" % client.transport._host, args[1]) + + +def test_run_asset_discovery_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +def test_run_asset_discovery_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + + # 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 + response = client.set_finding_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( + 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': "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 = 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.set_finding_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_finding_state_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_finding_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "state", "startTime", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_finding_state_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetFindingStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_finding_state(request) + + +def test_set_finding_state_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + mock_args.update(sample_request) + + # 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.set_finding_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/v1p1beta1/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) + + +def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +def test_set_finding_state_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.set_iam_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/v1p1beta1/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # 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 + response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_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.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1p1beta1/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.update_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.update_finding] = mock_rpc + + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_finding._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_finding._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.update_finding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.UpdateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_finding(request) + + +def test_update_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + finding=gcs_finding.Finding(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 = gcs_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.update_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/v1p1beta1/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) + + +def test_update_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, +]) +def test_update_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} + request_init["notification_config"] = {'name': 'organizations/sample1/notificationConfigs/sample2', 'description': 'description_value', 'event_type': 1, 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.UpdateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.UpdateNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("notificationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateNotificationConfigRequest.pb(securitycenter_service.UpdateNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) + + request = securitycenter_service.UpdateNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.update_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_notification_config(request) + + +def test_update_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/v1p1beta1/{notification_config.name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_update_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateOrganizationSettingsRequest, + dict, +]) +def test_update_organization_settings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + request_init["organization_settings"] = {'name': 'organizations/sample1/organizationSettings', 'enable_asset_discovery': True, 'asset_discovery_config': {'project_ids': ['project_ids_value1', 'project_ids_value2'], 'inclusion_mode': 1, 'folder_ids': ['folder_ids_value1', 'folder_ids_value2']}} + # The version of a generated dependency at test runtime may differ from the version used 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 = securitycenter_service.UpdateOrganizationSettingsRequest.meta.fields["organization_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["organization_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["organization_settings"][field])): + del request_init["organization_settings"][field][i][subfield] + else: + del request_init["organization_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 = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + +def test_update_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_organization_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_organization_settings] = mock_rpc + + request = {} + client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_organization_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_organization_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_organization_settings.OrganizationSettings() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_organization_settings.OrganizationSettings.pb(return_value) + 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_organization_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_organization_settings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_organization_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("organizationSettings", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_organization_settings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_organization_settings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_organization_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateOrganizationSettingsRequest.pb(securitycenter_service.UpdateOrganizationSettingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_organization_settings.OrganizationSettings.to_json(gcs_organization_settings.OrganizationSettings()) + + request = securitycenter_service.UpdateOrganizationSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_organization_settings.OrganizationSettings() + + client.update_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_organization_settings(request) + + +def test_update_organization_settings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_organization_settings.OrganizationSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + organization_settings=gcs_organization_settings.OrganizationSettings(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 = gcs_organization_settings.OrganizationSettings.pb(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_organization_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/v1p1beta1/{organization_settings.name=organizations/*/organizationSettings}" % client.transport._host, args[1]) + + +def test_update_organization_settings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +def test_update_organization_settings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.UpdateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_source(request) + + +def test_update_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1p1beta1/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_update_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + request_init["security_marks"] = {'name': 'organizations/sample1/assets/sample2/securityMarks', 'marks': {}, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] + + 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["security_marks"].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["security_marks"][field])): + del request_init["security_marks"][field][i][subfield] + else: + del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + +def test_update_security_marks_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_security_marks._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_security_marks._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("start_time", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_security_marks_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_security_marks._get_unset_required_fields({}) + assert set(unset_fields) == (set(("startTime", "updateMask", )) & set(("securityMarks", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_security_marks_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) + + request = securitycenter_service.UpdateSecurityMarksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_security_marks.SecurityMarks() + + client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_security_marks(request) + + +def test_update_security_marks_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + + # get arguments that satisfy an http rule for this method + sample_request = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} + + # get truthy value for each flattened field + mock_args = dict( + security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1p1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}" % client.transport._host, args[1]) + + +def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_security_marks_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SecurityCenterClient( + 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 = SecurityCenterClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecurityCenterClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, +]) +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() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SecurityCenterClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecurityCenterGrpcTransport, + ) + +def test_security_center_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_security_center_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_source', + 'create_finding', + 'create_notification_config', + 'delete_notification_config', + 'get_iam_policy', + 'get_notification_config', + 'get_organization_settings', + 'get_source', + 'group_assets', + 'group_findings', + 'list_assets', + 'list_findings', + 'list_notification_configs', + 'list_sources', + 'run_asset_discovery', + 'set_finding_state', + 'set_iam_policy', + 'test_iam_permissions', + 'update_finding', + 'update_notification_config', + 'update_organization_settings', + 'update_source', + 'update_security_marks', + ) + 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_security_center_base_transport_with_credentials_file(): + # Instantiate the 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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + 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_security_center_base_transport_with_adc(): + # Test the default 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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +def test_security_center_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) + SecurityCenterClient() + 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_transport_auth_adc(transport_class): + # If 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, + ], +) +def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_security_center_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host 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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_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.SecurityCenterRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_security_center_rest_lro_client(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a 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 + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_no_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_with_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_security_center_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SecurityCenterClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SecurityCenterClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_source._session + session2 = client2.transport.create_source._session + assert session1 != session2 + session1 = client1.transport.create_finding._session + session2 = client2.transport.create_finding._session + assert session1 != session2 + session1 = client1.transport.create_notification_config._session + session2 = client2.transport.create_notification_config._session + assert session1 != session2 + session1 = client1.transport.delete_notification_config._session + session2 = client2.transport.delete_notification_config._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.get_notification_config._session + session2 = client2.transport.get_notification_config._session + assert session1 != session2 + session1 = client1.transport.get_organization_settings._session + session2 = client2.transport.get_organization_settings._session + assert session1 != session2 + session1 = client1.transport.get_source._session + session2 = client2.transport.get_source._session + assert session1 != session2 + session1 = client1.transport.group_assets._session + session2 = client2.transport.group_assets._session + assert session1 != session2 + session1 = client1.transport.group_findings._session + session2 = client2.transport.group_findings._session + assert session1 != session2 + session1 = client1.transport.list_assets._session + session2 = client2.transport.list_assets._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_notification_configs._session + session2 = client2.transport.list_notification_configs._session + assert session1 != session2 + session1 = client1.transport.list_sources._session + session2 = client2.transport.list_sources._session + assert session1 != session2 + session1 = client1.transport.run_asset_discovery._session + session2 = client2.transport.run_asset_discovery._session + assert session1 != session2 + session1 = client1.transport.set_finding_state._session + session2 = client2.transport.set_finding_state._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 + session1 = client1.transport.update_finding._session + session2 = client2.transport.update_finding._session + assert session1 != session2 + session1 = client1.transport.update_notification_config._session + session2 = client2.transport.update_notification_config._session + assert session1 != session2 + session1 = client1.transport.update_organization_settings._session + session2 = client2.transport.update_organization_settings._session + assert session1 != session2 + session1 = client1.transport.update_source._session + session2 = client2.transport.update_source._session + assert session1 != session2 + session1 = client1.transport.update_security_marks._session + session2 = client2.transport.update_security_marks._session + assert session1 != session2 +def test_security_center_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcTransport( + 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_security_center_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcAsyncIOTransport( + 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(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_security_center_grpc_lro_client(): + client = SecurityCenterClient( + 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_security_center_grpc_lro_async_client(): + client = SecurityCenterAsyncClient( + 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_asset_path(): + organization = "squid" + asset = "clam" + expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.asset_path(organization, asset) + assert expected == actual + + +def test_parse_asset_path(): + expected = { + "organization": "whelk", + "asset": "octopus", + } + path = SecurityCenterClient.asset_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_asset_path(path) + assert expected == actual + +def test_finding_path(): + organization = "oyster" + source = "nudibranch" + finding = "cuttlefish" + expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + actual = SecurityCenterClient.finding_path(organization, source, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "organization": "mussel", + "source": "winkle", + "finding": "nautilus", + } + path = SecurityCenterClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_finding_path(path) + assert expected == actual + +def test_notification_config_path(): + organization = "scallop" + notification_config = "abalone" + expected = "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) + actual = SecurityCenterClient.notification_config_path(organization, notification_config) + assert expected == actual + + +def test_parse_notification_config_path(): + expected = { + "organization": "squid", + "notification_config": "clam", + } + path = SecurityCenterClient.notification_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_notification_config_path(path) + assert expected == actual + +def test_organization_settings_path(): + organization = "whelk" + expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) + actual = SecurityCenterClient.organization_settings_path(organization) + assert expected == actual + + +def test_parse_organization_settings_path(): + expected = { + "organization": "octopus", + } + path = SecurityCenterClient.organization_settings_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_organization_settings_path(path) + assert expected == actual + +def test_security_marks_path(): + organization = "oyster" + asset = "nudibranch" + expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.security_marks_path(organization, asset) + assert expected == actual + + +def test_parse_security_marks_path(): + expected = { + "organization": "cuttlefish", + "asset": "mussel", + } + path = SecurityCenterClient.security_marks_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_marks_path(path) + assert expected == actual + +def test_source_path(): + organization = "winkle" + source = "nautilus" + expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + actual = SecurityCenterClient.source_path(organization, source) + assert expected == actual + + +def test_parse_source_path(): + expected = { + "organization": "scallop", + "source": "abalone", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_path(path) + assert expected == actual + +def test_topic_path(): + project = "squid" + topic = "clam" + expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + actual = SecurityCenterClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "whelk", + "topic": "octopus", + } + path = SecurityCenterClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_topic_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SecurityCenterClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = SecurityCenterClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = SecurityCenterClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = SecurityCenterClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SecurityCenterClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = SecurityCenterClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = SecurityCenterClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = SecurityCenterClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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 = SecurityCenterClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = SecurityCenterClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + transport_class = SecurityCenterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), +]) +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-securitycenter/v2/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v2/.coveragerc new file mode 100644 index 000000000000..45cb273f8f7c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/securitycenter/__init__.py + google/cloud/securitycenter/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-securitycenter/v2/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v2/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v2/MANIFEST.in new file mode 100644 index 000000000000..7d0a7010fae0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/securitycenter *.py +recursive-include google/cloud/securitycenter_v2 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/README.rst b/owl-bot-staging/google-cloud-securitycenter/v2/README.rst new file mode 100644 index 000000000000..f8c63f4cb48a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v2/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v2/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v2/docs/conf.py new file mode 100644 index 000000000000..8e92d2319721 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter 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-securitycenter" +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-securitycenter-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-securitycenter.tex", + u"google-cloud-securitycenter 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-securitycenter", + u"Google Cloud Securitycenter 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-securitycenter", + u"google-cloud-securitycenter Documentation", + author, + "google-cloud-securitycenter", + "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v2/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/index.rst new file mode 100644 index 000000000000..af3ca0f134f0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + securitycenter_v2/services + securitycenter_v2/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst new file mode 100644 index 000000000000..6b9d3b9b1795 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst @@ -0,0 +1,10 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v2.services.security_center + :members: + :inherited-members: + +.. automodule:: google.cloud.securitycenter_v2.services.security_center.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst new file mode 100644 index 000000000000..adb8a6096090 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v2 API +=============================================== +.. toctree:: + :maxdepth: 2 + + security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst new file mode 100644 index 000000000000..3210d372fb24 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Securitycenter v2 API +============================================ + +.. automodule:: google.cloud.securitycenter_v2.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py new file mode 100644 index 000000000000..121fb285646b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py @@ -0,0 +1,257 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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.securitycenter import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.securitycenter_v2.services.security_center.client import SecurityCenterClient +from google.cloud.securitycenter_v2.services.security_center.async_client import SecurityCenterAsyncClient + +from google.cloud.securitycenter_v2.types.access import Access +from google.cloud.securitycenter_v2.types.access import Geolocation +from google.cloud.securitycenter_v2.types.access import ServiceAccountDelegationInfo +from google.cloud.securitycenter_v2.types.application import Application +from google.cloud.securitycenter_v2.types.attack_exposure import AttackExposure +from google.cloud.securitycenter_v2.types.attack_path import AttackPath +from google.cloud.securitycenter_v2.types.backup_disaster_recovery import BackupDisasterRecovery +from google.cloud.securitycenter_v2.types.bigquery_export import BigQueryExport +from google.cloud.securitycenter_v2.types.cloud_armor import AdaptiveProtection +from google.cloud.securitycenter_v2.types.cloud_armor import Attack +from google.cloud.securitycenter_v2.types.cloud_armor import CloudArmor +from google.cloud.securitycenter_v2.types.cloud_armor import Requests +from google.cloud.securitycenter_v2.types.cloud_armor import SecurityPolicy +from google.cloud.securitycenter_v2.types.cloud_dlp_data_profile import CloudDlpDataProfile +from google.cloud.securitycenter_v2.types.cloud_dlp_inspection import CloudDlpInspection +from google.cloud.securitycenter_v2.types.compliance import Compliance +from google.cloud.securitycenter_v2.types.connection import Connection +from google.cloud.securitycenter_v2.types.contact_details import Contact +from google.cloud.securitycenter_v2.types.contact_details import ContactDetails +from google.cloud.securitycenter_v2.types.container import Container +from google.cloud.securitycenter_v2.types.database import Database +from google.cloud.securitycenter_v2.types.exfiltration import ExfilResource +from google.cloud.securitycenter_v2.types.exfiltration import Exfiltration +from google.cloud.securitycenter_v2.types.external_system import ExternalSystem +from google.cloud.securitycenter_v2.types.file import File +from google.cloud.securitycenter_v2.types.finding import Finding +from google.cloud.securitycenter_v2.types.folder import Folder +from google.cloud.securitycenter_v2.types.group_membership import GroupMembership +from google.cloud.securitycenter_v2.types.iam_binding import IamBinding +from google.cloud.securitycenter_v2.types.indicator import Indicator +from google.cloud.securitycenter_v2.types.kernel_rootkit import KernelRootkit +from google.cloud.securitycenter_v2.types.kubernetes import Kubernetes +from google.cloud.securitycenter_v2.types.label import Label +from google.cloud.securitycenter_v2.types.load_balancer import LoadBalancer +from google.cloud.securitycenter_v2.types.log_entry import CloudLoggingEntry +from google.cloud.securitycenter_v2.types.log_entry import LogEntry +from google.cloud.securitycenter_v2.types.mitre_attack import MitreAttack +from google.cloud.securitycenter_v2.types.mute_config import MuteConfig +from google.cloud.securitycenter_v2.types.notebook import Notebook +from google.cloud.securitycenter_v2.types.notification_config import NotificationConfig +from google.cloud.securitycenter_v2.types.notification_message import NotificationMessage +from google.cloud.securitycenter_v2.types.org_policy import OrgPolicy +from google.cloud.securitycenter_v2.types.process import EnvironmentVariable +from google.cloud.securitycenter_v2.types.process import Process +from google.cloud.securitycenter_v2.types.resource import AwsMetadata +from google.cloud.securitycenter_v2.types.resource import AzureMetadata +from google.cloud.securitycenter_v2.types.resource import GcpMetadata +from google.cloud.securitycenter_v2.types.resource import Resource +from google.cloud.securitycenter_v2.types.resource import ResourcePath +from google.cloud.securitycenter_v2.types.resource import CloudProvider +from google.cloud.securitycenter_v2.types.resource_value_config import ResourceValueConfig +from google.cloud.securitycenter_v2.types.resource_value_config import ResourceValue +from google.cloud.securitycenter_v2.types.security_marks import SecurityMarks +from google.cloud.securitycenter_v2.types.security_posture import SecurityPosture +from google.cloud.securitycenter_v2.types.securitycenter_service import BatchCreateResourceValueConfigsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import BatchCreateResourceValueConfigsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import BulkMuteFindingsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import BulkMuteFindingsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import CreateBigQueryExportRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import CreateFindingRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import CreateMuteConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import CreateNotificationConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import CreateResourceValueConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import CreateSourceRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteBigQueryExportRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteMuteConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteNotificationConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteResourceValueConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetBigQueryExportRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetMuteConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetNotificationConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetResourceValueConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetSimulationRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetSourceRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GetValuedResourceRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GroupFindingsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import GroupFindingsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import GroupResult +from google.cloud.securitycenter_v2.types.securitycenter_service import ListAttackPathsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListAttackPathsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListBigQueryExportsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListBigQueryExportsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListFindingsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListFindingsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListMuteConfigsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListMuteConfigsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListNotificationConfigsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListNotificationConfigsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListResourceValueConfigsRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListResourceValueConfigsResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListSourcesRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListSourcesResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import ListValuedResourcesRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import ListValuedResourcesResponse +from google.cloud.securitycenter_v2.types.securitycenter_service import SetFindingStateRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import SetMuteRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateBigQueryExportRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateExternalSystemRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateFindingRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateMuteConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateNotificationConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateResourceValueConfigRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateSecurityMarksRequest +from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateSourceRequest +from google.cloud.securitycenter_v2.types.simulation import Simulation +from google.cloud.securitycenter_v2.types.source import Source +from google.cloud.securitycenter_v2.types.toxic_combination import ToxicCombination +from google.cloud.securitycenter_v2.types.valued_resource import ResourceValueConfigMetadata +from google.cloud.securitycenter_v2.types.valued_resource import ValuedResource +from google.cloud.securitycenter_v2.types.vulnerability import Cve +from google.cloud.securitycenter_v2.types.vulnerability import Cvssv3 +from google.cloud.securitycenter_v2.types.vulnerability import Package +from google.cloud.securitycenter_v2.types.vulnerability import Reference +from google.cloud.securitycenter_v2.types.vulnerability import SecurityBulletin +from google.cloud.securitycenter_v2.types.vulnerability import Vulnerability + +__all__ = ('SecurityCenterClient', + 'SecurityCenterAsyncClient', + 'Access', + 'Geolocation', + 'ServiceAccountDelegationInfo', + 'Application', + 'AttackExposure', + 'AttackPath', + 'BackupDisasterRecovery', + 'BigQueryExport', + 'AdaptiveProtection', + 'Attack', + 'CloudArmor', + 'Requests', + 'SecurityPolicy', + 'CloudDlpDataProfile', + 'CloudDlpInspection', + 'Compliance', + 'Connection', + 'Contact', + 'ContactDetails', + 'Container', + 'Database', + 'ExfilResource', + 'Exfiltration', + 'ExternalSystem', + 'File', + 'Finding', + 'Folder', + 'GroupMembership', + 'IamBinding', + 'Indicator', + 'KernelRootkit', + 'Kubernetes', + 'Label', + 'LoadBalancer', + 'CloudLoggingEntry', + 'LogEntry', + 'MitreAttack', + 'MuteConfig', + 'Notebook', + 'NotificationConfig', + 'NotificationMessage', + 'OrgPolicy', + 'EnvironmentVariable', + 'Process', + 'AwsMetadata', + 'AzureMetadata', + 'GcpMetadata', + 'Resource', + 'ResourcePath', + 'CloudProvider', + 'ResourceValueConfig', + 'ResourceValue', + 'SecurityMarks', + 'SecurityPosture', + 'BatchCreateResourceValueConfigsRequest', + 'BatchCreateResourceValueConfigsResponse', + 'BulkMuteFindingsRequest', + 'BulkMuteFindingsResponse', + 'CreateBigQueryExportRequest', + 'CreateFindingRequest', + 'CreateMuteConfigRequest', + 'CreateNotificationConfigRequest', + 'CreateResourceValueConfigRequest', + 'CreateSourceRequest', + 'DeleteBigQueryExportRequest', + 'DeleteMuteConfigRequest', + 'DeleteNotificationConfigRequest', + 'DeleteResourceValueConfigRequest', + 'GetBigQueryExportRequest', + 'GetMuteConfigRequest', + 'GetNotificationConfigRequest', + 'GetResourceValueConfigRequest', + 'GetSimulationRequest', + 'GetSourceRequest', + 'GetValuedResourceRequest', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAttackPathsRequest', + 'ListAttackPathsResponse', + 'ListBigQueryExportsRequest', + 'ListBigQueryExportsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListMuteConfigsRequest', + 'ListMuteConfigsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListResourceValueConfigsRequest', + 'ListResourceValueConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListValuedResourcesRequest', + 'ListValuedResourcesResponse', + 'SetFindingStateRequest', + 'SetMuteRequest', + 'UpdateBigQueryExportRequest', + 'UpdateExternalSystemRequest', + 'UpdateFindingRequest', + 'UpdateMuteConfigRequest', + 'UpdateNotificationConfigRequest', + 'UpdateResourceValueConfigRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Simulation', + 'Source', + 'ToxicCombination', + 'ResourceValueConfigMetadata', + 'ValuedResource', + 'Cve', + 'Cvssv3', + 'Package', + 'Reference', + 'SecurityBulletin', + 'Vulnerability', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/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-securitycenter/v2/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py new file mode 100644 index 000000000000..f27bfdd5500f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py @@ -0,0 +1,258 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.securitycenter_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + +from .types.access import Access +from .types.access import Geolocation +from .types.access import ServiceAccountDelegationInfo +from .types.application import Application +from .types.attack_exposure import AttackExposure +from .types.attack_path import AttackPath +from .types.backup_disaster_recovery import BackupDisasterRecovery +from .types.bigquery_export import BigQueryExport +from .types.cloud_armor import AdaptiveProtection +from .types.cloud_armor import Attack +from .types.cloud_armor import CloudArmor +from .types.cloud_armor import Requests +from .types.cloud_armor import SecurityPolicy +from .types.cloud_dlp_data_profile import CloudDlpDataProfile +from .types.cloud_dlp_inspection import CloudDlpInspection +from .types.compliance import Compliance +from .types.connection import Connection +from .types.contact_details import Contact +from .types.contact_details import ContactDetails +from .types.container import Container +from .types.database import Database +from .types.exfiltration import ExfilResource +from .types.exfiltration import Exfiltration +from .types.external_system import ExternalSystem +from .types.file import File +from .types.finding import Finding +from .types.folder import Folder +from .types.group_membership import GroupMembership +from .types.iam_binding import IamBinding +from .types.indicator import Indicator +from .types.kernel_rootkit import KernelRootkit +from .types.kubernetes import Kubernetes +from .types.label import Label +from .types.load_balancer import LoadBalancer +from .types.log_entry import CloudLoggingEntry +from .types.log_entry import LogEntry +from .types.mitre_attack import MitreAttack +from .types.mute_config import MuteConfig +from .types.notebook import Notebook +from .types.notification_config import NotificationConfig +from .types.notification_message import NotificationMessage +from .types.org_policy import OrgPolicy +from .types.process import EnvironmentVariable +from .types.process import Process +from .types.resource import AwsMetadata +from .types.resource import AzureMetadata +from .types.resource import GcpMetadata +from .types.resource import Resource +from .types.resource import ResourcePath +from .types.resource import CloudProvider +from .types.resource_value_config import ResourceValueConfig +from .types.resource_value_config import ResourceValue +from .types.security_marks import SecurityMarks +from .types.security_posture import SecurityPosture +from .types.securitycenter_service import BatchCreateResourceValueConfigsRequest +from .types.securitycenter_service import BatchCreateResourceValueConfigsResponse +from .types.securitycenter_service import BulkMuteFindingsRequest +from .types.securitycenter_service import BulkMuteFindingsResponse +from .types.securitycenter_service import CreateBigQueryExportRequest +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateMuteConfigRequest +from .types.securitycenter_service import CreateNotificationConfigRequest +from .types.securitycenter_service import CreateResourceValueConfigRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import DeleteBigQueryExportRequest +from .types.securitycenter_service import DeleteMuteConfigRequest +from .types.securitycenter_service import DeleteNotificationConfigRequest +from .types.securitycenter_service import DeleteResourceValueConfigRequest +from .types.securitycenter_service import GetBigQueryExportRequest +from .types.securitycenter_service import GetMuteConfigRequest +from .types.securitycenter_service import GetNotificationConfigRequest +from .types.securitycenter_service import GetResourceValueConfigRequest +from .types.securitycenter_service import GetSimulationRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GetValuedResourceRequest +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAttackPathsRequest +from .types.securitycenter_service import ListAttackPathsResponse +from .types.securitycenter_service import ListBigQueryExportsRequest +from .types.securitycenter_service import ListBigQueryExportsResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListMuteConfigsRequest +from .types.securitycenter_service import ListMuteConfigsResponse +from .types.securitycenter_service import ListNotificationConfigsRequest +from .types.securitycenter_service import ListNotificationConfigsResponse +from .types.securitycenter_service import ListResourceValueConfigsRequest +from .types.securitycenter_service import ListResourceValueConfigsResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import ListValuedResourcesRequest +from .types.securitycenter_service import ListValuedResourcesResponse +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import SetMuteRequest +from .types.securitycenter_service import UpdateBigQueryExportRequest +from .types.securitycenter_service import UpdateExternalSystemRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateMuteConfigRequest +from .types.securitycenter_service import UpdateNotificationConfigRequest +from .types.securitycenter_service import UpdateResourceValueConfigRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.simulation import Simulation +from .types.source import Source +from .types.toxic_combination import ToxicCombination +from .types.valued_resource import ResourceValueConfigMetadata +from .types.valued_resource import ValuedResource +from .types.vulnerability import Cve +from .types.vulnerability import Cvssv3 +from .types.vulnerability import Package +from .types.vulnerability import Reference +from .types.vulnerability import SecurityBulletin +from .types.vulnerability import Vulnerability + +__all__ = ( + 'SecurityCenterAsyncClient', +'Access', +'AdaptiveProtection', +'Application', +'Attack', +'AttackExposure', +'AttackPath', +'AwsMetadata', +'AzureMetadata', +'BackupDisasterRecovery', +'BatchCreateResourceValueConfigsRequest', +'BatchCreateResourceValueConfigsResponse', +'BigQueryExport', +'BulkMuteFindingsRequest', +'BulkMuteFindingsResponse', +'CloudArmor', +'CloudDlpDataProfile', +'CloudDlpInspection', +'CloudLoggingEntry', +'CloudProvider', +'Compliance', +'Connection', +'Contact', +'ContactDetails', +'Container', +'CreateBigQueryExportRequest', +'CreateFindingRequest', +'CreateMuteConfigRequest', +'CreateNotificationConfigRequest', +'CreateResourceValueConfigRequest', +'CreateSourceRequest', +'Cve', +'Cvssv3', +'Database', +'DeleteBigQueryExportRequest', +'DeleteMuteConfigRequest', +'DeleteNotificationConfigRequest', +'DeleteResourceValueConfigRequest', +'EnvironmentVariable', +'ExfilResource', +'Exfiltration', +'ExternalSystem', +'File', +'Finding', +'Folder', +'GcpMetadata', +'Geolocation', +'GetBigQueryExportRequest', +'GetMuteConfigRequest', +'GetNotificationConfigRequest', +'GetResourceValueConfigRequest', +'GetSimulationRequest', +'GetSourceRequest', +'GetValuedResourceRequest', +'GroupFindingsRequest', +'GroupFindingsResponse', +'GroupMembership', +'GroupResult', +'IamBinding', +'Indicator', +'KernelRootkit', +'Kubernetes', +'Label', +'ListAttackPathsRequest', +'ListAttackPathsResponse', +'ListBigQueryExportsRequest', +'ListBigQueryExportsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListMuteConfigsRequest', +'ListMuteConfigsResponse', +'ListNotificationConfigsRequest', +'ListNotificationConfigsResponse', +'ListResourceValueConfigsRequest', +'ListResourceValueConfigsResponse', +'ListSourcesRequest', +'ListSourcesResponse', +'ListValuedResourcesRequest', +'ListValuedResourcesResponse', +'LoadBalancer', +'LogEntry', +'MitreAttack', +'MuteConfig', +'Notebook', +'NotificationConfig', +'NotificationMessage', +'OrgPolicy', +'Package', +'Process', +'Reference', +'Requests', +'Resource', +'ResourcePath', +'ResourceValue', +'ResourceValueConfig', +'ResourceValueConfigMetadata', +'SecurityBulletin', +'SecurityCenterClient', +'SecurityMarks', +'SecurityPolicy', +'SecurityPosture', +'ServiceAccountDelegationInfo', +'SetFindingStateRequest', +'SetMuteRequest', +'Simulation', +'Source', +'ToxicCombination', +'UpdateBigQueryExportRequest', +'UpdateExternalSystemRequest', +'UpdateFindingRequest', +'UpdateMuteConfigRequest', +'UpdateNotificationConfigRequest', +'UpdateResourceValueConfigRequest', +'UpdateSecurityMarksRequest', +'UpdateSourceRequest', +'ValuedResource', +'Vulnerability', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json new file mode 100644 index 000000000000..517d51c03f32 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json @@ -0,0 +1,628 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v2", + "protoPackage": "google.cloud.securitycenter.v2", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "rest": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_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-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_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-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__init__.py new file mode 100644 index 000000000000..bffcff5da306 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + 'SecurityCenterClient', + 'SecurityCenterAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py new file mode 100644 index 000000000000..2d6ff6d7cf55 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py @@ -0,0 +1,5422 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.securitycenter_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.securitycenter_v2.services.security_center import pagers +from google.cloud.securitycenter_v2.types import access +from google.cloud.securitycenter_v2.types import application +from google.cloud.securitycenter_v2.types import attack_exposure +from google.cloud.securitycenter_v2.types import attack_path +from google.cloud.securitycenter_v2.types import backup_disaster_recovery +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import cloud_armor +from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile +from google.cloud.securitycenter_v2.types import cloud_dlp_inspection +from google.cloud.securitycenter_v2.types import compliance +from google.cloud.securitycenter_v2.types import connection +from google.cloud.securitycenter_v2.types import container +from google.cloud.securitycenter_v2.types import database +from google.cloud.securitycenter_v2.types import exfiltration +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import file +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import group_membership +from google.cloud.securitycenter_v2.types import iam_binding +from google.cloud.securitycenter_v2.types import indicator +from google.cloud.securitycenter_v2.types import kernel_rootkit +from google.cloud.securitycenter_v2.types import kubernetes +from google.cloud.securitycenter_v2.types import load_balancer +from google.cloud.securitycenter_v2.types import log_entry +from google.cloud.securitycenter_v2.types import mitre_attack +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notebook +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import org_policy +from google.cloud.securitycenter_v2.types import process +from google.cloud.securitycenter_v2.types import resource +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import security_posture +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import toxic_combination +from google.cloud.securitycenter_v2.types import valued_resource +from google.cloud.securitycenter_v2.types import vulnerability +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 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 SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V2 APIs for Security Center service.""" + + _client: SecurityCenterClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE + + attack_path_path = staticmethod(SecurityCenterClient.attack_path_path) + parse_attack_path_path = staticmethod(SecurityCenterClient.parse_attack_path_path) + big_query_export_path = staticmethod(SecurityCenterClient.big_query_export_path) + parse_big_query_export_path = staticmethod(SecurityCenterClient.parse_big_query_export_path) + dlp_job_path = staticmethod(SecurityCenterClient.dlp_job_path) + parse_dlp_job_path = staticmethod(SecurityCenterClient.parse_dlp_job_path) + external_system_path = staticmethod(SecurityCenterClient.external_system_path) + parse_external_system_path = staticmethod(SecurityCenterClient.parse_external_system_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) + parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) + mute_config_path = staticmethod(SecurityCenterClient.mute_config_path) + parse_mute_config_path = staticmethod(SecurityCenterClient.parse_mute_config_path) + notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) + parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) + policy_path = staticmethod(SecurityCenterClient.policy_path) + parse_policy_path = staticmethod(SecurityCenterClient.parse_policy_path) + resource_value_config_path = staticmethod(SecurityCenterClient.resource_value_config_path) + parse_resource_value_config_path = staticmethod(SecurityCenterClient.parse_resource_value_config_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) + simulation_path = staticmethod(SecurityCenterClient.simulation_path) + parse_simulation_path = staticmethod(SecurityCenterClient.parse_simulation_path) + source_path = staticmethod(SecurityCenterClient.source_path) + parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) + table_data_profile_path = staticmethod(SecurityCenterClient.table_data_profile_path) + parse_table_data_profile_path = staticmethod(SecurityCenterClient.parse_table_data_profile_path) + topic_path = staticmethod(SecurityCenterClient.topic_path) + parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) + valued_resource_path = staticmethod(SecurityCenterClient.valued_resource_path) + parse_valued_resource_path = staticmethod(SecurityCenterClient.parse_valued_resource_path) + common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) + parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) + common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) + parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) + common_project_path = staticmethod(SecurityCenterClient.common_project_path) + parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) + common_location_path = staticmethod(SecurityCenterClient.common_location_path) + parse_common_location_path = staticmethod(SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def batch_create_resource_value_configs(self, + request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + requests = securitycenter_v2.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + + request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest, dict]]): + The request object. Request message to create multiple + resource value configs + parent (:class:`str`): + Required. Resource name of the new + ResourceValueConfig's parent. The parent + field in the + CreateResourceValueConfigRequest + messages must either be empty or match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (:class:`MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]`): + Required. The resource value configs + to be created. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, requests]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): + request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests: + request.requests.extend(requests) + + # 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_resource_value_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, + ) + + # Done; return the response. + return response + + async def bulk_mute_findings(self, + request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off an LRO to bulk mute findings for a parent + based on a filter. If no location is specified, findings + are muted in global. The parent can be either an + organization, folder, or project. The findings matched + by the filter will be muted after the LRO is done. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest, dict]]): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + parent (:class:`str`): + Required. The parent, at which bulk action needs to be + applied. If no location is specified, findings are + updated in global. The following list shows some + examples: + + - ``organizations/[organization_id]`` + - ``organizations/[organization_id]/locations/[location_id]`` + - ``folders/[folder_id]`` + - ``folders/[folder_id]/locations/[location_id]`` + - ``projects/[project_id]`` + - ``projects/[project_id]/locations/[location_id]`` + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v2.types.BulkMuteFindingsResponse` + The response to a BulkMute request. Contains the LRO + 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]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): + request = securitycenter_service.BulkMuteFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.bulk_mute_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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + securitycenter_service.BulkMuteFindingsResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def create_big_query_export(self, + request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, + *, + parent: Optional[str] = None, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + big_query_export_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Creates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_create_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = await client.create_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest, dict]]): + The request object. Request message for creating a + BigQuery export. + parent (:class:`str`): + Required. The name of the parent resource of the new + BigQuery export. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export (:class:`google.cloud.securitycenter_v2.types.BigQueryExport`): + Required. The BigQuery export being + created. + + This corresponds to the ``big_query_export`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``big_query_export_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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): + request = securitycenter_service.CreateBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if big_query_export is not None: + request.big_query_export = big_query_export + if big_query_export_id is not None: + request.big_query_export_id = big_query_export_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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + finding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding in a location. The corresponding + source must exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_create_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateFindingRequest, dict]]): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. The + following list shows some examples of the format: + + ``organizations/[organization_id]/sources/[source_id]`` + + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`google.cloud.securitycenter_v2.types.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_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.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding, finding_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, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding is not None: + request.finding = finding + if finding_id is not None: + request.finding_id = finding_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_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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 create_mute_config(self, + request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + mute_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Creates a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_create_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = await client.create_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateMuteConfigRequest, dict]]): + The request object. Request message for creating a mute + config. + parent (:class:`str`): + Required. Resource name of the new mute configs's + parent. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config (:class:`google.cloud.securitycenter_v2.types.MuteConfig`): + Required. The mute config being + created. + + This corresponds to the ``mute_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``mute_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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): + request = securitycenter_service.CreateMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mute_config is not None: + request.mute_config = mute_config + if mute_config_id is not None: + request.mute_config_id = mute_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_mute_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 create_notification_config(self, + request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_create_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest, dict]]): + The request object. Request message for creating a + notification config. + parent (:class:`str`): + Required. Resource name of the new notification config's + parent. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (:class:`google.cloud.securitycenter_v2.types.NotificationConfig`): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (:class:`str`): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters and contain + alphanumeric characters, underscores, or + hyphens only. + + This corresponds to the ``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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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_config, 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, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if notification_config is not None: + request.notification_config = notification_config + if config_id is not None: + request.config_id = 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_notification_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 create_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v2 + + async def sample_create_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateSourceRequest, dict]]): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be ``organizations/[organization_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`google.cloud.securitycenter_v2.types.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = 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_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 delete_big_query_export(self, + request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + await client.delete_big_query_export(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest, dict]]): + The request object. Request message for deleting a + BigQuery export. + name (:class:`str`): + Required. The name of the BigQuery export to delete. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}/locations/{location}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): + request = securitycenter_service.DeleteBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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 delete_mute_config(self, + request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. If no location is + specified, default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_delete_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_mute_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest, dict]]): + The request object. Request message for deleting a mute + config. If no location is specified, + default is global. + name (:class:`str`): + Required. Name of the mute config to delete. The + following list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): + request = securitycenter_service.DeleteMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_mute_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 delete_notification_config(self, + request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest, dict]]): + The request object. Request message for deleting a + notification config. + name (:class:`str`): + Required. Name of the notification config to delete. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 delete_resource_value_config(self, + request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_resource_value_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest, dict]]): + The request object. Request message to delete resource + value config + name (:class:`str`): + Required. Name of the + ResourceValueConfig 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. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): + request = securitycenter_service.DeleteResourceValueConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_resource_value_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_big_query_export(self, + request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Gets a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_get_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetBigQueryExportRequest, dict]]): + The request object. Request message for retrieving a + BigQuery export. + name (:class:`str`): + Required. Name of the BigQuery export to retrieve. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}locations/{location}//bigQueryExports/{export_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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): + request = securitycenter_service.GetBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_simulation(self, + request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> simulation.Simulation: + r"""Get the simulation by name or the latest simulation + for the given organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_get_simulation(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_simulation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetSimulationRequest, dict]]): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + name (:class:`str`): + Required. The organization name or simulation name of + this simulation + + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.Simulation: + Attack path simulation + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSimulationRequest): + request = securitycenter_service.GetSimulationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_simulation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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_valued_resource(self, + request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> valued_resource.ValuedResource: + r"""Get the valued resource by 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 import securitycenter_v2 + + async def sample_get_valued_resource(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_valued_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetValuedResourceRequest, dict]]): + The request object. Request message for getting a valued + resource. + name (:class:`str`): + Required. The name of this valued resource + + Valid format: + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v2.types.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetValuedResourceRequest): + request = securitycenter_service.GetValuedResourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_valued_resource] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 get_mute_config(self, + request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> mute_config.MuteConfig: + r"""Gets a mute config. If no location is specified, + default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_get_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetMuteConfigRequest, dict]]): + The request object. Request message for retrieving a mute + config. If no location is specified, + default is global. + name (:class:`str`): + Required. Name of the mute config to retrieve. The + following list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetMuteConfigRequest): + request = securitycenter_service.GetMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_mute_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 get_notification_config(self, + request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_get_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetNotificationConfigRequest, dict]]): + The request object. Request message for getting a + notification config. + name (:class:`str`): + Required. Name of the notification config to get. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 get_resource_value_config(self, + request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource_value_config.ResourceValueConfig: + r"""Gets a ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest, dict]]): + The request object. Request message to get resource value + config + name (:class:`str`): + Required. Name of the resource value config to retrieve. + Its format is + organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v2.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): + request = securitycenter_service.GetResourceValueConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_resource_value_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 get_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v2 + + async def sample_get_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetSourceRequest, dict]]): + The request object. Request message for getting a source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_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 group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties in a location. If no location is + specified, findings are assumed to be in global + + To group across all sources provide a ``-`` as the source id. + The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + - ``/v2/folders/{folder_id}/sources/-/findings`` + - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` + - ``/v2/projects/{project_id}/sources/-/findings`` + - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_group_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GroupFindingsRequest, dict]]): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. If no location + is specified, finding is assumed to be in global. The + following list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To groupBy across all sources provide a source_id of + ``-``. The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/[location_id]`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-/locations/[location_id]`` + - ``projects/{project_id}/sources/-`` + - ``projects/{project_id}/sources/-/locations/[location_id]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping. The string value should follow SQL + syntax: comma separated list of fields. For example: + "parent,resource_name". + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_attack_paths(self, + request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsAsyncPager: + r"""Lists the attack paths for a set of simulation + results or valued resources and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_attack_paths(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListAttackPathsRequest, dict]]): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + parent (:class:`str`): + Required. Name of parent to list attack paths. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + + 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.securitycenter_v2.services.security_center.pagers.ListAttackPathsAsyncPager: + Response message for listing the + attack paths for a given simulation or + valued resource. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): + request = securitycenter_service.ListAttackPathsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_attack_paths] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListAttackPathsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_big_query_exports(self, + request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsAsyncPager: + r"""Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are 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 securitycenter_v2 + + async def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest, dict]]): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or project. + parent (:class:`str`): + Required. The parent, which owns the collection of + BigQuery exports. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + 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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsAsyncPager: + Response message for listing BigQuery + exports. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): + request = securitycenter_service.ListBigQueryExportsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_big_query_exports] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListBigQueryExportsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings(self, + request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsAsyncPager: + r"""Lists an organization or source's findings. + + To list across all sources for a given location provide a ``-`` + as the source id. If no location is specified, finding are + assumed to be in global. The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListFindingsRequest( + parent="parent_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.securitycenter_v2.types.ListFindingsRequest, dict]]): + The request object. Request message for listing findings. + parent (:class:`str`): + Required. Name of the source the findings belong to. If + no location is specified, the default is global. The + following list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To list across all sources provide a source_id of ``-``. + The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/{location_id}`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-locations/{location_id}`` + - ``projects/{projects_id}/sources/-`` + - ``projects/{projects_id}/sources/-/locations/{location_id}`` + + 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.securitycenter_v2.services.security_center.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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_mute_configs(self, + request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsAsyncPager: + r"""Lists mute configs. If no location is specified, + default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_mute_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListMuteConfigsRequest, dict]]): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or project. If no + location is specified, default is + global. + parent (:class:`str`): + Required. The parent, which owns the collection of mute + configs. Its format is + ``organizations/[organization_id]", "folders/[folder_id]``, + ``projects/[project_id]``, + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, + ``projects/[project_id]/locations/[location_id]``. + + 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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsAsyncPager: + Response message for listing mute + configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): + request = securitycenter_service.ListMuteConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_mute_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.ListMuteConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_notification_configs(self, + request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsAsyncPager: + r"""Lists notification configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest, dict]]): + The request object. Request message for listing + notification configs. + parent (:class:`str`): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + 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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsAsyncPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListNotificationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_resource_value_configs(self, + request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsAsyncPager: + r"""Lists all ResourceValueConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest, dict]]): + The request object. Request message to list resource + value configs of a parent + parent (:class:`str`): + Required. The parent, which owns the collection of + resource value configs. Its format is + ``organizations/[organization_id]`` + + 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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsAsyncPager: + Response message to list resource + value configs + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): + request = securitycenter_service.ListResourceValueConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_resource_value_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.ListResourceValueConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_sources(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListSourcesRequest, dict]]): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + 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.securitycenter_v2.services.security_center.pagers.ListSourcesAsyncPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_valued_resources(self, + request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesAsyncPager: + r"""Lists the valued resources for a set of simulation + results and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_list_valued_resources(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListValuedResourcesRequest, dict]]): + The request object. Request message for listing the + valued resources for a given simulation. + parent (:class:`str`): + Required. Name of parent to list exposed resources. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + + 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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesAsyncPager: + Response message for listing the + valued resources for a given simulation. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): + request = securitycenter_service.ListValuedResourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_valued_resources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", 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.ListValuedResourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. If no location is + specified, finding is assumed to be in global + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_set_finding_state(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.SetFindingStateRequest, dict]]): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`google.cloud.securitycenter_v2.types.Finding.State`): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 set_mute(self, + request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, + *, + name: Optional[str] = None, + mute: Optional[finding.Finding.Mute] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the mute state of a finding. If no location + is specified, finding is assumed to be in global + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_set_mute(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = await client.set_mute(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.SetMuteRequest, dict]]): + The request object. Request message for updating a + finding's mute status. + name (:class:`str`): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute (:class:`google.cloud.securitycenter_v2.types.Finding.Mute`): + Required. The desired state of the + Mute. + + This corresponds to the ``mute`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, mute]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetMuteRequest): + request = securitycenter_service.SetMuteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if mute is not None: + request.mute = mute + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.set_mute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._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 update_big_query_export(self, + request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, + *, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + update_mask: 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]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Updates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateBigQueryExportRequest( + ) + + # Make the request + response = await client.update_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest, dict]]): + The request object. Request message for updating a + BigQuery export. + big_query_export (:class:`google.cloud.securitycenter_v2.types.BigQueryExport`): + Required. The BigQuery export being + updated. + + This corresponds to the ``big_query_export`` 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. + If empty all mutable fields 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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): + request = securitycenter_service.UpdateBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if big_query_export is not None: + request.big_query_export = big_query_export + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("big_query_export.name", request.big_query_export.name), + )), + ) + + # Validate the universe domain. + self._client._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_external_system(self, + request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, + *, + external_system: Optional[gcs_external_system.ExternalSystem] = None, + update_mask: 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]] = (), + ) -> gcs_external_system.ExternalSystem: + r"""Updates external system. This is for a given finding. + If no location is specified, finding is assumed to be in + global + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_external_system(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateExternalSystemRequest( + ) + + # Make the request + response = await client.update_external_system(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest, dict]]): + The request object. Request message for updating a + ExternalSystem resource. + external_system (:class:`google.cloud.securitycenter_v2.types.ExternalSystem`): + Required. The external system + resource to update. + + This corresponds to the ``external_system`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the external system resource. + If empty all mutable fields 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.cloud.securitycenter_v2.types.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): + request = securitycenter_service.UpdateExternalSystemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if external_system is not None: + request.external_system = external_system + 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_external_system] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("external_system.name", request.external_system.name), + )), + ) + + # Validate the universe domain. + self._client._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_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + update_mask: 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]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. If no location is + specified, finding is assumed to be in global. The + corresponding source must exist for a finding creation + to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateFindingRequest, dict]]): + The request object. Request message for updating or + creating a finding. + finding (:class:`google.cloud.securitycenter_v2.types.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + + 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.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + 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_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe domain. + self._client._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_mute_config(self, + request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, + *, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + update_mask: 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]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Updates a mute config. If no location is specified, + default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = await client.update_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest, dict]]): + The request object. Request message for updating a mute + config. + mute_config (:class:`google.cloud.securitycenter_v2.types.MuteConfig`): + Required. The mute config being + updated. + + This corresponds to the ``mute_config`` 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. + If empty all mutable fields 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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): + request = securitycenter_service.UpdateMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mute_config is not None: + request.mute_config = mute_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_mute_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("mute_config.name", request.mute_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 update_notification_config(self, + request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, + *, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + update_mask: 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest, dict]]): + The request object. Request message for updating a + notification config. + notification_config (:class:`google.cloud.securitycenter_v2.types.NotificationConfig`): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the notification config. + If empty all mutable fields 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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_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 update_resource_value_config(self, + request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, + *, + resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, + update_mask: 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]] = (), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Updates an existing ResourceValueConfigs with new + rules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateResourceValueConfigRequest( + ) + + # Make the request + response = await client.update_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest, dict]]): + The request object. Request message to update resource + value config + resource_value_config (:class:`google.cloud.securitycenter_v2.types.ResourceValueConfig`): + Required. The resource value config + being updated. + + This corresponds to the ``resource_value_config`` 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. If empty all mutable + fields will be updated. + + To update nested fields, include the top level field in + the mask For example, to update + gcp_metadata.resource_type, include the "gcp_metadata" + field mask + + 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.securitycenter_v2.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): + request = securitycenter_service.UpdateResourceValueConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if resource_value_config is not None: + request.resource_value_config = resource_value_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_resource_value_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource_value_config.name", request.resource_value_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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + update_mask: 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]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. For Finding Security marks, + if no location is specified, finding is assumed to be in + global. Assets Security Marks can only be accessed + through global endpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_security_marks(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest, dict]]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`google.cloud.securitycenter_v2.types.SecurityMarks`): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + + 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.securitycenter_v2.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + 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_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe domain. + self._client._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_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + update_mask: 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]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v2 + + async def sample_update_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateSourceRequest, dict]]): + The request object. Request message for updating a + source. + source (:class:`google.cloud.securitycenter_v2.types.Source`): + Required. The source resource to + update. + + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the source resource. + If empty all mutable fields 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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = 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_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self) -> "SecurityCenterAsyncClient": + 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__ = ( + "SecurityCenterAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py new file mode 100644 index 000000000000..550305f1c892 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py @@ -0,0 +1,5948 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.securitycenter_v2.services.security_center import pagers +from google.cloud.securitycenter_v2.types import access +from google.cloud.securitycenter_v2.types import application +from google.cloud.securitycenter_v2.types import attack_exposure +from google.cloud.securitycenter_v2.types import attack_path +from google.cloud.securitycenter_v2.types import backup_disaster_recovery +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import cloud_armor +from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile +from google.cloud.securitycenter_v2.types import cloud_dlp_inspection +from google.cloud.securitycenter_v2.types import compliance +from google.cloud.securitycenter_v2.types import connection +from google.cloud.securitycenter_v2.types import container +from google.cloud.securitycenter_v2.types import database +from google.cloud.securitycenter_v2.types import exfiltration +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import file +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import group_membership +from google.cloud.securitycenter_v2.types import iam_binding +from google.cloud.securitycenter_v2.types import indicator +from google.cloud.securitycenter_v2.types import kernel_rootkit +from google.cloud.securitycenter_v2.types import kubernetes +from google.cloud.securitycenter_v2.types import load_balancer +from google.cloud.securitycenter_v2.types import log_entry +from google.cloud.securitycenter_v2.types import mitre_attack +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notebook +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import org_policy +from google.cloud.securitycenter_v2.types import process +from google.cloud.securitycenter_v2.types import resource +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import security_posture +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import toxic_combination +from google.cloud.securitycenter_v2.types import valued_resource +from google.cloud.securitycenter_v2.types import vulnerability +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 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 SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .transports.rest import SecurityCenterRestTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + _transport_registry["rest"] = SecurityCenterRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SecurityCenterTransport]: + """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V2 APIs for Security Center 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 = "securitycenter.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: + SecurityCenterClient: 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: + SecurityCenterClient: 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) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def attack_path_path(organization: str,simulation: str,valued_resource: str,attack_path: str,) -> str: + """Returns a fully-qualified attack_path string.""" + return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) + + @staticmethod + def parse_attack_path_path(path: str) -> Dict[str,str]: + """Parses a attack_path path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?P.+?)/attackPaths/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def big_query_export_path(organization: str,location: str,export: str,) -> str: + """Returns a fully-qualified big_query_export string.""" + return "organizations/{organization}/locations/{location}/bigQueryExports/{export}".format(organization=organization, location=location, export=export, ) + + @staticmethod + def parse_big_query_export_path(path: str) -> Dict[str,str]: + """Parses a big_query_export path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/locations/(?P.+?)/bigQueryExports/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def dlp_job_path(project: str,dlp_job: str,) -> str: + """Returns a fully-qualified dlp_job string.""" + return "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) + + @staticmethod + def parse_dlp_job_path(path: str) -> Dict[str,str]: + """Parses a dlp_job path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/dlpJobs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def external_system_path(organization: str,source: str,finding: str,externalsystem: str,) -> str: + """Returns a fully-qualified external_system string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) + + @staticmethod + def parse_external_system_path(path: str) -> Dict[str,str]: + """Parses a external_system path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)/externalSystems/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def finding_path(organization: str,source: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def mute_config_path(organization: str,mute_config: str,) -> str: + """Returns a fully-qualified mute_config string.""" + return "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) + + @staticmethod + def parse_mute_config_path(path: str) -> Dict[str,str]: + """Parses a mute_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/muteConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def notification_config_path(organization: str,location: str,notification_config: str,) -> str: + """Returns a fully-qualified notification_config string.""" + return "organizations/{organization}/locations/{location}/notificationConfigs/{notification_config}".format(organization=organization, location=location, notification_config=notification_config, ) + + @staticmethod + def parse_notification_config_path(path: str) -> Dict[str,str]: + """Parses a notification_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/locations/(?P.+?)/notificationConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def policy_path(organization: str,constraint_name: str,) -> str: + """Returns a fully-qualified policy string.""" + return "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) + + @staticmethod + def parse_policy_path(path: str) -> Dict[str,str]: + """Parses a policy path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/policies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def resource_value_config_path(organization: str,resource_value_config: str,) -> str: + """Returns a fully-qualified resource_value_config string.""" + return "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) + + @staticmethod + def parse_resource_value_config_path(path: str) -> Dict[str,str]: + """Parses a resource_value_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/resourceValueConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str,str]: + """Parses a security_marks path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) + return m.groupdict() if m else {} + + @staticmethod + def simulation_path(organization: str,simulation: str,) -> str: + """Returns a fully-qualified simulation string.""" + return "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) + + @staticmethod + def parse_simulation_path(path: str) -> Dict[str,str]: + """Parses a simulation path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str,source: str,) -> str: + """Returns a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str,str]: + """Parses a source path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def table_data_profile_path(project: str,table_profile: str,) -> str: + """Returns a fully-qualified table_data_profile string.""" + return "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) + + @staticmethod + def parse_table_data_profile_path(path: str) -> Dict[str,str]: + """Parses a table_data_profile path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/tableProfiles/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def topic_path(project: str,topic: str,) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str,str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def valued_resource_path(organization: str,simulation: str,valued_resource: str,) -> str: + """Returns a fully-qualified valued_resource string.""" + return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) + + @staticmethod + def parse_valued_resource_path(path: str) -> Dict[str,str]: + """Parses a valued_resource path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 + SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): + 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 SecurityCenterTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SecurityCenterClient._read_environment_variables() + self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) + if transport_provided: + # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SecurityCenterTransport], 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 batch_create_resource_value_configs(self, + request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, + *, + parent: Optional[str] = None, + requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + requests = securitycenter_v2.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + + request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest, dict]): + The request object. Request message to create multiple + resource value configs + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. The parent + field in the + CreateResourceValueConfigRequest + messages must either be empty or match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]): + Required. The resource value configs + to be created. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, requests]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): + request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_resource_value_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, + ) + + # Done; return the response. + return response + + def bulk_mute_findings(self, + request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), + ) -> operation.Operation: + r"""Kicks off an LRO to bulk mute findings for a parent + based on a filter. If no location is specified, findings + are muted in global. The parent can be either an + organization, folder, or project. The findings matched + by the filter will be muted after the LRO is done. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest, dict]): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + parent (str): + Required. The parent, at which bulk action needs to be + applied. If no location is specified, findings are + updated in global. The following list shows some + examples: + + - ``organizations/[organization_id]`` + - ``organizations/[organization_id]/locations/[location_id]`` + - ``folders/[folder_id]`` + - ``folders/[folder_id]/locations/[location_id]`` + - ``projects/[project_id]`` + - ``projects/[project_id]/locations/[location_id]`` + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v2.types.BulkMuteFindingsResponse` + The response to a BulkMute request. Contains the LRO + 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): + request = securitycenter_service.BulkMuteFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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.bulk_mute_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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + securitycenter_service.BulkMuteFindingsResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def create_big_query_export(self, + request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, + *, + parent: Optional[str] = None, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + big_query_export_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Creates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_create_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = client.create_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest, dict]): + The request object. Request message for creating a + BigQuery export. + parent (str): + Required. The name of the parent resource of the new + BigQuery export. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): + Required. The BigQuery export being + created. + + This corresponds to the ``big_query_export`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``big_query_export_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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): + request = securitycenter_service.CreateBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if big_query_export is not None: + request.big_query_export = big_query_export + if big_query_export_id is not None: + request.big_query_export_id = big_query_export_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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 create_finding(self, + request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + finding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding in a location. The corresponding + source must exist for finding creation to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_create_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateFindingRequest, dict]): + The request object. Request message for creating a + finding. + parent (str): + Required. Resource name of the new finding's parent. The + following list shows some examples of the format: + + ``organizations/[organization_id]/sources/[source_id]`` + + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (google.cloud.securitycenter_v2.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_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.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding, finding_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, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding is not None: + request.finding = finding + if finding_id is not None: + request.finding_id = finding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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 create_mute_config(self, + request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + mute_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Creates a mute config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_create_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = client.create_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateMuteConfigRequest, dict]): + The request object. Request message for creating a mute + config. + parent (str): + Required. Resource name of the new mute configs's + parent. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config (google.cloud.securitycenter_v2.types.MuteConfig): + Required. The mute config being + created. + + This corresponds to the ``mute_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``mute_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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): + request = securitycenter_service.CreateMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mute_config is not None: + request.mute_config = mute_config + if mute_config_id is not None: + request.mute_config_id = mute_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_mute_config] + + header_params = {} + + routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + 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_notification_config(self, + request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_create_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest, dict]): + The request object. Request message for creating a + notification config. + parent (str): + Required. Resource name of the new notification config's + parent. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (str): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters and contain + alphanumeric characters, underscores, or + hyphens only. + + This corresponds to the ``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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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_config, 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, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if notification_config is not None: + request.notification_config = notification_config + if config_id is not None: + request.config_id = config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_notification_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 create_source(self, + request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a 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.cloud import securitycenter_v2 + + def sample_create_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateSourceRequest, dict]): + The request object. Request message for creating a + source. + parent (str): + Required. Resource name of the new source's parent. Its + format should be ``organizations/[organization_id]``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (google.cloud.securitycenter_v2.types.Source): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_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 delete_big_query_export(self, + request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + client.delete_big_query_export(request=request) + + Args: + request (Union[google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest, dict]): + The request object. Request message for deleting a + BigQuery export. + name (str): + Required. The name of the BigQuery export to delete. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}/locations/{location}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): + request = securitycenter_service.DeleteBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + 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 delete_mute_config(self, + request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. If no location is + specified, default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_delete_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_mute_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest, dict]): + The request object. Request message for deleting a mute + config. If no location is specified, + default is global. + name (str): + Required. Name of the mute config to delete. The + following list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): + request = securitycenter_service.DeleteMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_mute_config] + + header_params = {} + + routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + 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 delete_notification_config(self, + request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_delete_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest, dict]): + The request object. Request message for deleting a + notification config. + name (str): + Required. Name of the notification config to delete. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 delete_resource_value_config(self, + request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_resource_value_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest, dict]): + The request object. Request message to delete resource + value config + name (str): + Required. Name of the + ResourceValueConfig 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. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): + request = securitycenter_service.DeleteResourceValueConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_resource_value_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_big_query_export(self, + request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Gets a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_get_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = client.get_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetBigQueryExportRequest, dict]): + The request object. Request message for retrieving a + BigQuery export. + name (str): + Required. Name of the BigQuery export to retrieve. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}locations/{location}//bigQueryExports/{export_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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): + request = securitycenter_service.GetBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_simulation(self, + request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> simulation.Simulation: + r"""Get the simulation by name or the latest simulation + for the given organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_get_simulation(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = client.get_simulation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetSimulationRequest, dict]): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + name (str): + Required. The organization name or simulation name of + this simulation + + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.Simulation: + Attack path simulation + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSimulationRequest): + request = securitycenter_service.GetSimulationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_simulation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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_valued_resource(self, + request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> valued_resource.ValuedResource: + r"""Get the valued resource by 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 import securitycenter_v2 + + def sample_get_valued_resource(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_valued_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetValuedResourceRequest, dict]): + The request object. Request message for getting a valued + resource. + name (str): + Required. The name of this valued resource + + Valid format: + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v2.types.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetValuedResourceRequest): + request = securitycenter_service.GetValuedResourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_valued_resource] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 get_mute_config(self, + request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> mute_config.MuteConfig: + r"""Gets a mute config. If no location is specified, + default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_get_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetMuteConfigRequest, dict]): + The request object. Request message for retrieving a mute + config. If no location is specified, + default is global. + name (str): + Required. Name of the mute config to retrieve. The + following list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetMuteConfigRequest): + request = securitycenter_service.GetMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_mute_config] + + header_params = {} + + routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + 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_notification_config(self, + request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_get_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetNotificationConfigRequest, dict]): + The request object. Request message for getting a + notification config. + name (str): + Required. Name of the notification config to get. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 get_resource_value_config(self, + request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource_value_config.ResourceValueConfig: + r"""Gets a ResourceValueConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest, dict]): + The request object. Request message to get resource value + config + name (str): + Required. Name of the resource value config to retrieve. + Its format is + organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v2.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): + request = securitycenter_service.GetResourceValueConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_resource_value_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 get_source(self, + request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a 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.cloud import securitycenter_v2 + + def sample_get_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetSourceRequest, dict]): + The request object. Request message for getting a source. + name (str): + Required. Relative resource name of the source. Its + format is + ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_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 group_findings(self, + request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties in a location. If no location is + specified, findings are assumed to be in global + + To group across all sources provide a ``-`` as the source id. + The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + - ``/v2/folders/{folder_id}/sources/-/findings`` + - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` + - ``/v2/projects/{project_id}/sources/-/findings`` + - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_group_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GroupFindingsRequest, dict]): + The request object. Request message for grouping by + findings. + parent (str): + Required. Name of the source to groupBy. If no location + is specified, finding is assumed to be in global. The + following list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To groupBy across all sources provide a source_id of + ``-``. The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/[location_id]`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-/locations/[location_id]`` + - ``projects/{project_id}/sources/-`` + - ``projects/{project_id}/sources/-/locations/[location_id]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (str): + Required. Expression that defines what assets fields to + use for grouping. The string value should follow SQL + syntax: comma separated list of fields. For example: + "parent,resource_name". + + This corresponds to the ``group_by`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_attack_paths(self, + request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsPager: + r"""Lists the attack paths for a set of simulation + results or valued resources and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_attack_paths(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListAttackPathsRequest, dict]): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + parent (str): + Required. Name of parent to list attack paths. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + + 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.securitycenter_v2.services.security_center.pagers.ListAttackPathsPager: + Response message for listing the + attack paths for a given simulation or + valued resource. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): + request = securitycenter_service.ListAttackPathsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_attack_paths] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListAttackPathsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_big_query_exports(self, + request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsPager: + r"""Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are 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 securitycenter_v2 + + def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest, dict]): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or project. + parent (str): + Required. The parent, which owns the collection of + BigQuery exports. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + + 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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsPager: + Response message for listing BigQuery + exports. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): + request = securitycenter_service.ListBigQueryExportsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_big_query_exports] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListBigQueryExportsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings(self, + request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsPager: + r"""Lists an organization or source's findings. + + To list across all sources for a given location provide a ``-`` + as the source id. If no location is specified, finding are + assumed to be in global. The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListFindingsRequest( + parent="parent_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.securitycenter_v2.types.ListFindingsRequest, dict]): + The request object. Request message for listing findings. + parent (str): + Required. Name of the source the findings belong to. If + no location is specified, the default is global. The + following list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To list across all sources provide a source_id of ``-``. + The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/{location_id}`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-locations/{location_id}`` + - ``projects/{projects_id}/sources/-`` + - ``projects/{projects_id}/sources/-/locations/{location_id}`` + + 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.securitycenter_v2.services.security_center.pagers.ListFindingsPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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_mute_configs(self, + request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsPager: + r"""Lists mute configs. If no location is specified, + default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_mute_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListMuteConfigsRequest, dict]): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or project. If no + location is specified, default is + global. + parent (str): + Required. The parent, which owns the collection of mute + configs. Its format is + ``organizations/[organization_id]", "folders/[folder_id]``, + ``projects/[project_id]``, + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, + ``projects/[project_id]/locations/[location_id]``. + + 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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsPager: + Response message for listing mute + configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): + request = securitycenter_service.ListMuteConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_mute_configs] + + header_params = {} + + routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + 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.ListMuteConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_notification_configs(self, + request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsPager: + r"""Lists notification configs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_notification_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest, dict]): + The request object. Request message for listing + notification configs. + parent (str): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + 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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListNotificationConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_resource_value_configs(self, + request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsPager: + r"""Lists all ResourceValueConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest, dict]): + The request object. Request message to list resource + value configs of a parent + parent (str): + Required. The parent, which owns the collection of + resource value configs. Its format is + ``organizations/[organization_id]`` + + 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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsPager: + Response message to list resource + value configs + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): + request = securitycenter_service.ListResourceValueConfigsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_resource_value_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.ListResourceValueConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sources(self, + request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_sources(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListSourcesRequest, dict]): + The request object. Request message for listing sources. + parent (str): + Required. Resource name of the parent of sources to + list. Its format should be + ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + + 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.securitycenter_v2.services.security_center.pagers.ListSourcesPager: + Response message for listing sources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_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.ListSourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_valued_resources(self, + request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesPager: + r"""Lists the valued resources for a set of simulation + results and filter. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_list_valued_resources(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListValuedResourcesRequest, dict]): + The request object. Request message for listing the + valued resources for a given simulation. + parent (str): + Required. Name of parent to list exposed resources. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + + 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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesPager: + Response message for listing the + valued resources for a given simulation. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): + request = securitycenter_service.ListValuedResourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_valued_resources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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.ListValuedResourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_finding_state(self, + request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. If no location is + specified, finding is assumed to be in global + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_set_finding_state(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.SetFindingStateRequest, dict]): + The request object. Request message for updating a + finding's state. + name (str): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (google.cloud.securitycenter_v2.types.Finding.State): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on the specified + 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.cloud import securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # 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 set_mute(self, + request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, + *, + name: Optional[str] = None, + mute: Optional[finding.Finding.Mute] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the mute state of a finding. If no location + is specified, finding is assumed to be in global + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_set_mute(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = client.set_mute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.SetMuteRequest, dict]): + The request object. Request message for updating a + finding's mute status. + name (str): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute (google.cloud.securitycenter_v2.types.Finding.Mute): + Required. The desired state of the + Mute. + + This corresponds to the ``mute`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, mute]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, securitycenter_service.SetMuteRequest): + request = securitycenter_service.SetMuteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if mute is not None: + request.mute = mute + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_mute] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the + specified 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.cloud import securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # - The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # 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 + + def update_big_query_export(self, + request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, + *, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + update_mask: 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]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Updates a BigQuery export. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateBigQueryExportRequest( + ) + + # Make the request + response = client.update_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest, dict]): + The request object. Request message for updating a + BigQuery export. + big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): + Required. The BigQuery export being + updated. + + This corresponds to the ``big_query_export`` 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. + If empty all mutable fields 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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): + request = securitycenter_service.UpdateBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if big_query_export is not None: + request.big_query_export = big_query_export + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("big_query_export.name", request.big_query_export.name), + )), + ) + + # Validate the universe 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_external_system(self, + request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, + *, + external_system: Optional[gcs_external_system.ExternalSystem] = None, + update_mask: 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]] = (), + ) -> gcs_external_system.ExternalSystem: + r"""Updates external system. This is for a given finding. + If no location is specified, finding is assumed to be in + global + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_external_system(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateExternalSystemRequest( + ) + + # Make the request + response = client.update_external_system(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest, dict]): + The request object. Request message for updating a + ExternalSystem resource. + external_system (google.cloud.securitycenter_v2.types.ExternalSystem): + Required. The external system + resource to update. + + This corresponds to the ``external_system`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the external system resource. + If empty all mutable fields 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.cloud.securitycenter_v2.types.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): + request = securitycenter_service.UpdateExternalSystemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if external_system is not None: + request.external_system = external_system + 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_external_system] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("external_system.name", request.external_system.name), + )), + ) + + # Validate the universe 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_finding(self, + request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, + *, + finding: Optional[gcs_finding.Finding] = None, + update_mask: 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]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. If no location is + specified, finding is assumed to be in global. The + corresponding source must exist for a finding creation + to succeed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateFindingRequest, dict]): + The request object. Request message for updating or + creating a finding. + finding (google.cloud.securitycenter_v2.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + + 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.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + 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_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Validate the universe 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_mute_config(self, + request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, + *, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + update_mask: 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]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Updates a mute config. If no location is specified, + default is global. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = client.update_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest, dict]): + The request object. Request message for updating a mute + config. + mute_config (google.cloud.securitycenter_v2.types.MuteConfig): + Required. The mute config being + updated. + + This corresponds to the ``mute_config`` 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. + If empty all mutable fields 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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): + request = securitycenter_service.UpdateMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mute_config is not None: + request.mute_config = mute_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_mute_config] + + header_params = {} + + routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.mute_config.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.mute_config.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') + regex_match = routing_param_regex.match(request.mute_config.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + 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_notification_config(self, + request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, + *, + notification_config: Optional[gcs_notification_config.NotificationConfig] = None, + update_mask: 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest, dict]): + The request object. Request message for updating a + notification config. + notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the notification config. + If empty all mutable fields 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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_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 update_resource_value_config(self, + request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, + *, + resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, + update_mask: 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]] = (), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Updates an existing ResourceValueConfigs with new + rules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateResourceValueConfigRequest( + ) + + # Make the request + response = client.update_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest, dict]): + The request object. Request message to update resource + value config + resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): + Required. The resource value config + being updated. + + This corresponds to the ``resource_value_config`` 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. If empty all mutable + fields will be updated. + + To update nested fields, include the top level field in + the mask For example, to update + gcp_metadata.resource_type, include the "gcp_metadata" + field mask + + 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.securitycenter_v2.types.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): + request = securitycenter_service.UpdateResourceValueConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if resource_value_config is not None: + request.resource_value_config = resource_value_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_resource_value_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource_value_config.name", request.resource_value_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 update_security_marks(self, + request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = None, + update_mask: 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]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. For Finding Security marks, + if no location is specified, finding is assumed to be in + global. Assets Security Marks can only be accessed + through global endpoint. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_security_marks(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest, dict]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + + 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.securitycenter_v2.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + 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_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Validate the universe 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_source(self, + request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, + *, + source: Optional[gcs_source.Source] = None, + update_mask: 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]] = (), + ) -> gcs_source.Source: + r"""Updates a 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.cloud import securitycenter_v2 + + def sample_update_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateSourceRequest, dict]): + The request object. Request message for updating a + source. + source (google.cloud.securitycenter_v2.types.Source): + Required. The source resource to + update. + + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the source resource. + If empty all mutable fields 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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = 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_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.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 __enter__(self) -> "SecurityCenterClient": + 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 = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + 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 = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SecurityCenterClient", +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py new file mode 100644 index 000000000000..59d34c60c0a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py @@ -0,0 +1,1249 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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.securitycenter_v2.types import attack_path +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import valued_resource + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v2.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` + attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v2.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + 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[securitycenter_service.GroupFindingsResponse]: + 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[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAttackPathsPager: + """A pager for iterating through ``list_attack_paths`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``attack_paths`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAttackPaths`` requests and continue to iterate + through the ``attack_paths`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListAttackPathsResponse], + request: securitycenter_service.ListAttackPathsRequest, + response: securitycenter_service.ListAttackPathsResponse, + *, + 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.securitycenter_v2.types.ListAttackPathsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListAttackPathsResponse): + 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 = securitycenter_service.ListAttackPathsRequest(request) + 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[securitycenter_service.ListAttackPathsResponse]: + 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[attack_path.AttackPath]: + for page in self.pages: + yield from page.attack_paths + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAttackPathsAsyncPager: + """A pager for iterating through ``list_attack_paths`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``attack_paths`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAttackPaths`` requests and continue to iterate + through the ``attack_paths`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` + attributes are available on the 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[securitycenter_service.ListAttackPathsResponse]], + request: securitycenter_service.ListAttackPathsRequest, + response: securitycenter_service.ListAttackPathsResponse, + *, + 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.securitycenter_v2.types.ListAttackPathsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListAttackPathsResponse): + 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 = securitycenter_service.ListAttackPathsRequest(request) + 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[securitycenter_service.ListAttackPathsResponse]: + 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[attack_path.AttackPath]: + async def async_generator(): + async for page in self.pages: + for response in page.attack_paths: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBigQueryExportsPager: + """A pager for iterating through ``list_big_query_exports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``big_query_exports`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBigQueryExports`` requests and continue to iterate + through the ``big_query_exports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListBigQueryExportsResponse], + request: securitycenter_service.ListBigQueryExportsRequest, + response: securitycenter_service.ListBigQueryExportsResponse, + *, + 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.securitycenter_v2.types.ListBigQueryExportsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse): + 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 = securitycenter_service.ListBigQueryExportsRequest(request) + 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[securitycenter_service.ListBigQueryExportsResponse]: + 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[bigquery_export.BigQueryExport]: + for page in self.pages: + yield from page.big_query_exports + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBigQueryExportsAsyncPager: + """A pager for iterating through ``list_big_query_exports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``big_query_exports`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBigQueryExports`` requests and continue to iterate + through the ``big_query_exports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` + attributes are available on the 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[securitycenter_service.ListBigQueryExportsResponse]], + request: securitycenter_service.ListBigQueryExportsRequest, + response: securitycenter_service.ListBigQueryExportsResponse, + *, + 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.securitycenter_v2.types.ListBigQueryExportsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse): + 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 = securitycenter_service.ListBigQueryExportsRequest(request) + 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[securitycenter_service.ListBigQueryExportsResponse]: + 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[bigquery_export.BigQueryExport]: + async def async_generator(): + async for page in self.pages: + for response in page.big_query_exports: + 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.securitycenter_v2.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.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[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v2.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + for page in self.pages: + yield from page.list_findings_results + + 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.securitycenter_v2.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.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[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.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.securitycenter_v2.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_findings_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMuteConfigsPager: + """A pager for iterating through ``list_mute_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``mute_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMuteConfigs`` requests and continue to iterate + through the ``mute_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListMuteConfigsResponse], + request: securitycenter_service.ListMuteConfigsRequest, + response: securitycenter_service.ListMuteConfigsResponse, + *, + 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.securitycenter_v2.types.ListMuteConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListMuteConfigsResponse): + 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 = securitycenter_service.ListMuteConfigsRequest(request) + 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[securitycenter_service.ListMuteConfigsResponse]: + 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[mute_config.MuteConfig]: + for page in self.pages: + yield from page.mute_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMuteConfigsAsyncPager: + """A pager for iterating through ``list_mute_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``mute_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMuteConfigs`` requests and continue to iterate + through the ``mute_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` + attributes are available on the 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[securitycenter_service.ListMuteConfigsResponse]], + request: securitycenter_service.ListMuteConfigsRequest, + response: securitycenter_service.ListMuteConfigsResponse, + *, + 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.securitycenter_v2.types.ListMuteConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListMuteConfigsResponse): + 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 = securitycenter_service.ListMuteConfigsRequest(request) + 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[securitycenter_service.ListMuteConfigsResponse]: + 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[mute_config.MuteConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.mute_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v2.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + 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[securitycenter_service.ListNotificationConfigsResponse]: + 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[notification_config.NotificationConfig]: + for page in self.pages: + yield from page.notification_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsAsyncPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` + attributes are available on the 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[securitycenter_service.ListNotificationConfigsResponse]], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v2.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + 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[securitycenter_service.ListNotificationConfigsResponse]: + 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[notification_config.NotificationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.notification_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourceValueConfigsPager: + """A pager for iterating through ``list_resource_value_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resource_value_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListResourceValueConfigs`` requests and continue to iterate + through the ``resource_value_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListResourceValueConfigsResponse], + request: securitycenter_service.ListResourceValueConfigsRequest, + response: securitycenter_service.ListResourceValueConfigsResponse, + *, + 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.securitycenter_v2.types.ListResourceValueConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse): + 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 = securitycenter_service.ListResourceValueConfigsRequest(request) + 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[securitycenter_service.ListResourceValueConfigsResponse]: + 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[resource_value_config.ResourceValueConfig]: + for page in self.pages: + yield from page.resource_value_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourceValueConfigsAsyncPager: + """A pager for iterating through ``list_resource_value_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resource_value_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListResourceValueConfigs`` requests and continue to iterate + through the ``resource_value_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` + attributes are available on the 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[securitycenter_service.ListResourceValueConfigsResponse]], + request: securitycenter_service.ListResourceValueConfigsRequest, + response: securitycenter_service.ListResourceValueConfigsResponse, + *, + 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.securitycenter_v2.types.ListResourceValueConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse): + 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 = securitycenter_service.ListResourceValueConfigsRequest(request) + 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[securitycenter_service.ListResourceValueConfigsResponse]: + 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[resource_value_config.ResourceValueConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.resource_value_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v2.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` + attributes are available on the 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[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v2.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + 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[securitycenter_service.ListSourcesResponse]: + 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[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.sources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListValuedResourcesPager: + """A pager for iterating through ``list_valued_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``valued_resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListValuedResources`` requests and continue to iterate + through the ``valued_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., securitycenter_service.ListValuedResourcesResponse], + request: securitycenter_service.ListValuedResourcesRequest, + response: securitycenter_service.ListValuedResourcesResponse, + *, + 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.securitycenter_v2.types.ListValuedResourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListValuedResourcesResponse): + 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 = securitycenter_service.ListValuedResourcesRequest(request) + 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[securitycenter_service.ListValuedResourcesResponse]: + 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[valued_resource.ValuedResource]: + for page in self.pages: + yield from page.valued_resources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListValuedResourcesAsyncPager: + """A pager for iterating through ``list_valued_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``valued_resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListValuedResources`` requests and continue to iterate + through the ``valued_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` + attributes are available on the 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[securitycenter_service.ListValuedResourcesResponse]], + request: securitycenter_service.ListValuedResourcesRequest, + response: securitycenter_service.ListValuedResourcesResponse, + *, + 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.securitycenter_v2.types.ListValuedResourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListValuedResourcesResponse): + 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 = securitycenter_service.ListValuedResourcesRequest(request) + 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[securitycenter_service.ListValuedResourcesResponse]: + 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[valued_resource.ValuedResource]: + async def async_generator(): + async for page in self.pages: + for response in page.valued_resources: + 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-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py new file mode 100644 index 000000000000..9d36139c1a9b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/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 SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .rest import SecurityCenterRestTransport +from .rest import SecurityCenterRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry['grpc'] = SecurityCenterGrpcTransport +_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport +_transport_registry['rest'] = SecurityCenterRestTransport + +__all__ = ( + 'SecurityCenterTransport', + 'SecurityCenterGrpcTransport', + 'SecurityCenterGrpcAsyncIOTransport', + 'SecurityCenterRestTransport', + 'SecurityCenterRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py new file mode 100644 index 000000000000..817f5b747cd0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py @@ -0,0 +1,761 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.securitycenter_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.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.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource +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 empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'securitycenter.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.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: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials 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.batch_create_resource_value_configs: gapic_v1.method.wrap_method( + self.batch_create_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.bulk_mute_findings: gapic_v1.method.wrap_method( + self.bulk_mute_findings, + default_timeout=None, + client_info=client_info, + ), + self.create_big_query_export: gapic_v1.method.wrap_method( + self.create_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, + default_timeout=None, + client_info=client_info, + ), + self.create_mute_config: gapic_v1.method.wrap_method( + self.create_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method.wrap_method( + self.create_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.create_source: gapic_v1.method.wrap_method( + self.create_source, + default_timeout=None, + client_info=client_info, + ), + self.delete_big_query_export: gapic_v1.method.wrap_method( + self.delete_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.delete_mute_config: gapic_v1.method.wrap_method( + self.delete_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method.wrap_method( + self.delete_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_resource_value_config: gapic_v1.method.wrap_method( + self.delete_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_big_query_export: gapic_v1.method.wrap_method( + self.get_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.get_simulation: gapic_v1.method.wrap_method( + self.get_simulation, + default_timeout=None, + client_info=client_info, + ), + self.get_valued_resource: gapic_v1.method.wrap_method( + self.get_valued_resource, + default_timeout=None, + 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.get_mute_config: gapic_v1.method.wrap_method( + self.get_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.get_notification_config: gapic_v1.method.wrap_method( + self.get_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.get_resource_value_config: gapic_v1.method.wrap_method( + self.get_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_source: gapic_v1.method.wrap_method( + self.get_source, + default_timeout=None, + client_info=client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_findings, + default_timeout=None, + client_info=client_info, + ), + self.list_attack_paths: gapic_v1.method.wrap_method( + self.list_attack_paths, + default_timeout=None, + client_info=client_info, + ), + self.list_big_query_exports: gapic_v1.method.wrap_method( + self.list_big_query_exports, + default_timeout=None, + client_info=client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + default_timeout=None, + client_info=client_info, + ), + self.list_mute_configs: gapic_v1.method.wrap_method( + self.list_mute_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method.wrap_method( + self.list_notification_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_resource_value_configs: gapic_v1.method.wrap_method( + self.list_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_sources: gapic_v1.method.wrap_method( + self.list_sources, + default_timeout=None, + client_info=client_info, + ), + self.list_valued_resources: gapic_v1.method.wrap_method( + self.list_valued_resources, + default_timeout=None, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, + 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.set_mute: gapic_v1.method.wrap_method( + self.set_mute, + 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.update_big_query_export: gapic_v1.method.wrap_method( + self.update_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.update_external_system: gapic_v1.method.wrap_method( + self.update_external_system, + default_timeout=None, + client_info=client_info, + ), + self.update_finding: gapic_v1.method.wrap_method( + self.update_finding, + default_timeout=None, + client_info=client_info, + ), + self.update_mute_config: gapic_v1.method.wrap_method( + self.update_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method.wrap_method( + self.update_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.update_resource_value_config: gapic_v1.method.wrap_method( + self.update_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=None, + client_info=client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + Union[ + securitycenter_service.BatchCreateResourceValueConfigsResponse, + Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, + Awaitable[bigquery_export.BigQueryExport] + ]]: + raise NotImplementedError() + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + Union[ + gcs_mute_config.MuteConfig, + Awaitable[gcs_mute_config.MuteConfig] + ]]: + raise NotImplementedError() + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, + Awaitable[bigquery_export.BigQueryExport] + ]]: + raise NotImplementedError() + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + Union[ + simulation.Simulation, + Awaitable[simulation.Simulation] + ]]: + raise NotImplementedError() + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + Union[ + valued_resource.ValuedResource, + Awaitable[valued_resource.ValuedResource] + ]]: + 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 get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + Union[ + mute_config.MuteConfig, + Awaitable[mute_config.MuteConfig] + ]]: + raise NotImplementedError() + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Union[ + notification_config.NotificationConfig, + Awaitable[notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + Union[ + resource_value_config.ResourceValueConfig, + Awaitable[resource_value_config.ResourceValueConfig] + ]]: + raise NotImplementedError() + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Union[ + source.Source, + Awaitable[source.Source] + ]]: + raise NotImplementedError() + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Union[ + securitycenter_service.GroupFindingsResponse, + Awaitable[securitycenter_service.GroupFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + Union[ + securitycenter_service.ListAttackPathsResponse, + Awaitable[securitycenter_service.ListAttackPathsResponse] + ]]: + raise NotImplementedError() + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + Union[ + securitycenter_service.ListBigQueryExportsResponse, + Awaitable[securitycenter_service.ListBigQueryExportsResponse] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Union[ + securitycenter_service.ListFindingsResponse, + Awaitable[securitycenter_service.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + Union[ + securitycenter_service.ListMuteConfigsResponse, + Awaitable[securitycenter_service.ListMuteConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Union[ + securitycenter_service.ListNotificationConfigsResponse, + Awaitable[securitycenter_service.ListNotificationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + Union[ + securitycenter_service.ListResourceValueConfigsResponse, + Awaitable[securitycenter_service.ListResourceValueConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Union[ + securitycenter_service.ListSourcesResponse, + Awaitable[securitycenter_service.ListSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + Union[ + securitycenter_service.ListValuedResourcesResponse, + Awaitable[securitycenter_service.ListValuedResourcesResponse] + ]]: + raise NotImplementedError() + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + 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 set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + 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 update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, + Awaitable[bigquery_export.BigQueryExport] + ]]: + raise NotImplementedError() + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + Union[ + gcs_external_system.ExternalSystem, + Awaitable[gcs_external_system.ExternalSystem] + ]]: + raise NotImplementedError() + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + Union[ + gcs_mute_config.MuteConfig, + Awaitable[gcs_mute_config.MuteConfig] + ]]: + raise NotImplementedError() + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + Union[ + gcs_resource_value_config.ResourceValueConfig, + Awaitable[gcs_resource_value_config.ResourceValueConfig] + ]]: + raise NotImplementedError() + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Union[ + gcs_security_marks.SecurityMarks, + Awaitable[gcs_security_marks.SecurityMarks] + ]]: + raise NotImplementedError() + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SecurityCenterTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py new file mode 100644 index 000000000000..3ab2b66d9b6e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py @@ -0,0 +1,1452 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource +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 empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V2 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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 batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + securitycenter_service.BatchCreateResourceValueConfigsResponse]: + r"""Return a callable for the batch create resource value + configs method over gRPC. + + Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + Returns: + Callable[[~.BatchCreateResourceValueConfigsRequest], + ~.BatchCreateResourceValueConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: + self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/BatchCreateResourceValueConfigs', + request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, + ) + return self._stubs['batch_create_resource_value_configs'] + + @property + def bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + operations_pb2.Operation]: + r"""Return a callable for the bulk mute findings method over gRPC. + + Kicks off an LRO to bulk mute findings for a parent + based on a filter. If no location is specified, findings + are muted in global. The parent can be either an + organization, folder, or project. The findings matched + by the filter will be muted after the LRO is done. + + Returns: + Callable[[~.BulkMuteFindingsRequest], + ~.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 'bulk_mute_findings' not in self._stubs: + self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/BulkMuteFindings', + request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['bulk_mute_findings'] + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + r"""Return a callable for the create big query export method over gRPC. + + Creates a BigQuery export. + + Returns: + Callable[[~.CreateBigQueryExportRequest], + ~.BigQueryExport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateBigQueryExport', + request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['create_big_query_export'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding in a location. The corresponding + source must exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + r"""Return a callable for the create mute config method over gRPC. + + Creates a mute config. + + Returns: + Callable[[~.CreateMuteConfigRequest], + ~.MuteConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateMuteConfig', + request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['create_mute_config'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete big query export method over gRPC. + + Deletes an existing BigQuery export. + + Returns: + Callable[[~.DeleteBigQueryExportRequest], + ~.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_big_query_export' not in self._stubs: + self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteBigQueryExport', + request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_big_query_export'] + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete mute config method over gRPC. + + Deletes an existing mute config. If no location is + specified, default is global. + + Returns: + Callable[[~.DeleteMuteConfigRequest], + ~.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_mute_config' not in self._stubs: + self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteMuteConfig', + request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_mute_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + ~.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_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete resource value config method over gRPC. + + Deletes a ResourceValueConfig. + + Returns: + Callable[[~.DeleteResourceValueConfigRequest], + ~.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_resource_value_config' not in self._stubs: + self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteResourceValueConfig', + request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_resource_value_config'] + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + bigquery_export.BigQueryExport]: + r"""Return a callable for the get big query export method over gRPC. + + Gets a BigQuery export. + + Returns: + Callable[[~.GetBigQueryExportRequest], + ~.BigQueryExport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_big_query_export' not in self._stubs: + self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetBigQueryExport', + request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['get_big_query_export'] + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + simulation.Simulation]: + r"""Return a callable for the get simulation method over gRPC. + + Get the simulation by name or the latest simulation + for the given organization. + + Returns: + Callable[[~.GetSimulationRequest], + ~.Simulation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_simulation' not in self._stubs: + self._stubs['get_simulation'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetSimulation', + request_serializer=securitycenter_service.GetSimulationRequest.serialize, + response_deserializer=simulation.Simulation.deserialize, + ) + return self._stubs['get_simulation'] + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + valued_resource.ValuedResource]: + r"""Return a callable for the get valued resource method over gRPC. + + Get the valued resource by name + + Returns: + Callable[[~.GetValuedResourceRequest], + ~.ValuedResource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_valued_resource' not in self._stubs: + self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetValuedResource', + request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, + response_deserializer=valued_resource.ValuedResource.deserialize, + ) + return self._stubs['get_valued_resource'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v2.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + mute_config.MuteConfig]: + r"""Return a callable for the get mute config method over gRPC. + + Gets a mute config. If no location is specified, + default is global. + + Returns: + Callable[[~.GetMuteConfigRequest], + ~.MuteConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_mute_config' not in self._stubs: + self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetMuteConfig', + request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, + response_deserializer=mute_config.MuteConfig.deserialize, + ) + return self._stubs['get_mute_config'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + resource_value_config.ResourceValueConfig]: + r"""Return a callable for the get resource value config method over gRPC. + + Gets a ResourceValueConfig. + + Returns: + Callable[[~.GetResourceValueConfigRequest], + ~.ResourceValueConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_resource_value_config' not in self._stubs: + self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetResourceValueConfig', + request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, + response_deserializer=resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['get_resource_value_config'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties in a location. If no location is + specified, findings are assumed to be in global + + To group across all sources provide a ``-`` as the source id. + The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + - ``/v2/folders/{folder_id}/sources/-/findings`` + - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` + - ``/v2/projects/{project_id}/sources/-/findings`` + - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + securitycenter_service.ListAttackPathsResponse]: + r"""Return a callable for the list attack paths method over gRPC. + + Lists the attack paths for a set of simulation + results or valued resources and filter. + + Returns: + Callable[[~.ListAttackPathsRequest], + ~.ListAttackPathsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_attack_paths' not in self._stubs: + self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListAttackPaths', + request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, + response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, + ) + return self._stubs['list_attack_paths'] + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + securitycenter_service.ListBigQueryExportsResponse]: + r"""Return a callable for the list big query exports method over gRPC. + + Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are returned. + + Returns: + Callable[[~.ListBigQueryExportsRequest], + ~.ListBigQueryExportsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_big_query_exports' not in self._stubs: + self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListBigQueryExports', + request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, + response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, + ) + return self._stubs['list_big_query_exports'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources for a given location provide a ``-`` + as the source id. If no location is specified, finding are + assumed to be in global. The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + 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.securitycenter.v2.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + securitycenter_service.ListMuteConfigsResponse]: + r"""Return a callable for the list mute configs method over gRPC. + + Lists mute configs. If no location is specified, + default is global. + + Returns: + Callable[[~.ListMuteConfigsRequest], + ~.ListMuteConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_mute_configs' not in self._stubs: + self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListMuteConfigs', + request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, + ) + return self._stubs['list_mute_configs'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + ~.ListNotificationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + securitycenter_service.ListResourceValueConfigsResponse]: + r"""Return a callable for the list resource value configs method over gRPC. + + Lists all ResourceValueConfigs. + + Returns: + Callable[[~.ListResourceValueConfigsRequest], + ~.ListResourceValueConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_resource_value_configs' not in self._stubs: + self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListResourceValueConfigs', + request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, + ) + return self._stubs['list_resource_value_configs'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + securitycenter_service.ListValuedResourcesResponse]: + r"""Return a callable for the list valued resources method over gRPC. + + Lists the valued resources for a set of simulation + results and filter. + + Returns: + Callable[[~.ListValuedResourcesRequest], + ~.ListValuedResourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_valued_resources' not in self._stubs: + self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListValuedResources', + request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, + response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, + ) + return self._stubs['list_valued_resources'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. If no location is + specified, finding is assumed to be in global + + Returns: + Callable[[~.SetFindingStateRequest], + ~.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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v2.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + finding.Finding]: + r"""Return a callable for the set mute method over gRPC. + + Updates the mute state of a finding. If no location + is specified, finding is assumed to be in global + + Returns: + Callable[[~.SetMuteRequest], + ~.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 'set_mute' not in self._stubs: + self._stubs['set_mute'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/SetMute', + request_serializer=securitycenter_service.SetMuteRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_mute'] + + @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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v2.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + r"""Return a callable for the update big query export method over gRPC. + + Updates a BigQuery export. + + Returns: + Callable[[~.UpdateBigQueryExportRequest], + ~.BigQueryExport]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateBigQueryExport', + request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['update_big_query_export'] + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + gcs_external_system.ExternalSystem]: + r"""Return a callable for the update external system method over gRPC. + + Updates external system. This is for a given finding. + If no location is specified, finding is assumed to be in + global + + Returns: + Callable[[~.UpdateExternalSystemRequest], + ~.ExternalSystem]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_external_system' not in self._stubs: + self._stubs['update_external_system'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateExternalSystem', + request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, + response_deserializer=gcs_external_system.ExternalSystem.deserialize, + ) + return self._stubs['update_external_system'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. If no location is + specified, finding is assumed to be in global. The + corresponding source must exist for a finding creation + to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + r"""Return a callable for the update mute config method over gRPC. + + Updates a mute config. If no location is specified, + default is global. + + Returns: + Callable[[~.UpdateMuteConfigRequest], + ~.MuteConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateMuteConfig', + request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['update_mute_config'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + gcs_resource_value_config.ResourceValueConfig]: + r"""Return a callable for the update resource value config method over gRPC. + + Updates an existing ResourceValueConfigs with new + rules. + + Returns: + Callable[[~.UpdateResourceValueConfigRequest], + ~.ResourceValueConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: + self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateResourceValueConfig', + request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, + response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['update_resource_value_config'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. For Finding Security marks, + if no location is specified, finding is assumed to be in + global. Assets Security Marks can only be accessed + through global endpoint. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + 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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SecurityCenterGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 000000000000..b83a55a9f90c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,1657 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 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.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource +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 empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V2 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be 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._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 batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse]]: + r"""Return a callable for the batch create resource value + configs method over gRPC. + + Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + Returns: + Callable[[~.BatchCreateResourceValueConfigsRequest], + Awaitable[~.BatchCreateResourceValueConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: + self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/BatchCreateResourceValueConfigs', + request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, + ) + return self._stubs['batch_create_resource_value_configs'] + + @property + def bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the bulk mute findings method over gRPC. + + Kicks off an LRO to bulk mute findings for a parent + based on a filter. If no location is specified, findings + are muted in global. The parent can be either an + organization, folder, or project. The findings matched + by the filter will be muted after the LRO is done. + + Returns: + Callable[[~.BulkMuteFindingsRequest], + 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 'bulk_mute_findings' not in self._stubs: + self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/BulkMuteFindings', + request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['bulk_mute_findings'] + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport]]: + r"""Return a callable for the create big query export method over gRPC. + + Creates a BigQuery export. + + Returns: + Callable[[~.CreateBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateBigQueryExport', + request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['create_big_query_export'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding in a location. The corresponding + source must exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + 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 'create_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + Awaitable[gcs_mute_config.MuteConfig]]: + r"""Return a callable for the create mute config method over gRPC. + + Creates a mute config. + + Returns: + Callable[[~.CreateMuteConfigRequest], + Awaitable[~.MuteConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateMuteConfig', + request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['create_mute_config'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete big query export method over gRPC. + + Deletes an existing BigQuery export. + + Returns: + Callable[[~.DeleteBigQueryExportRequest], + 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_big_query_export' not in self._stubs: + self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteBigQueryExport', + request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_big_query_export'] + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete mute config method over gRPC. + + Deletes an existing mute config. If no location is + specified, default is global. + + Returns: + Callable[[~.DeleteMuteConfigRequest], + 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_mute_config' not in self._stubs: + self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteMuteConfig', + request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_mute_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + 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_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete resource value config method over gRPC. + + Deletes a ResourceValueConfig. + + Returns: + Callable[[~.DeleteResourceValueConfigRequest], + 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_resource_value_config' not in self._stubs: + self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/DeleteResourceValueConfig', + request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_resource_value_config'] + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport]]: + r"""Return a callable for the get big query export method over gRPC. + + Gets a BigQuery export. + + Returns: + Callable[[~.GetBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_big_query_export' not in self._stubs: + self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetBigQueryExport', + request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['get_big_query_export'] + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + Awaitable[simulation.Simulation]]: + r"""Return a callable for the get simulation method over gRPC. + + Get the simulation by name or the latest simulation + for the given organization. + + Returns: + Callable[[~.GetSimulationRequest], + Awaitable[~.Simulation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_simulation' not in self._stubs: + self._stubs['get_simulation'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetSimulation', + request_serializer=securitycenter_service.GetSimulationRequest.serialize, + response_deserializer=simulation.Simulation.deserialize, + ) + return self._stubs['get_simulation'] + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + Awaitable[valued_resource.ValuedResource]]: + r"""Return a callable for the get valued resource method over gRPC. + + Get the valued resource by name + + Returns: + Callable[[~.GetValuedResourceRequest], + Awaitable[~.ValuedResource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_valued_resource' not in self._stubs: + self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetValuedResource', + request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, + response_deserializer=valued_resource.ValuedResource.deserialize, + ) + return self._stubs['get_valued_resource'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v2.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + Awaitable[mute_config.MuteConfig]]: + r"""Return a callable for the get mute config method over gRPC. + + Gets a mute config. If no location is specified, + default is global. + + Returns: + Callable[[~.GetMuteConfigRequest], + Awaitable[~.MuteConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_mute_config' not in self._stubs: + self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetMuteConfig', + request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, + response_deserializer=mute_config.MuteConfig.deserialize, + ) + return self._stubs['get_mute_config'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Awaitable[notification_config.NotificationConfig]]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + Awaitable[resource_value_config.ResourceValueConfig]]: + r"""Return a callable for the get resource value config method over gRPC. + + Gets a ResourceValueConfig. + + Returns: + Callable[[~.GetResourceValueConfigRequest], + Awaitable[~.ResourceValueConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_resource_value_config' not in self._stubs: + self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetResourceValueConfig', + request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, + response_deserializer=resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['get_resource_value_config'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse]]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties in a location. If no location is + specified, findings are assumed to be in global + + To group across all sources provide a ``-`` as the source id. + The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + - ``/v2/folders/{folder_id}/sources/-/findings`` + - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` + - ``/v2/projects/{project_id}/sources/-/findings`` + - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + Awaitable[securitycenter_service.ListAttackPathsResponse]]: + r"""Return a callable for the list attack paths method over gRPC. + + Lists the attack paths for a set of simulation + results or valued resources and filter. + + Returns: + Callable[[~.ListAttackPathsRequest], + Awaitable[~.ListAttackPathsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_attack_paths' not in self._stubs: + self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListAttackPaths', + request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, + response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, + ) + return self._stubs['list_attack_paths'] + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + Awaitable[securitycenter_service.ListBigQueryExportsResponse]]: + r"""Return a callable for the list big query exports method over gRPC. + + Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are returned. + + Returns: + Callable[[~.ListBigQueryExportsRequest], + Awaitable[~.ListBigQueryExportsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_big_query_exports' not in self._stubs: + self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListBigQueryExports', + request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, + response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, + ) + return self._stubs['list_big_query_exports'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources for a given location provide a ``-`` + as the source id. If no location is specified, finding are + assumed to be in global. The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + 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.securitycenter.v2.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + Awaitable[securitycenter_service.ListMuteConfigsResponse]]: + r"""Return a callable for the list mute configs method over gRPC. + + Lists mute configs. If no location is specified, + default is global. + + Returns: + Callable[[~.ListMuteConfigsRequest], + Awaitable[~.ListMuteConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_mute_configs' not in self._stubs: + self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListMuteConfigs', + request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, + ) + return self._stubs['list_mute_configs'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + Awaitable[~.ListNotificationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + Awaitable[securitycenter_service.ListResourceValueConfigsResponse]]: + r"""Return a callable for the list resource value configs method over gRPC. + + Lists all ResourceValueConfigs. + + Returns: + Callable[[~.ListResourceValueConfigsRequest], + Awaitable[~.ListResourceValueConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_resource_value_configs' not in self._stubs: + self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListResourceValueConfigs', + request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, + ) + return self._stubs['list_resource_value_configs'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse]]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + Awaitable[securitycenter_service.ListValuedResourcesResponse]]: + r"""Return a callable for the list valued resources method over gRPC. + + Lists the valued resources for a set of simulation + results and filter. + + Returns: + Callable[[~.ListValuedResourcesRequest], + Awaitable[~.ListValuedResourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_valued_resources' not in self._stubs: + self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/ListValuedResources', + request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, + response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, + ) + return self._stubs['list_valued_resources'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. If no location is + specified, finding is assumed to be in global + + Returns: + Callable[[~.SetFindingStateRequest], + 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 'set_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.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.cloud.securitycenter.v2.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set mute method over gRPC. + + Updates the mute state of a finding. If no location + is specified, finding is assumed to be in global + + Returns: + Callable[[~.SetMuteRequest], + 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 'set_mute' not in self._stubs: + self._stubs['set_mute'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/SetMute', + request_serializer=securitycenter_service.SetMuteRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_mute'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.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.cloud.securitycenter.v2.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport]]: + r"""Return a callable for the update big query export method over gRPC. + + Updates a BigQuery export. + + Returns: + Callable[[~.UpdateBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: + self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateBigQueryExport', + request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs['update_big_query_export'] + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + Awaitable[gcs_external_system.ExternalSystem]]: + r"""Return a callable for the update external system method over gRPC. + + Updates external system. This is for a given finding. + If no location is specified, finding is assumed to be in + global + + Returns: + Callable[[~.UpdateExternalSystemRequest], + Awaitable[~.ExternalSystem]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_external_system' not in self._stubs: + self._stubs['update_external_system'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateExternalSystem', + request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, + response_deserializer=gcs_external_system.ExternalSystem.deserialize, + ) + return self._stubs['update_external_system'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. If no location is + specified, finding is assumed to be in global. The + corresponding source must exist for a finding creation + to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + 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 'update_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + Awaitable[gcs_mute_config.MuteConfig]]: + r"""Return a callable for the update mute config method over gRPC. + + Updates a mute config. If no location is specified, + default is global. + + Returns: + Callable[[~.UpdateMuteConfigRequest], + Awaitable[~.MuteConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mute_config' not in self._stubs: + self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateMuteConfig', + request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs['update_mute_config'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + Awaitable[gcs_resource_value_config.ResourceValueConfig]]: + r"""Return a callable for the update resource value config method over gRPC. + + Updates an existing ResourceValueConfigs with new + rules. + + Returns: + Callable[[~.UpdateResourceValueConfigRequest], + Awaitable[~.ResourceValueConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: + self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateResourceValueConfig', + request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, + response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs['update_resource_value_config'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks]]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. For Finding Security marks, + if no location is specified, finding is assumed to be in + global. Assets Security Marks can only be accessed + through global endpoint. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_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.batch_create_resource_value_configs: gapic_v1.method_async.wrap_method( + self.batch_create_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.bulk_mute_findings: gapic_v1.method_async.wrap_method( + self.bulk_mute_findings, + default_timeout=None, + client_info=client_info, + ), + self.create_big_query_export: gapic_v1.method_async.wrap_method( + self.create_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.create_finding: gapic_v1.method_async.wrap_method( + self.create_finding, + default_timeout=None, + client_info=client_info, + ), + self.create_mute_config: gapic_v1.method_async.wrap_method( + self.create_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method_async.wrap_method( + self.create_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.create_source: gapic_v1.method_async.wrap_method( + self.create_source, + default_timeout=None, + client_info=client_info, + ), + self.delete_big_query_export: gapic_v1.method_async.wrap_method( + self.delete_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.delete_mute_config: gapic_v1.method_async.wrap_method( + self.delete_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method_async.wrap_method( + self.delete_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_resource_value_config: gapic_v1.method_async.wrap_method( + self.delete_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_big_query_export: gapic_v1.method_async.wrap_method( + self.get_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.get_simulation: gapic_v1.method_async.wrap_method( + self.get_simulation, + default_timeout=None, + client_info=client_info, + ), + self.get_valued_resource: gapic_v1.method_async.wrap_method( + self.get_valued_resource, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_mute_config: gapic_v1.method_async.wrap_method( + self.get_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.get_notification_config: gapic_v1.method_async.wrap_method( + self.get_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.get_resource_value_config: gapic_v1.method_async.wrap_method( + self.get_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_source: gapic_v1.method_async.wrap_method( + self.get_source, + default_timeout=None, + client_info=client_info, + ), + self.group_findings: gapic_v1.method_async.wrap_method( + self.group_findings, + default_timeout=None, + client_info=client_info, + ), + self.list_attack_paths: gapic_v1.method_async.wrap_method( + self.list_attack_paths, + default_timeout=None, + client_info=client_info, + ), + self.list_big_query_exports: gapic_v1.method_async.wrap_method( + self.list_big_query_exports, + default_timeout=None, + client_info=client_info, + ), + self.list_findings: gapic_v1.method_async.wrap_method( + self.list_findings, + default_timeout=None, + client_info=client_info, + ), + self.list_mute_configs: gapic_v1.method_async.wrap_method( + self.list_mute_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method_async.wrap_method( + self.list_notification_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_resource_value_configs: gapic_v1.method_async.wrap_method( + self.list_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_sources: gapic_v1.method_async.wrap_method( + self.list_sources, + default_timeout=None, + client_info=client_info, + ), + self.list_valued_resources: gapic_v1.method_async.wrap_method( + self.list_valued_resources, + default_timeout=None, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method_async.wrap_method( + self.set_finding_state, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_mute: gapic_v1.method_async.wrap_method( + self.set_mute, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.update_big_query_export: gapic_v1.method_async.wrap_method( + self.update_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.update_external_system: gapic_v1.method_async.wrap_method( + self.update_external_system, + default_timeout=None, + client_info=client_info, + ), + self.update_finding: gapic_v1.method_async.wrap_method( + self.update_finding, + default_timeout=None, + client_info=client_info, + ), + self.update_mute_config: gapic_v1.method_async.wrap_method( + self.update_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method_async.wrap_method( + self.update_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.update_resource_value_config: gapic_v1.method_async.wrap_method( + self.update_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method_async.wrap_method( + self.update_security_marks, + default_timeout=None, + client_info=client_info, + ), + self.update_source: gapic_v1.method_async.wrap_method( + self.update_source, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return 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"] + + +__all__ = ( + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py new file mode 100644 index 000000000000..251cc55815bd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py @@ -0,0 +1,5820 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # 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 path_template +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 +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SecurityCenterRestInterceptor: + """Interceptor for SecurityCenter. + + 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 SecurityCenterRestTransport. + + .. code-block:: python + class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): + def pre_batch_create_resource_value_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_resource_value_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_bulk_mute_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_bulk_mute_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_resource_value_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_simulation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_simulation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_valued_resource(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_valued_resource(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_attack_paths(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_attack_paths(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_big_query_exports(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_big_query_exports(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_mute_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_mute_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_notification_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_notification_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_resource_value_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_resource_value_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_valued_resources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_valued_resources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_finding_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_finding_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_mute(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_mute(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_external_system(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_external_system(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_resource_value_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_security_marks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_security_marks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_source(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) + client = SecurityCenterClient(transport=transport) + + + """ + def pre_batch_create_resource_value_configs(self, request: securitycenter_service.BatchCreateResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BatchCreateResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_create_resource_value_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_batch_create_resource_value_configs(self, response: securitycenter_service.BatchCreateResourceValueConfigsResponse) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + """Post-rpc interceptor for batch_create_resource_value_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_bulk_mute_findings(self, request: securitycenter_service.BulkMuteFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BulkMuteFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for bulk_mute_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_bulk_mute_findings(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for bulk_mute_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_big_query_export(self, request: securitycenter_service.CreateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for create_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for create_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_mute_config(self, request: securitycenter_service.CreateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: + """Post-rpc interceptor for create_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_notification_config(self, request: securitycenter_service.CreateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for create_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_delete_big_query_export(self, request: securitycenter_service.DeleteBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_mute_config(self, request: securitycenter_service.DeleteMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_notification_config(self, request: securitycenter_service.DeleteNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_resource_value_config(self, request: securitycenter_service.DeleteResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteResourceValueConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_get_big_query_export(self, request: securitycenter_service.GetBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for get_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_mute_config(self, request: securitycenter_service.GetMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_mute_config(self, response: mute_config.MuteConfig) -> mute_config.MuteConfig: + """Post-rpc interceptor for get_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_notification_config(self, request: securitycenter_service.GetNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_notification_config(self, response: notification_config.NotificationConfig) -> notification_config.NotificationConfig: + """Post-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_resource_value_config(self, request: securitycenter_service.GetResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetResourceValueConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_resource_value_config(self, response: resource_value_config.ResourceValueConfig) -> resource_value_config.ResourceValueConfig: + """Post-rpc interceptor for get_resource_value_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_simulation(self, request: securitycenter_service.GetSimulationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSimulationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_simulation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_simulation(self, response: simulation.Simulation) -> simulation.Simulation: + """Post-rpc interceptor for get_simulation + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_source(self, response: source.Source) -> source.Source: + """Post-rpc interceptor for get_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_get_valued_resource(self, request: securitycenter_service.GetValuedResourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetValuedResourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_valued_resource + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_valued_resource(self, response: valued_resource.ValuedResource) -> valued_resource.ValuedResource: + """Post-rpc interceptor for get_valued_resource + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: + """Post-rpc interceptor for group_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_attack_paths(self, request: securitycenter_service.ListAttackPathsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAttackPathsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_attack_paths + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_attack_paths(self, response: securitycenter_service.ListAttackPathsResponse) -> securitycenter_service.ListAttackPathsResponse: + """Post-rpc interceptor for list_attack_paths + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_big_query_exports(self, request: securitycenter_service.ListBigQueryExportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListBigQueryExportsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_big_query_exports + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_big_query_exports(self, response: securitycenter_service.ListBigQueryExportsResponse) -> securitycenter_service.ListBigQueryExportsResponse: + """Post-rpc interceptor for list_big_query_exports + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. + """ + return request, metadata + + def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_mute_configs(self, request: securitycenter_service.ListMuteConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListMuteConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_mute_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_mute_configs(self, response: securitycenter_service.ListMuteConfigsResponse) -> securitycenter_service.ListMuteConfigsResponse: + """Post-rpc interceptor for list_mute_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_notification_configs(self, request: securitycenter_service.ListNotificationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListNotificationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_notification_configs(self, response: securitycenter_service.ListNotificationConfigsResponse) -> securitycenter_service.ListNotificationConfigsResponse: + """Post-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_resource_value_configs(self, request: securitycenter_service.ListResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_resource_value_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_resource_value_configs(self, response: securitycenter_service.ListResourceValueConfigsResponse) -> securitycenter_service.ListResourceValueConfigsResponse: + """Post-rpc interceptor for list_resource_value_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_sources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: + """Post-rpc interceptor for list_sources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_list_valued_resources(self, request: securitycenter_service.ListValuedResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListValuedResourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_valued_resources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_valued_resources(self, response: securitycenter_service.ListValuedResourcesResponse) -> securitycenter_service.ListValuedResourcesResponse: + """Post-rpc interceptor for list_valued_resources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_set_mute(self, request: securitycenter_service.SetMuteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetMuteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_mute + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_mute(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_mute + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_big_query_export(self, request: securitycenter_service.UpdateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateBigQueryExportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for update_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_external_system(self, request: securitycenter_service.UpdateExternalSystemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateExternalSystemRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_external_system + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_external_system(self, response: gcs_external_system.ExternalSystem) -> gcs_external_system.ExternalSystem: + """Post-rpc interceptor for update_external_system + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for update_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_mute_config(self, request: securitycenter_service.UpdateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: + """Post-rpc interceptor for update_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_notification_config(self, request: securitycenter_service.UpdateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateNotificationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_resource_value_config(self, request: securitycenter_service.UpdateResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateResourceValueConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_resource_value_config(self, response: gcs_resource_value_config.ResourceValueConfig) -> gcs_resource_value_config.ResourceValueConfig: + """Post-rpc interceptor for update_resource_value_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: + """Post-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for update_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SecurityCenterRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SecurityCenterRestInterceptor + + +class SecurityCenterRestTransport(SecurityCenterTransport): + """REST backend transport for SecurityCenter. + + V2 APIs for Security Center 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 = 'securitycenter.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[SecurityCenterRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the 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 + 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 + ) + 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 SecurityCenterRestInterceptor() + 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': '/v2/{name=organizations/*/operations/*}:cancel', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v2/{name=organizations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v2/{name=organizations/*/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="v2") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _BatchCreateResourceValueConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("BatchCreateResourceValueConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.BatchCreateResourceValueConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Call the batch create resource + value configs method over HTTP. + + Args: + request (~.securitycenter_service.BatchCreateResourceValueConfigsRequest): + The request object. Request message to create multiple + resource value configs + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*}/resourceValueConfigs:batchCreate', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/locations/*}/resourceValueConfigs:batchCreate', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_batch_create_resource_value_configs(request, metadata) + pb_request = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.BatchCreateResourceValueConfigsResponse() + pb_resp = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_create_resource_value_configs(resp) + return resp + + class _BulkMuteFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("BulkMuteFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.BulkMuteFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the bulk mute findings method over HTTP. + + Args: + request (~.securitycenter_service.BulkMuteFindingsRequest): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/locations/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*/locations/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*}/findings:bulkMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*/locations/*}/findings:bulkMute', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_bulk_mute_findings(request, metadata) + pb_request = securitycenter_service.BulkMuteFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_bulk_mute_findings(resp) + return resp + + class _CreateBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "bigQueryExportId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> bigquery_export.BigQueryExport: + r"""Call the create big query export method over HTTP. + + Args: + request (~.securitycenter_service.CreateBigQueryExportRequest): + The request object. Request message for creating a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/locations/*}/bigQueryExports', + 'body': 'big_query_export', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*/locations/*}/bigQueryExports', + 'body': 'big_query_export', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*/locations/*}/bigQueryExports', + 'body': 'big_query_export', + }, + ] + request, metadata = self._interceptor.pre_create_big_query_export(request, metadata) + pb_request = securitycenter_service.CreateBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_big_query_export(resp) + return resp + + class _CreateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "findingId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the create finding method over HTTP. + + Args: + request (~.securitycenter_service.CreateFindingRequest): + The request object. Request message for creating a + finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/sources/*/locations/*}/findings', + 'body': 'finding', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/sources/*}/findings', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_create_finding(request, metadata) + pb_request = securitycenter_service.CreateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_finding(resp) + return resp + + class _CreateMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "muteConfigId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_mute_config.MuteConfig: + r"""Call the create mute config method over HTTP. + + Args: + request (~.securitycenter_service.CreateMuteConfigRequest): + The request object. Request message for creating a mute + config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/locations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*/locations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*/locations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*}/muteConfigs', + 'body': 'mute_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*}/muteConfigs', + 'body': 'mute_config', + }, + ] + request, metadata = self._interceptor.pre_create_mute_config(request, metadata) + pb_request = securitycenter_service.CreateMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_mute_config.MuteConfig() + pb_resp = gcs_mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_mute_config(resp) + return resp + + class _CreateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "configId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the create notification + config method over HTTP. + + Args: + request (~.securitycenter_service.CreateNotificationConfigRequest): + The request object. Request message for creating a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/locations/*}/notificationConfigs', + 'body': 'notification_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*/locations/*}/notificationConfigs', + 'body': 'notification_config', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*/locations/*}/notificationConfigs', + 'body': 'notification_config', + }, + ] + request, metadata = self._interceptor.pre_create_notification_config(request, metadata) + pb_request = securitycenter_service.CreateNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_notification_config(resp) + return resp + + class _CreateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.CreateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the create source method over HTTP. + + Args: + request (~.securitycenter_service.CreateSourceRequest): + The request object. Request message for creating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*}/sources', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_create_source(request, metadata) + pb_request = securitycenter_service.CreateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_source(resp) + return resp + + class _DeleteBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete big query export method over HTTP. + + Args: + request (~.securitycenter_service.DeleteBigQueryExportRequest): + The request object. Request message for deleting a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/locations/*/bigQueryExports/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=folders/*/locations/*/bigQueryExports/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=projects/*/locations/*/bigQueryExports/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_big_query_export(request, metadata) + pb_request = securitycenter_service.DeleteBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete mute config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteMuteConfigRequest): + The request object. Request message for deleting a mute + config. If no location is specified, + default is global. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=folders/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=folders/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=projects/*/muteConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=projects/*/locations/*/muteConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_mute_config(request, metadata) + pb_request = securitycenter_service.DeleteMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete notification + config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteNotificationConfigRequest): + The request object. Request message for deleting a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/locations/*/notificationConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=folders/*/locations/*/notificationConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=projects/*/locations/*/notificationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_notification_config(request, metadata) + pb_request = securitycenter_service.DeleteNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _DeleteResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteResourceValueConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.DeleteResourceValueConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete resource value + config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteResourceValueConfigRequest): + The request object. Request message to delete resource + value config + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/resourceValueConfigs/*}', + }, +{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/locations/*/resourceValueConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_resource_value_config(request, metadata) + pb_request = securitycenter_service.DeleteResourceValueConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 _GetBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("GetBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> bigquery_export.BigQueryExport: + r"""Call the get big query export method over HTTP. + + Args: + request (~.securitycenter_service.GetBigQueryExportRequest): + The request object. Request message for retrieving a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/locations/*/bigQueryExports/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=folders/*/locations/*/bigQueryExports/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=projects/*/locations/*/bigQueryExports/*}', + }, + ] + request, metadata = self._interceptor.pre_get_big_query_export(request, metadata) + pb_request = securitycenter_service.GetBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_big_query_export(resp) + return resp + + class _GetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{resource=organizations/*/sources/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> mute_config.MuteConfig: + r"""Call the get mute config method over HTTP. + + Args: + request (~.securitycenter_service.GetMuteConfigRequest): + The request object. Request message for retrieving a mute + config. If no location is specified, + default is global. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=folders/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=folders/*/locations/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=projects/*/muteConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=projects/*/locations/*/muteConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_mute_config(request, metadata) + pb_request = securitycenter_service.GetMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = mute_config.MuteConfig() + pb_resp = mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_mute_config(resp) + return resp + + class _GetNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> notification_config.NotificationConfig: + r"""Call the get notification config method over HTTP. + + Args: + request (~.securitycenter_service.GetNotificationConfigRequest): + The request object. Request message for getting a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/locations/*/notificationConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=folders/*/locations/*/notificationConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=projects/*/locations/*/notificationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_notification_config(request, metadata) + pb_request = securitycenter_service.GetNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = notification_config.NotificationConfig() + pb_resp = notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_notification_config(resp) + return resp + + class _GetResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetResourceValueConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetResourceValueConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resource_value_config.ResourceValueConfig: + r"""Call the get resource value config method over HTTP. + + Args: + request (~.securitycenter_service.GetResourceValueConfigRequest): + The request object. Request message to get resource value + config + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resource_value_config.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/resourceValueConfigs/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/locations/*/resourceValueConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_resource_value_config(request, metadata) + pb_request = securitycenter_service.GetResourceValueConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resource_value_config.ResourceValueConfig() + pb_resp = resource_value_config.ResourceValueConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_resource_value_config(resp) + return resp + + class _GetSimulation(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSimulation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSimulationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> simulation.Simulation: + r"""Call the get simulation method over HTTP. + + Args: + request (~.securitycenter_service.GetSimulationRequest): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.simulation.Simulation: + Attack path simulation + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/simulations/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/locations/*/simulations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_simulation(request, metadata) + pb_request = securitycenter_service.GetSimulationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = simulation.Simulation() + pb_resp = simulation.Simulation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_simulation(resp) + return resp + + class _GetSource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> source.Source: + r"""Call the get source method over HTTP. + + Args: + request (~.securitycenter_service.GetSourceRequest): + The request object. Request message for getting a source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/sources/*}', + }, + ] + request, metadata = self._interceptor.pre_get_source(request, metadata) + pb_request = securitycenter_service.GetSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = source.Source() + pb_resp = source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_source(resp) + return resp + + class _GetValuedResource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetValuedResource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GetValuedResourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> valued_resource.ValuedResource: + r"""Call the get valued resource method over HTTP. + + Args: + request (~.securitycenter_service.GetValuedResourceRequest): + The request object. Request message for getting a valued + resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.valued_resource.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/simulations/*/valuedResources/*}', + }, +{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/locations/*/simulations/*/valuedResources/*}', + }, + ] + request, metadata = self._interceptor.pre_get_valued_resource(request, metadata) + pb_request = securitycenter_service.GetValuedResourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = valued_resource.ValuedResource() + pb_resp = valued_resource.ValuedResource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_valued_resource(resp) + return resp + + class _GroupFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.GroupFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.GroupFindingsResponse: + r"""Call the group findings method over HTTP. + + Args: + request (~.securitycenter_service.GroupFindingsRequest): + The request object. Request message for grouping by + findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.GroupFindingsResponse: + Response message for group by + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=organizations/*/sources/*/locations/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=folders/*/sources/*/locations/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*/sources/*}/findings:group', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{parent=projects/*/sources/*/locations/*}/findings:group', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_group_findings(request, metadata) + pb_request = securitycenter_service.GroupFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.GroupFindingsResponse() + pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_findings(resp) + return resp + + class _ListAttackPaths(SecurityCenterRestStub): + def __hash__(self): + return hash("ListAttackPaths") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListAttackPathsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListAttackPathsResponse: + r"""Call the list attack paths method over HTTP. + + Args: + request (~.securitycenter_service.ListAttackPathsRequest): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListAttackPathsResponse: + Response message for listing the + attack paths for a given simulation or + valued resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/simulations/*}/attackPaths', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/simulations/*/valuedResources/*}/attackPaths', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/locations/*/simulations/*/valuedResources/*}/attackPaths', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/simulations/*/attackExposureResults/*}/attackPaths', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/locations/*/simulations/*/attackExposureResults/*}/attackPaths', + }, + ] + request, metadata = self._interceptor.pre_list_attack_paths(request, metadata) + pb_request = securitycenter_service.ListAttackPathsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListAttackPathsResponse() + pb_resp = securitycenter_service.ListAttackPathsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_attack_paths(resp) + return resp + + class _ListBigQueryExports(SecurityCenterRestStub): + def __hash__(self): + return hash("ListBigQueryExports") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListBigQueryExportsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListBigQueryExportsResponse: + r"""Call the list big query exports method over HTTP. + + Args: + request (~.securitycenter_service.ListBigQueryExportsRequest): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or 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: + ~.securitycenter_service.ListBigQueryExportsResponse: + Response message for listing BigQuery + exports. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/locations/*}/bigQueryExports', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*/locations/*}/bigQueryExports', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*/locations/*}/bigQueryExports', + }, + ] + request, metadata = self._interceptor.pre_list_big_query_exports(request, metadata) + pb_request = securitycenter_service.ListBigQueryExportsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListBigQueryExportsResponse() + pb_resp = securitycenter_service.ListBigQueryExportsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_big_query_exports(resp) + return resp + + class _ListFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("ListFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListFindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.securitycenter_service.ListFindingsRequest): + The request object. Request message for listing findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListFindingsResponse: + Response message for listing + findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/sources/*/locations/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*/sources/*/locations/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*/sources/*}/findings', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*/sources/*/locations/*}/findings', + }, + ] + request, metadata = self._interceptor.pre_list_findings(request, metadata) + pb_request = securitycenter_service.ListFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListFindingsResponse() + pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListMuteConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListMuteConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListMuteConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListMuteConfigsResponse: + r"""Call the list mute configs method over HTTP. + + Args: + request (~.securitycenter_service.ListMuteConfigsRequest): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or project. If no + location is specified, default is + global. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListMuteConfigsResponse: + Response message for listing mute + configs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/locations/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*/locations/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*}/muteConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*/locations/*}/muteConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_mute_configs(request, metadata) + pb_request = securitycenter_service.ListMuteConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListMuteConfigsResponse() + pb_resp = securitycenter_service.ListMuteConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_mute_configs(resp) + return resp + + class _ListNotificationConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListNotificationConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListNotificationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListNotificationConfigsResponse: + r"""Call the list notification configs method over HTTP. + + Args: + request (~.securitycenter_service.ListNotificationConfigsRequest): + The request object. Request message for listing + notification configs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListNotificationConfigsResponse: + Response message for listing + notification configs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/locations/*}/notificationConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*/locations/*}/notificationConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*/locations/*}/notificationConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_notification_configs(request, metadata) + pb_request = securitycenter_service.ListNotificationConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListNotificationConfigsResponse() + pb_resp = securitycenter_service.ListNotificationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_notification_configs(resp) + return resp + + class _ListResourceValueConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListResourceValueConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListResourceValueConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListResourceValueConfigsResponse: + r"""Call the list resource value + configs method over HTTP. + + Args: + request (~.securitycenter_service.ListResourceValueConfigsRequest): + The request object. Request message to list resource + value configs of a parent + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListResourceValueConfigsResponse: + Response message to list resource + value configs + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*}/resourceValueConfigs', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/locations/*}/resourceValueConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_resource_value_configs(request, metadata) + pb_request = securitycenter_service.ListResourceValueConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListResourceValueConfigsResponse() + pb_resp = securitycenter_service.ListResourceValueConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_resource_value_configs(resp) + return resp + + class _ListSources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListSources") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListSourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListSourcesResponse: + r"""Call the list sources method over HTTP. + + Args: + request (~.securitycenter_service.ListSourcesRequest): + The request object. Request message for listing sources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListSourcesResponse: + Response message for listing sources. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*}/sources', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=folders/*}/sources', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=projects/*}/sources', + }, + ] + request, metadata = self._interceptor.pre_list_sources(request, metadata) + pb_request = securitycenter_service.ListSourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListSourcesResponse() + pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sources(resp) + return resp + + class _ListValuedResources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListValuedResources") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.ListValuedResourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> securitycenter_service.ListValuedResourcesResponse: + r"""Call the list valued resources method over HTTP. + + Args: + request (~.securitycenter_service.ListValuedResourcesRequest): + The request object. Request message for listing the + valued resources for a given simulation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.securitycenter_service.ListValuedResourcesResponse: + Response message for listing the + valued resources for a given simulation. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/simulations/*}/valuedResources', + }, +{ + 'method': 'get', + 'uri': '/v2/{parent=organizations/*/simulations/*/attackExposureResults/*}/valuedResources', + }, + ] + request, metadata = self._interceptor.pre_list_valued_resources(request, metadata) + pb_request = securitycenter_service.ListValuedResourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = securitycenter_service.ListValuedResourcesResponse() + pb_resp = securitycenter_service.ListValuedResourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_valued_resources(resp) + return resp + + class _SetFindingState(SecurityCenterRestStub): + def __hash__(self): + return hash("SetFindingState") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SetFindingStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the set finding state method over HTTP. + + Args: + request (~.securitycenter_service.SetFindingStateRequest): + The request object. Request message for updating a + finding's state. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{name=organizations/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=organizations/*/sources/*/locations/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=folders/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=folders/*/sources/*/locations/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=projects/*/sources/*/findings/*}:setState', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=projects/*/sources/*/locations/*/findings/*}:setState', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_finding_state(request, metadata) + pb_request = securitycenter_service.SetFindingStateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_set_finding_state(resp) + return resp + + class _SetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{resource=organizations/*/sources/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _SetMute(SecurityCenterRestStub): + def __hash__(self): + return hash("SetMute") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.SetMuteRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> finding.Finding: + r"""Call the set mute method over HTTP. + + Args: + request (~.securitycenter_service.SetMuteRequest): + The request object. Request message for updating a + finding's mute status. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{name=organizations/*/sources/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=organizations/*/sources/*/locations/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=folders/*/sources/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=folders/*/sources/*/locations/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=projects/*/sources/*/findings/*}:setMute', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v2/{name=projects/*/sources/*/locations/*/findings/*}:setMute', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_mute(request, metadata) + pb_request = securitycenter_service.SetMuteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, 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_set_mute(resp) + return resp + + class _TestIamPermissions(SecurityCenterRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + 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. 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{resource=organizations/*/sources/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UpdateBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateBigQueryExportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> bigquery_export.BigQueryExport: + r"""Call the update big query export method over HTTP. + + Args: + request (~.securitycenter_service.UpdateBigQueryExportRequest): + The request object. Request message for updating a + BigQuery export. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{big_query_export.name=organizations/*/locations/*/bigQueryExports/*}', + 'body': 'big_query_export', + }, +{ + 'method': 'patch', + 'uri': '/v2/{big_query_export.name=folders/*/locations/*/bigQueryExports/*}', + 'body': 'big_query_export', + }, +{ + 'method': 'patch', + 'uri': '/v2/{big_query_export.name=projects/*/locations/*/bigQueryExports/*}', + 'body': 'big_query_export', + }, + ] + request, metadata = self._interceptor.pre_update_big_query_export(request, metadata) + pb_request = securitycenter_service.UpdateBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_big_query_export(resp) + return resp + + class _UpdateExternalSystem(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateExternalSystem") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateExternalSystemRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_external_system.ExternalSystem: + r"""Call the update external system method over HTTP. + + Args: + request (~.securitycenter_service.UpdateExternalSystemRequest): + The request object. Request message for updating a + ExternalSystem resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_external_system.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v2/{external_system.name=organizations/*/sources/*/locations/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v2/{external_system.name=folders/*/sources/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v2/{external_system.name=folders/*/sources/*/locations/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v2/{external_system.name=projects/*/sources/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, +{ + 'method': 'patch', + 'uri': '/v2/{external_system.name=projects/*/sources/*/locations/*/findings/*/externalSystems/*}', + 'body': 'external_system', + }, + ] + request, metadata = self._interceptor.pre_update_external_system(request, metadata) + pb_request = securitycenter_service.UpdateExternalSystemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_external_system.ExternalSystem() + pb_resp = gcs_external_system.ExternalSystem.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_external_system(resp) + return resp + + class _UpdateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateFindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_finding.Finding: + r"""Call the update finding method over HTTP. + + Args: + request (~.securitycenter_service.UpdateFindingRequest): + The request object. Request message for updating or + creating a finding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{finding.name=organizations/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v2/{finding.name=organizations/*/sources/*/locations/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v2/{finding.name=folders/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v2/{finding.name=folders/*/sources/*/locations/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v2/{finding.name=projects/*/sources/*/findings/*}', + 'body': 'finding', + }, +{ + 'method': 'patch', + 'uri': '/v2/{finding.name=projects/*/sources/*/locations/*/findings/*}', + 'body': 'finding', + }, + ] + request, metadata = self._interceptor.pre_update_finding(request, metadata) + pb_request = securitycenter_service.UpdateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_finding(resp) + return resp + + class _UpdateMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateMuteConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_mute_config.MuteConfig: + r"""Call the update mute config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateMuteConfigRequest): + The request object. Request message for updating a mute + config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{mute_config.name=organizations/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{mute_config.name=organizations/*/locations/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{mute_config.name=folders/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{mute_config.name=folders/*/locations/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{mute_config.name=projects/*/muteConfigs/*}', + 'body': 'mute_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{mute_config.name=projects/*/locations/*/muteConfigs/*}', + 'body': 'mute_config', + }, + ] + request, metadata = self._interceptor.pre_update_mute_config(request, metadata) + pb_request = securitycenter_service.UpdateMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_mute_config.MuteConfig() + pb_resp = gcs_mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_mute_config(resp) + return resp + + class _UpdateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateNotificationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the update notification + config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateNotificationConfigRequest): + The request object. Request message for updating a + notification config. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{notification_config.name=organizations/*/locations/*/notificationConfigs/*}', + 'body': 'notification_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{notification_config.name=folders/*/locations/*/notificationConfigs/*}', + 'body': 'notification_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{notification_config.name=projects/*/locations/*/notificationConfigs/*}', + 'body': 'notification_config', + }, + ] + request, metadata = self._interceptor.pre_update_notification_config(request, metadata) + pb_request = securitycenter_service.UpdateNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_notification_config(resp) + return resp + + class _UpdateResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateResourceValueConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateResourceValueConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Call the update resource value + config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateResourceValueConfigRequest): + The request object. Request message to update resource + value config + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_resource_value_config.ResourceValueConfig: + A resource value configuration (RVC) + is a mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{resource_value_config.name=organizations/*/resourceValueConfigs/*}', + 'body': 'resource_value_config', + }, +{ + 'method': 'patch', + 'uri': '/v2/{resource_value_config.name=organizations/*/locations/*/resourceValueConfigs/*}', + 'body': 'resource_value_config', + }, + ] + request, metadata = self._interceptor.pre_update_resource_value_config(request, metadata) + pb_request = securitycenter_service.UpdateResourceValueConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_resource_value_config.ResourceValueConfig() + pb_resp = gcs_resource_value_config.ResourceValueConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_resource_value_config(resp) + return resp + + class _UpdateSecurityMarks(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSecurityMarks") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSecurityMarksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_security_marks.SecurityMarks: + r"""Call the update security marks method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSecurityMarksRequest): + The request object. Request message for updating a + SecurityMarks resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=organizations/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=organizations/*/sources/*/locations/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=folders/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=folders/*/sources/*/locations/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=projects/*/assets/*/securityMarks}', + 'body': 'security_marks', + }, +{ + 'method': 'patch', + 'uri': '/v2/{security_marks.name=projects/*/sources/*/locations/*/findings/*/securityMarks}', + 'body': 'security_marks', + }, + ] + request, metadata = self._interceptor.pre_update_security_marks(request, metadata) + pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_security_marks.SecurityMarks() + pb_resp = gcs_security_marks.SecurityMarks.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_security_marks(resp) + return resp + + class _UpdateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSource") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: securitycenter_service.UpdateSourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcs_source.Source: + r"""Call the update source method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSourceRequest): + The request object. Request message for updating a + source. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v2/{source.name=organizations/*/sources/*}', + 'body': 'source', + }, + ] + request, metadata = self._interceptor.pre_update_source(request, metadata) + pb_request = securitycenter_service.UpdateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_source(resp) + return resp + + @property + def batch_create_resource_value_configs(self) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + securitycenter_service.BatchCreateResourceValueConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreateResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def bulk_mute_findings(self) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + 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._BulkMuteFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_big_query_export(self) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_mute_config(self) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_big_query_export(self) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + 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._DeleteBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_mute_config(self) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + 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._DeleteMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + 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._DeleteNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_resource_value_config(self) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + 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._DeleteResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_big_query_export(self) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + bigquery_export.BigQueryExport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_mute_config(self) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + mute_config.MuteConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_resource_value_config(self) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + resource_value_config.ResourceValueConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_simulation(self) -> Callable[ + [securitycenter_service.GetSimulationRequest], + simulation.Simulation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSimulation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_valued_resource(self) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + valued_resource.ValuedResource]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetValuedResource(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_attack_paths(self) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + securitycenter_service.ListAttackPathsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAttackPaths(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_big_query_exports(self) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + securitycenter_service.ListBigQueryExportsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBigQueryExports(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.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_mute_configs(self) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + securitycenter_service.ListMuteConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMuteConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListNotificationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_resource_value_configs(self) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + securitycenter_service.ListResourceValueConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_valued_resources(self) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + securitycenter_service.ListValuedResourcesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListValuedResources(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_mute(self) -> Callable[ + [securitycenter_service.SetMuteRequest], + 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._SetMute(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_big_query_export(self) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + bigquery_export.BigQueryExport]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_external_system(self) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + gcs_external_system.ExternalSystem]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateExternalSystem(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_mute_config(self) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + gcs_mute_config.MuteConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_resource_value_config(self) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + gcs_resource_value_config.ResourceValueConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v2/{name=organizations/*/operations/*}:cancel', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In 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(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v2/{name=organizations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In 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(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), 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(SecurityCenterRestStub): + 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: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v2/{name=organizations/*/operations}', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SecurityCenterRestTransport', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.py new file mode 100644 index 000000000000..bb1db5459f13 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.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. +# +from .access import ( + Access, + Geolocation, + ServiceAccountDelegationInfo, +) +from .application import ( + Application, +) +from .attack_exposure import ( + AttackExposure, +) +from .attack_path import ( + AttackPath, +) +from .backup_disaster_recovery import ( + BackupDisasterRecovery, +) +from .bigquery_export import ( + BigQueryExport, +) +from .cloud_armor import ( + AdaptiveProtection, + Attack, + CloudArmor, + Requests, + SecurityPolicy, +) +from .cloud_dlp_data_profile import ( + CloudDlpDataProfile, +) +from .cloud_dlp_inspection import ( + CloudDlpInspection, +) +from .compliance import ( + Compliance, +) +from .connection import ( + Connection, +) +from .contact_details import ( + Contact, + ContactDetails, +) +from .container import ( + Container, +) +from .database import ( + Database, +) +from .exfiltration import ( + ExfilResource, + Exfiltration, +) +from .external_system import ( + ExternalSystem, +) +from .file import ( + File, +) +from .finding import ( + Finding, +) +from .folder import ( + Folder, +) +from .group_membership import ( + GroupMembership, +) +from .iam_binding import ( + IamBinding, +) +from .indicator import ( + Indicator, +) +from .kernel_rootkit import ( + KernelRootkit, +) +from .kubernetes import ( + Kubernetes, +) +from .label import ( + Label, +) +from .load_balancer import ( + LoadBalancer, +) +from .log_entry import ( + CloudLoggingEntry, + LogEntry, +) +from .mitre_attack import ( + MitreAttack, +) +from .mute_config import ( + MuteConfig, +) +from .notebook import ( + Notebook, +) +from .notification_config import ( + NotificationConfig, +) +from .notification_message import ( + NotificationMessage, +) +from .org_policy import ( + OrgPolicy, +) +from .process import ( + EnvironmentVariable, + Process, +) +from .resource import ( + AwsMetadata, + AzureMetadata, + GcpMetadata, + Resource, + ResourcePath, + CloudProvider, +) +from .resource_value_config import ( + ResourceValueConfig, + ResourceValue, +) +from .security_marks import ( + SecurityMarks, +) +from .security_posture import ( + SecurityPosture, +) +from .securitycenter_service import ( + BatchCreateResourceValueConfigsRequest, + BatchCreateResourceValueConfigsResponse, + BulkMuteFindingsRequest, + BulkMuteFindingsResponse, + CreateBigQueryExportRequest, + CreateFindingRequest, + CreateMuteConfigRequest, + CreateNotificationConfigRequest, + CreateResourceValueConfigRequest, + CreateSourceRequest, + DeleteBigQueryExportRequest, + DeleteMuteConfigRequest, + DeleteNotificationConfigRequest, + DeleteResourceValueConfigRequest, + GetBigQueryExportRequest, + GetMuteConfigRequest, + GetNotificationConfigRequest, + GetResourceValueConfigRequest, + GetSimulationRequest, + GetSourceRequest, + GetValuedResourceRequest, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListAttackPathsRequest, + ListAttackPathsResponse, + ListBigQueryExportsRequest, + ListBigQueryExportsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListMuteConfigsRequest, + ListMuteConfigsResponse, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListResourceValueConfigsRequest, + ListResourceValueConfigsResponse, + ListSourcesRequest, + ListSourcesResponse, + ListValuedResourcesRequest, + ListValuedResourcesResponse, + SetFindingStateRequest, + SetMuteRequest, + UpdateBigQueryExportRequest, + UpdateExternalSystemRequest, + UpdateFindingRequest, + UpdateMuteConfigRequest, + UpdateNotificationConfigRequest, + UpdateResourceValueConfigRequest, + UpdateSecurityMarksRequest, + UpdateSourceRequest, +) +from .simulation import ( + Simulation, +) +from .source import ( + Source, +) +from .toxic_combination import ( + ToxicCombination, +) +from .valued_resource import ( + ResourceValueConfigMetadata, + ValuedResource, +) +from .vulnerability import ( + Cve, + Cvssv3, + Package, + Reference, + SecurityBulletin, + Vulnerability, +) + +__all__ = ( + 'Access', + 'Geolocation', + 'ServiceAccountDelegationInfo', + 'Application', + 'AttackExposure', + 'AttackPath', + 'BackupDisasterRecovery', + 'BigQueryExport', + 'AdaptiveProtection', + 'Attack', + 'CloudArmor', + 'Requests', + 'SecurityPolicy', + 'CloudDlpDataProfile', + 'CloudDlpInspection', + 'Compliance', + 'Connection', + 'Contact', + 'ContactDetails', + 'Container', + 'Database', + 'ExfilResource', + 'Exfiltration', + 'ExternalSystem', + 'File', + 'Finding', + 'Folder', + 'GroupMembership', + 'IamBinding', + 'Indicator', + 'KernelRootkit', + 'Kubernetes', + 'Label', + 'LoadBalancer', + 'CloudLoggingEntry', + 'LogEntry', + 'MitreAttack', + 'MuteConfig', + 'Notebook', + 'NotificationConfig', + 'NotificationMessage', + 'OrgPolicy', + 'EnvironmentVariable', + 'Process', + 'AwsMetadata', + 'AzureMetadata', + 'GcpMetadata', + 'Resource', + 'ResourcePath', + 'CloudProvider', + 'ResourceValueConfig', + 'ResourceValue', + 'SecurityMarks', + 'SecurityPosture', + 'BatchCreateResourceValueConfigsRequest', + 'BatchCreateResourceValueConfigsResponse', + 'BulkMuteFindingsRequest', + 'BulkMuteFindingsResponse', + 'CreateBigQueryExportRequest', + 'CreateFindingRequest', + 'CreateMuteConfigRequest', + 'CreateNotificationConfigRequest', + 'CreateResourceValueConfigRequest', + 'CreateSourceRequest', + 'DeleteBigQueryExportRequest', + 'DeleteMuteConfigRequest', + 'DeleteNotificationConfigRequest', + 'DeleteResourceValueConfigRequest', + 'GetBigQueryExportRequest', + 'GetMuteConfigRequest', + 'GetNotificationConfigRequest', + 'GetResourceValueConfigRequest', + 'GetSimulationRequest', + 'GetSourceRequest', + 'GetValuedResourceRequest', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAttackPathsRequest', + 'ListAttackPathsResponse', + 'ListBigQueryExportsRequest', + 'ListBigQueryExportsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListMuteConfigsRequest', + 'ListMuteConfigsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListResourceValueConfigsRequest', + 'ListResourceValueConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListValuedResourcesRequest', + 'ListValuedResourcesResponse', + 'SetFindingStateRequest', + 'SetMuteRequest', + 'UpdateBigQueryExportRequest', + 'UpdateExternalSystemRequest', + 'UpdateFindingRequest', + 'UpdateMuteConfigRequest', + 'UpdateNotificationConfigRequest', + 'UpdateResourceValueConfigRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Simulation', + 'Source', + 'ToxicCombination', + 'ResourceValueConfigMetadata', + 'ValuedResource', + 'Cve', + 'Cvssv3', + 'Package', + 'Reference', + 'SecurityBulletin', + 'Vulnerability', +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py new file mode 100644 index 000000000000..e617c4170012 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v2', + manifest={ + 'Access', + 'ServiceAccountDelegationInfo', + 'Geolocation', + }, +) + + +class Access(proto.Message): + r"""Represents an access event. + + Attributes: + principal_email (str): + Associated email, such as "foo@google.com". + + The email address of the authenticated user or a service + account acting on behalf of a third party principal making + the request. For third party identity callers, the + ``principal_subject`` field is populated instead of this + field. For privacy reasons, the principal email address is + sometimes redacted. For more information, see `Caller + identities in audit + logs `__. + caller_ip (str): + Caller's IP address, such as "1.1.1.1". + caller_ip_geo (google.cloud.securitycenter_v2.types.Geolocation): + The caller IP's geolocation, which identifies + where the call came from. + user_agent_family (str): + Type of user agent associated with the + finding. For example, an operating system shell + or an embedded or standalone application. + user_agent (str): + The caller's user agent string associated + with the finding. + service_name (str): + This is the API service that the service + account made a call to, e.g. + "iam.googleapis.com". + method_name (str): + The method that the service account called, + e.g. "SetIamPolicy". + principal_subject (str): + A string that represents the principal_subject that is + associated with the identity. Unlike ``principal_email``, + ``principal_subject`` supports principals that aren't + associated with email addresses, such as third party + principals. For most identities, the format is + ``principal://iam.googleapis.com/{identity pool name}/subject/{subject}``. + Some GKE identities, such as GKE_WORKLOAD, FREEFORM, and + GKE_HUB_WORKLOAD, still use the legacy format + ``serviceAccount:{identity pool name}[{subject}]``. + service_account_key_name (str): + The name of the service account key that was used to create + or exchange credentials when authenticating the service + account that made the request. This is a scheme-less URI + full resource name. For example: + + "//iam.googleapis.com/projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}". + service_account_delegation_info (MutableSequence[google.cloud.securitycenter_v2.types.ServiceAccountDelegationInfo]): + The identity delegation history of an authenticated service + account that made the request. The + ``serviceAccountDelegationInfo[]`` object contains + information about the real authorities that try to access + Google Cloud resources by delegating on a service account. + When multiple authorities are present, they are guaranteed + to be sorted based on the original ordering of the identity + delegation events. + user_name (str): + A string that represents a username. The + username provided depends on the type of the + finding and is likely not an IAM principal. For + example, this can be a system username if the + finding is related to a virtual machine, or it + can be an application login username. + """ + + principal_email: str = proto.Field( + proto.STRING, + number=1, + ) + caller_ip: str = proto.Field( + proto.STRING, + number=2, + ) + caller_ip_geo: 'Geolocation' = proto.Field( + proto.MESSAGE, + number=3, + message='Geolocation', + ) + user_agent_family: str = proto.Field( + proto.STRING, + number=4, + ) + user_agent: str = proto.Field( + proto.STRING, + number=5, + ) + service_name: str = proto.Field( + proto.STRING, + number=6, + ) + method_name: str = proto.Field( + proto.STRING, + number=7, + ) + principal_subject: str = proto.Field( + proto.STRING, + number=8, + ) + service_account_key_name: str = proto.Field( + proto.STRING, + number=9, + ) + service_account_delegation_info: MutableSequence['ServiceAccountDelegationInfo'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='ServiceAccountDelegationInfo', + ) + user_name: str = proto.Field( + proto.STRING, + number=11, + ) + + +class ServiceAccountDelegationInfo(proto.Message): + r"""Identity delegation history of an authenticated service + account. + + Attributes: + principal_email (str): + The email address of a Google account. + principal_subject (str): + A string representing the principal_subject associated with + the identity. As compared to ``principal_email``, supports + principals that aren't associated with email addresses, such + as third party principals. For most identities, the format + will be + ``principal://iam.googleapis.com/{identity pool name}/subjects/{subject}`` + except for some GKE identities (GKE_WORKLOAD, FREEFORM, + GKE_HUB_WORKLOAD) that are still in the legacy format + ``serviceAccount:{identity pool name}[{subject}]`` + """ + + principal_email: str = proto.Field( + proto.STRING, + number=1, + ) + principal_subject: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Geolocation(proto.Message): + r"""Represents a geographical location for a given access. + + Attributes: + region_code (str): + A CLDR. + """ + + region_code: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.py new file mode 100644 index 000000000000..b77f5993987b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Application', + }, +) + + +class Application(proto.Message): + r"""Represents an application associated with a finding. + + Attributes: + base_uri (str): + The base URI that identifies the network location of the + application in which the vulnerability was detected. For + example, ``http://example.com``. + full_uri (str): + The full URI with payload that could be used to reproduce + the vulnerability. For example, + ``http://example.com?p=aMmYgI6H``. + """ + + base_uri: str = proto.Field( + proto.STRING, + number=1, + ) + full_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.py new file mode 100644 index 000000000000..600d1a66d91e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'AttackExposure', + }, +) + + +class AttackExposure(proto.Message): + r"""An attack exposure contains the results of an attack path + simulation run. + + Attributes: + score (float): + A number between 0 (inclusive) and infinity + that represents how important this finding is to + remediate. The higher the score, the more + important it is to remediate. + latest_calculation_time (google.protobuf.timestamp_pb2.Timestamp): + The most recent time the attack exposure was + updated on this finding. + attack_exposure_result (str): + The resource name of the attack path simulation result that + contains the details regarding this attack exposure score. + Example: + ``organizations/123/simulations/456/attackExposureResults/789`` + state (google.cloud.securitycenter_v2.types.AttackExposure.State): + Output only. What state this AttackExposure + is in. This captures whether or not an attack + exposure has been calculated or not. + exposed_high_value_resources_count (int): + The number of high value resources that are + exposed as a result of this finding. + exposed_medium_value_resources_count (int): + The number of medium value resources that are + exposed as a result of this finding. + exposed_low_value_resources_count (int): + The number of high value resources that are + exposed as a result of this finding. + """ + class State(proto.Enum): + r"""This enum defines the various states an AttackExposure can be + in. + + Values: + STATE_UNSPECIFIED (0): + The state is not specified. + CALCULATED (1): + The attack exposure has been calculated. + NOT_CALCULATED (2): + The attack exposure has not been calculated. + """ + STATE_UNSPECIFIED = 0 + CALCULATED = 1 + NOT_CALCULATED = 2 + + score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + latest_calculation_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + attack_exposure_result: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + exposed_high_value_resources_count: int = proto.Field( + proto.INT32, + number=5, + ) + exposed_medium_value_resources_count: int = proto.Field( + proto.INT32, + number=6, + ) + exposed_low_value_resources_count: int = proto.Field( + proto.INT32, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py new file mode 100644 index 000000000000..433afe1a5eee --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py @@ -0,0 +1,223 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v2', + manifest={ + 'AttackPath', + }, +) + + +class AttackPath(proto.Message): + r"""A path that an attacker could take to reach an exposed + resource. + + Attributes: + name (str): + The attack path name, for example, + ``organizations/12/simulations/34/valuedResources/56/attackPaths/78`` + path_nodes (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode]): + A list of nodes that exist in this attack + path. + edges (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathEdge]): + A list of the edges between nodes in this + attack path. + """ + + class AttackPathNode(proto.Message): + r"""Represents one point that an attacker passes through in this + attack path. + + Attributes: + resource (str): + The name of the resource at this point in the attack path. + The format of the name follows the Cloud Asset Inventory + `resource name + format `__ + resource_type (str): + The `supported resource + type `__ + display_name (str): + Human-readable name of this resource. + associated_findings (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.PathNodeAssociatedFinding]): + The findings associated with this node in the + attack path. + uuid (str): + Unique id of the attack path node. + attack_steps (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.AttackStepNode]): + A list of attack step nodes that exist in + this attack path node. + """ + class NodeType(proto.Enum): + r"""The type of the incoming attack step node. + + Values: + NODE_TYPE_UNSPECIFIED (0): + Type not specified + NODE_TYPE_AND (1): + Incoming edge joined with AND + NODE_TYPE_OR (2): + Incoming edge joined with OR + NODE_TYPE_DEFENSE (3): + Incoming edge is defense + NODE_TYPE_ATTACKER (4): + Incoming edge is attacker + """ + NODE_TYPE_UNSPECIFIED = 0 + NODE_TYPE_AND = 1 + NODE_TYPE_OR = 2 + NODE_TYPE_DEFENSE = 3 + NODE_TYPE_ATTACKER = 4 + + class PathNodeAssociatedFinding(proto.Message): + r"""A finding that is associated with this node in the attack + path. + + Attributes: + canonical_finding (str): + Canonical name of the associated findings. Example: + ``organizations/123/sources/456/findings/789`` + finding_category (str): + The additional taxonomy group within findings + from a given source. + name (str): + Full resource name of the finding. + """ + + canonical_finding: str = proto.Field( + proto.STRING, + number=1, + ) + finding_category: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class AttackStepNode(proto.Message): + r"""Detailed steps the attack can take between path nodes. + + Attributes: + uuid (str): + Unique ID for one Node + type_ (google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.NodeType): + Attack step type. Can be either AND, OR or + DEFENSE + display_name (str): + User friendly name of the attack step + labels (MutableMapping[str, str]): + Attack step labels for metadata + description (str): + Attack step description + """ + + uuid: str = proto.Field( + proto.STRING, + number=1, + ) + type_: 'AttackPath.AttackPathNode.NodeType' = proto.Field( + proto.ENUM, + number=2, + enum='AttackPath.AttackPathNode.NodeType', + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + + resource: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + associated_findings: MutableSequence['AttackPath.AttackPathNode.PathNodeAssociatedFinding'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AttackPath.AttackPathNode.PathNodeAssociatedFinding', + ) + uuid: str = proto.Field( + proto.STRING, + number=5, + ) + attack_steps: MutableSequence['AttackPath.AttackPathNode.AttackStepNode'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='AttackPath.AttackPathNode.AttackStepNode', + ) + + class AttackPathEdge(proto.Message): + r"""Represents a connection between a source node and a + destination node in this attack path. + + Attributes: + source (str): + The attack node uuid of the source node. + destination (str): + The attack node uuid of the destination node. + """ + + source: str = proto.Field( + proto.STRING, + number=1, + ) + destination: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + path_nodes: MutableSequence[AttackPathNode] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=AttackPathNode, + ) + edges: MutableSequence[AttackPathEdge] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=AttackPathEdge, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py new file mode 100644 index 000000000000..0c1d44505179 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v2', + manifest={ + 'BackupDisasterRecovery', + }, +) + + +class BackupDisasterRecovery(proto.Message): + r"""Information related to Google Cloud Backup and DR Service + findings. + + Attributes: + backup_template (str): + The name of a Backup and DR template which comprises one or + more backup policies. See the `Backup and DR + documentation `__ + for more information. For example, ``snap-ov``. + policies (MutableSequence[str]): + The names of Backup and DR policies that are associated with + a template and that define when to run a backup, how + frequently to run a backup, and how long to retain the + backup image. For example, ``onvaults``. + host (str): + The name of a Backup and DR host, which is managed by the + backup and recovery appliance and known to the management + console. The host can be of type Generic (for example, + Compute Engine, SQL Server, Oracle DB, SMB file system, + etc.), vCenter, or an ESX server. See the `Backup and DR + documentation on + hosts `__ + for more information. For example, ``centos7-01``. + applications (MutableSequence[str]): + The names of Backup and DR applications. An application is a + VM, database, or file system on a managed host monitored by + a backup and recovery appliance. For example, + ``centos7-01-vol00``, ``centos7-01-vol01``, + ``centos7-01-vol02``. + storage_pool (str): + The name of the Backup and DR storage pool that the backup + and recovery appliance is storing data in. The storage pool + could be of type Cloud, Primary, Snapshot, or OnVault. See + the `Backup and DR documentation on storage + pools `__. + For example, ``DiskPoolOne``. + policy_options (MutableSequence[str]): + The names of Backup and DR advanced policy options of a + policy applying to an application. See the `Backup and DR + documentation on policy + options `__. + For example, ``skipofflineappsincongrp, nounmap``. + profile (str): + The name of the Backup and DR resource profile that + specifies the storage media for backups of application and + VM data. See the `Backup and DR documentation on + profiles `__. + For example, ``GCP``. + appliance (str): + The name of the Backup and DR appliance that captures, + moves, and manages the lifecycle of backup data. For + example, ``backup-server-57137``. + backup_type (str): + The backup type of the Backup and DR image. For example, + ``Snapshot``, ``Remote Snapshot``, ``OnVault``. + backup_create_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp at which the Backup and DR + backup was created. + """ + + backup_template: str = proto.Field( + proto.STRING, + number=1, + ) + policies: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + host: str = proto.Field( + proto.STRING, + number=3, + ) + applications: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + storage_pool: str = proto.Field( + proto.STRING, + number=5, + ) + policy_options: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + profile: str = proto.Field( + proto.STRING, + number=7, + ) + appliance: str = proto.Field( + proto.STRING, + number=8, + ) + backup_type: str = proto.Field( + proto.STRING, + number=9, + ) + backup_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py new file mode 100644 index 000000000000..01d3971a5bd5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v2', + manifest={ + 'BigQueryExport', + }, +) + + +class BigQueryExport(proto.Message): + r"""Configures how to deliver Findings to BigQuery Instance. + + Attributes: + name (str): + Identifier. The relative resource name of this export. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name. + The following list shows some examples: + + - + + ``organizations/{organization_id}/locations/{location_id}/bigQueryExports/{export_id}`` + + - ``folders/{folder_id}/locations/{location_id}/bigQueryExports/{export_id}`` + - + + ``projects/{project_id}/locations/{location_id}/bigQueryExports/{export_id}`` + + This field is provided in responses, and is ignored when + provided in create requests. + description (str): + The description of the export (max of 1024 + characters). + filter (str): + Expression that defines the filter to apply across + create/update events of findings. The expression is a list + of zero or more restrictions combined via logical operators + ``AND`` and ``OR``. Parentheses are supported, and ``OR`` + has higher precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + dataset (str): + The dataset to write findings' updates to. Its format is + "projects/[project_id]/datasets/[bigquery_dataset_id]". + BigQuery dataset unique ID must contain only letters (a-z, + A-Z), numbers (0-9), or underscores (_). + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the BigQuery + export was created. This field is set by the + server and will be ignored if provided on export + on creation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time at which + the BigQuery export was updated. This field is + set by the server and will be ignored if + provided on export creation or update. + most_recent_editor (str): + Output only. Email address of the user who + last edited the BigQuery export. This field is + set by the server and will be ignored if + provided on export creation or update. + principal (str): + Output only. The service account that needs + permission to create table and upload data to + the BigQuery dataset. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + dataset: 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, + ) + most_recent_editor: str = proto.Field( + proto.STRING, + number=7, + ) + principal: str = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.py new file mode 100644 index 000000000000..2bf900e3af1c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.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.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'CloudArmor', + 'SecurityPolicy', + 'Requests', + 'AdaptiveProtection', + 'Attack', + }, +) + + +class CloudArmor(proto.Message): + r"""Fields related to Google Cloud Armor findings. + + Attributes: + security_policy (google.cloud.securitycenter_v2.types.SecurityPolicy): + Information about the `Google Cloud Armor security + policy `__ + relevant to the finding. + requests (google.cloud.securitycenter_v2.types.Requests): + Information about incoming requests evaluated by `Google + Cloud Armor security + policies `__. + adaptive_protection (google.cloud.securitycenter_v2.types.AdaptiveProtection): + Information about potential Layer 7 DDoS attacks identified + by `Google Cloud Armor Adaptive + Protection `__. + attack (google.cloud.securitycenter_v2.types.Attack): + Information about DDoS attack volume and + classification. + threat_vector (str): + Distinguish between volumetric & protocol DDoS attack and + application layer attacks. For example, "L3_4" for Layer 3 + and Layer 4 DDoS attacks, or "L_7" for Layer 7 DDoS attacks. + duration (google.protobuf.duration_pb2.Duration): + Duration of attack from the start until the + current moment (updated every 5 minutes). + """ + + security_policy: 'SecurityPolicy' = proto.Field( + proto.MESSAGE, + number=1, + message='SecurityPolicy', + ) + requests: 'Requests' = proto.Field( + proto.MESSAGE, + number=2, + message='Requests', + ) + adaptive_protection: 'AdaptiveProtection' = proto.Field( + proto.MESSAGE, + number=3, + message='AdaptiveProtection', + ) + attack: 'Attack' = proto.Field( + proto.MESSAGE, + number=4, + message='Attack', + ) + threat_vector: str = proto.Field( + proto.STRING, + number=5, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + + +class SecurityPolicy(proto.Message): + r"""Information about the `Google Cloud Armor security + policy `__ + relevant to the finding. + + Attributes: + name (str): + The name of the Google Cloud Armor security + policy, for example, "my-security-policy". + type_ (str): + The type of Google Cloud Armor security + policy for example, 'backend security policy', + 'edge security policy', 'network edge security + policy', or 'always-on DDoS protection'. + preview (bool): + Whether or not the associated rule or policy + is in preview mode. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + preview: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class Requests(proto.Message): + r"""Information about the requests relevant to the finding. + + Attributes: + ratio (float): + For 'Increasing deny ratio', the ratio is the + denied traffic divided by the allowed traffic. + For 'Allowed traffic spike', the ratio is the + allowed traffic in the short term divided by + allowed traffic in the long term. + short_term_allowed (int): + Allowed RPS (requests per second) in the + short term. + long_term_allowed (int): + Allowed RPS (requests per second) over the + long term. + long_term_denied (int): + Denied RPS (requests per second) over the + long term. + """ + + ratio: float = proto.Field( + proto.DOUBLE, + number=1, + ) + short_term_allowed: int = proto.Field( + proto.INT32, + number=2, + ) + long_term_allowed: int = proto.Field( + proto.INT32, + number=3, + ) + long_term_denied: int = proto.Field( + proto.INT32, + number=4, + ) + + +class AdaptiveProtection(proto.Message): + r"""Information about `Google Cloud Armor Adaptive + Protection `__. + + Attributes: + confidence (float): + A score of 0 means that there is low confidence that the + detected event is an actual attack. A score of 1 means that + there is high confidence that the detected event is an + attack. See the `Adaptive Protection + documentation `__ + for further explanation. + """ + + confidence: float = proto.Field( + proto.DOUBLE, + number=1, + ) + + +class Attack(proto.Message): + r"""Information about DDoS attack volume and classification. + + Attributes: + volume_pps (int): + Total PPS (packets per second) volume of + attack. + volume_bps (int): + Total BPS (bytes per second) volume of + attack. + classification (str): + Type of attack, for example, 'SYN-flood', + 'NTP-udp', or 'CHARGEN-udp'. + """ + + volume_pps: int = proto.Field( + proto.INT32, + number=1, + ) + volume_bps: int = proto.Field( + proto.INT32, + number=2, + ) + classification: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py new file mode 100644 index 000000000000..1b41c5f6d040 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.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.cloud.securitycenter.v2', + manifest={ + 'CloudDlpDataProfile', + }, +) + + +class CloudDlpDataProfile(proto.Message): + r"""The `data + profile `__ + associated with the finding. + + Attributes: + data_profile (str): + Name of the data profile, for example, + ``projects/123/locations/europe/tableProfiles/8383929``. + parent_type (google.cloud.securitycenter_v2.types.CloudDlpDataProfile.ParentType): + The resource hierarchy level at which the + data profile was generated. + """ + class ParentType(proto.Enum): + r"""Parents for configurations that produce data profile + findings. + + Values: + PARENT_TYPE_UNSPECIFIED (0): + Unspecified parent type. + ORGANIZATION (1): + Organization-level configurations. + PROJECT (2): + Project-level configurations. + """ + PARENT_TYPE_UNSPECIFIED = 0 + ORGANIZATION = 1 + PROJECT = 2 + + data_profile: str = proto.Field( + proto.STRING, + number=1, + ) + parent_type: ParentType = proto.Field( + proto.ENUM, + number=2, + enum=ParentType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py new file mode 100644 index 000000000000..c98af340d22a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'CloudDlpInspection', + }, +) + + +class CloudDlpInspection(proto.Message): + r"""Details about the Cloud Data Loss Prevention (Cloud DLP) `inspection + job `__ + that produced the finding. + + Attributes: + inspect_job (str): + Name of the inspection job, for example, + ``projects/123/locations/europe/dlpJobs/i-8383929``. + info_type (str): + The type of information (or + `infoType `__) + found, for example, ``EMAIL_ADDRESS`` or ``STREET_ADDRESS``. + info_type_count (int): + The number of times Cloud DLP found this + infoType within this job and resource. + full_scan (bool): + Whether Cloud DLP scanned the complete + resource or a sampled subset. + """ + + inspect_job: str = proto.Field( + proto.STRING, + number=1, + ) + info_type: str = proto.Field( + proto.STRING, + number=2, + ) + info_type_count: int = proto.Field( + proto.INT64, + number=3, + ) + full_scan: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.py new file mode 100644 index 000000000000..64f5c99ef06b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Compliance', + }, +) + + +class Compliance(proto.Message): + r"""Contains compliance information about a security standard + indicating unmet recommendations. + + Attributes: + standard (str): + Industry-wide compliance standards or + benchmarks, such as CIS, PCI, and OWASP. + version (str): + Version of the standard or benchmark, for + example, 1.1 + ids (MutableSequence[str]): + Policies within the standard or benchmark, + for example, A.12.4.1 + """ + + standard: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.py new file mode 100644 index 000000000000..1e0ff52947d5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.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.cloud.securitycenter.v2', + manifest={ + 'Connection', + }, +) + + +class Connection(proto.Message): + r"""Contains information about the IP connection associated with + the finding. + + Attributes: + destination_ip (str): + Destination IP address. Not present for + sockets that are listening and not connected. + destination_port (int): + Destination port. Not present for sockets + that are listening and not connected. + source_ip (str): + Source IP address. + source_port (int): + Source port. + protocol (google.cloud.securitycenter_v2.types.Connection.Protocol): + IANA Internet Protocol Number such as TCP(6) + and UDP(17). + """ + class Protocol(proto.Enum): + r"""IANA Internet Protocol Number such as TCP(6) and UDP(17). + + Values: + PROTOCOL_UNSPECIFIED (0): + Unspecified protocol (not HOPOPT). + ICMP (1): + Internet Control Message Protocol. + TCP (6): + Transmission Control Protocol. + UDP (17): + User Datagram Protocol. + GRE (47): + Generic Routing Encapsulation. + ESP (50): + Encap Security Payload. + """ + PROTOCOL_UNSPECIFIED = 0 + ICMP = 1 + TCP = 6 + UDP = 17 + GRE = 47 + ESP = 50 + + destination_ip: str = proto.Field( + proto.STRING, + number=1, + ) + destination_port: int = proto.Field( + proto.INT32, + number=2, + ) + source_ip: str = proto.Field( + proto.STRING, + number=3, + ) + source_port: int = proto.Field( + proto.INT32, + number=4, + ) + protocol: Protocol = proto.Field( + proto.ENUM, + number=5, + enum=Protocol, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.py new file mode 100644 index 000000000000..f7e49e2e4392 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'ContactDetails', + 'Contact', + }, +) + + +class ContactDetails(proto.Message): + r"""Details about specific contacts + + Attributes: + contacts (MutableSequence[google.cloud.securitycenter_v2.types.Contact]): + A list of contacts + """ + + contacts: MutableSequence['Contact'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Contact', + ) + + +class Contact(proto.Message): + r"""The email address of a contact. + + Attributes: + email (str): + An email address. For example, "``person123@company.com``". + """ + + email: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.py new file mode 100644 index 000000000000..de1e6fd55be0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v2.types import label +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Container', + }, +) + + +class Container(proto.Message): + r"""Container associated with the finding. + + Attributes: + name (str): + Name of the container. + uri (str): + Container image URI provided when configuring + a pod or container. This string can identify a + container image version using mutable tags. + image_id (str): + Optional container image ID, if provided by + the container runtime. Uniquely identifies the + container image launched using a container image + digest. + labels (MutableSequence[google.cloud.securitycenter_v2.types.Label]): + Container labels, as provided by the + container runtime. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time that the container was created. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + image_id: str = proto.Field( + proto.STRING, + number=3, + ) + labels: MutableSequence[label.Label] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=label.Label, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.py new file mode 100644 index 000000000000..59f3eefcf9e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Database', + }, +) + + +class Database(proto.Message): + r"""Represents database access information, such as queries. A database + may be a sub-resource of an instance (as in the case of Cloud SQL + instances or Cloud Spanner instances), or the database instance + itself. Some database resources might not have the `full resource + name `__ populated + because these resource types, such as Cloud SQL databases, are not + yet supported by Cloud Asset Inventory. In these cases only the + display name is provided. + + Attributes: + name (str): + Some database resources may not have the `full resource + name `__ + populated because these resource types are not yet supported + by Cloud Asset Inventory (e.g. Cloud SQL databases). In + these cases only the display name will be provided. The + `full resource + name `__ of + the database that the user connected to, if it is supported + by Cloud Asset Inventory. + display_name (str): + The human-readable name of the database that + the user connected to. + user_name (str): + The username used to connect to the database. + The username might not be an IAM principal and + does not have a set format. + query (str): + The SQL statement that is associated with the + database access. + grantees (MutableSequence[str]): + The target usernames, roles, or groups of an + SQL privilege grant, which is not an IAM policy + change. + version (str): + The version of the database, for example, POSTGRES_14. See + `the complete + list `__. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + user_name: str = proto.Field( + proto.STRING, + number=3, + ) + query: str = proto.Field( + proto.STRING, + number=4, + ) + grantees: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + version: str = proto.Field( + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.py new file mode 100644 index 000000000000..8a3c83a21200 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Exfiltration', + 'ExfilResource', + }, +) + + +class Exfiltration(proto.Message): + r"""Exfiltration represents a data exfiltration attempt from one or more + sources to one or more targets. The ``sources`` attribute lists the + sources of the exfiltrated data. The ``targets`` attribute lists the + destinations the data was copied to. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v2.types.ExfilResource]): + If there are multiple sources, then the data + is considered "joined" between them. For + instance, BigQuery can join multiple tables, and + each table would be considered a source. + targets (MutableSequence[google.cloud.securitycenter_v2.types.ExfilResource]): + If there are multiple targets, each target + would get a complete copy of the "joined" source + data. + total_exfiltrated_bytes (int): + Total exfiltrated bytes processed for the + entire job. + """ + + sources: MutableSequence['ExfilResource'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ExfilResource', + ) + targets: MutableSequence['ExfilResource'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='ExfilResource', + ) + total_exfiltrated_bytes: int = proto.Field( + proto.INT64, + number=3, + ) + + +class ExfilResource(proto.Message): + r"""Resource where data was exfiltrated from or exfiltrated to. + + Attributes: + name (str): + The resource's `full resource + name `__. + components (MutableSequence[str]): + Subcomponents of the asset that was + exfiltrated, like URIs used during exfiltration, + table names, databases, and filenames. For + example, multiple tables might have been + exfiltrated from the same Cloud SQL instance, or + multiple files might have been exfiltrated from + the same Cloud Storage bucket. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + components: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py new file mode 100644 index 000000000000..780eb3c24edf --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py @@ -0,0 +1,192 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v2', + manifest={ + 'ExternalSystem', + }, +) + + +class ExternalSystem(proto.Message): + r"""Representation of third party SIEM/SOAR fields within SCC. + + Attributes: + name (str): + Full resource name of the external system. The following + list shows some examples: + + - ``organizations/1234/sources/5678/findings/123456/externalSystems/jira`` + - + + ``organizations/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` + + - ``folders/1234/sources/5678/findings/123456/externalSystems/jira`` + - + + ``folders/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` + + - ``projects/1234/sources/5678/findings/123456/externalSystems/jira`` + - + + ``projects/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` + assignees (MutableSequence[str]): + References primary/secondary etc assignees in + the external system. + external_uid (str): + The identifier that's used to track the + finding's corresponding case in the external + system. + status (str): + The most recent status of the finding's + corresponding case, as reported by the external + system. + external_system_update_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was last updated, as + reported by the external system. + case_uri (str): + The link to the finding's corresponding case + in the external system. + case_priority (str): + The priority of the finding's corresponding + case in the external system. + case_sla (google.protobuf.timestamp_pb2.Timestamp): + The SLA of the finding's corresponding case + in the external system. + case_create_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was created, as + reported by the external system. + case_close_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was closed, as + reported by the external system. + ticket_info (google.cloud.securitycenter_v2.types.ExternalSystem.TicketInfo): + Information about the ticket, if any, that is + being used to track the resolution of the issue + that is identified by this finding. + """ + + class TicketInfo(proto.Message): + r"""Information about the ticket, if any, that is being used to + track the resolution of the issue that is identified by this + finding. + + Attributes: + id (str): + The identifier of the ticket in the ticket + system. + assignee (str): + The assignee of the ticket in the ticket + system. + description (str): + The description of the ticket in the ticket + system. + uri (str): + The link to the ticket in the ticket system. + status (str): + The latest status of the ticket, as reported + by the ticket system. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the ticket was last updated, as + reported by the ticket system. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + assignee: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + uri: str = proto.Field( + proto.STRING, + number=4, + ) + status: str = proto.Field( + proto.STRING, + number=5, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + assignees: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + external_uid: str = proto.Field( + proto.STRING, + number=3, + ) + status: str = proto.Field( + proto.STRING, + number=4, + ) + external_system_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + case_uri: str = proto.Field( + proto.STRING, + number=6, + ) + case_priority: str = proto.Field( + proto.STRING, + number=7, + ) + case_sla: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + case_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + case_close_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + ticket_info: TicketInfo = proto.Field( + proto.MESSAGE, + number=8, + message=TicketInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.py new file mode 100644 index 000000000000..5bb6f2f70ef0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'File', + }, +) + + +class File(proto.Message): + r"""File information about the related binary/library used by an + executable, or the script used by a script interpreter + + Attributes: + path (str): + Absolute path of the file as a JSON encoded + string. + size (int): + Size of the file in bytes. + sha256 (str): + SHA256 hash of the first hashed_size bytes of the file + encoded as a hex string. If hashed_size == size, sha256 + represents the SHA256 hash of the entire file. + hashed_size (int): + The length in bytes of the file prefix that was hashed. If + hashed_size == size, any hashes reported represent the + entire file. + partially_hashed (bool): + True when the hash covers only a prefix of + the file. + contents (str): + Prefix of the file contents as a JSON-encoded + string. + disk_path (google.cloud.securitycenter_v2.types.File.DiskPath): + Path of the file in terms of underlying + disk/partition identifiers. + """ + + class DiskPath(proto.Message): + r"""Path of the file in terms of underlying disk/partition + identifiers. + + Attributes: + partition_uuid (str): + UUID of the partition (format + https://wiki.archlinux.org/title/persistent_block_device_naming#by-uuid) + relative_path (str): + Relative path of the file in the partition as a JSON encoded + string. Example: /home/user1/executable_file.sh + """ + + partition_uuid: str = proto.Field( + proto.STRING, + number=1, + ) + relative_path: str = proto.Field( + proto.STRING, + number=2, + ) + + path: str = proto.Field( + proto.STRING, + number=1, + ) + size: int = proto.Field( + proto.INT64, + number=2, + ) + sha256: str = proto.Field( + proto.STRING, + number=3, + ) + hashed_size: int = proto.Field( + proto.INT64, + number=4, + ) + partially_hashed: bool = proto.Field( + proto.BOOL, + number=5, + ) + contents: str = proto.Field( + proto.STRING, + number=6, + ) + disk_path: DiskPath = proto.Field( + proto.MESSAGE, + number=7, + message=DiskPath, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.py new file mode 100644 index 000000000000..4e18ac0eb8ae --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v2.types import access as gcs_access +from google.cloud.securitycenter_v2.types import application as gcs_application +from google.cloud.securitycenter_v2.types import attack_exposure as gcs_attack_exposure +from google.cloud.securitycenter_v2.types import backup_disaster_recovery as gcs_backup_disaster_recovery +from google.cloud.securitycenter_v2.types import cloud_armor as gcs_cloud_armor +from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile as gcs_cloud_dlp_data_profile +from google.cloud.securitycenter_v2.types import cloud_dlp_inspection as gcs_cloud_dlp_inspection +from google.cloud.securitycenter_v2.types import compliance +from google.cloud.securitycenter_v2.types import connection +from google.cloud.securitycenter_v2.types import contact_details +from google.cloud.securitycenter_v2.types import container +from google.cloud.securitycenter_v2.types import database as gcs_database +from google.cloud.securitycenter_v2.types import exfiltration as gcs_exfiltration +from google.cloud.securitycenter_v2.types import external_system +from google.cloud.securitycenter_v2.types import file +from google.cloud.securitycenter_v2.types import group_membership +from google.cloud.securitycenter_v2.types import iam_binding +from google.cloud.securitycenter_v2.types import indicator as gcs_indicator +from google.cloud.securitycenter_v2.types import kernel_rootkit as gcs_kernel_rootkit +from google.cloud.securitycenter_v2.types import kubernetes as gcs_kubernetes +from google.cloud.securitycenter_v2.types import load_balancer +from google.cloud.securitycenter_v2.types import log_entry +from google.cloud.securitycenter_v2.types import mitre_attack as gcs_mitre_attack +from google.cloud.securitycenter_v2.types import notebook as gcs_notebook +from google.cloud.securitycenter_v2.types import org_policy +from google.cloud.securitycenter_v2.types import process +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import security_posture as gcs_security_posture +from google.cloud.securitycenter_v2.types import toxic_combination as gcs_toxic_combination +from google.cloud.securitycenter_v2.types import vulnerability as gcs_vulnerability +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + + A finding is a record of assessment data like security, risk, + health, or privacy, that is ingested into Security Command + Center for presentation, notification, analysis, policy testing, + and enforcement. For example, a cross-site scripting (XSS) + vulnerability in an App Engine application is a finding. + + Attributes: + name (str): + The `relative resource + name `__ + of the finding. The following list shows some examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + canonical_name (str): + Output only. The canonical name of the finding. The + following list shows some examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + The prefix is the closest CRM ancestor of the resource + associated with the finding. + parent (str): + The relative resource name of the source and location the + finding belongs to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. The following + list shows some examples: + + - ``organizations/{organization_id}/sources/{source_id}`` + - ``folders/{folders_id}/sources/{source_id}`` + - ``projects/{projects_id}/sources/{source_id}`` + - + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}`` + + - ``folders/{folders_id}/sources/{source_id}/locations/{location_id}`` + - ``projects/{projects_id}/sources/{source_id}/locations/{location_id}`` + resource_name (str): + Immutable. For findings on Google Cloud resources, the full + resource name of the Google Cloud resource this finding is + for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + state (google.cloud.securitycenter_v2.types.Finding.State): + Output only. The state of the finding. + category (str): + Immutable. The additional taxonomy group within findings + from a given source. Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (google.protobuf.timestamp_pb2.Timestamp): + The time the finding was first detected. If + an existing finding is updated, then this is the + time the update occurred. For example, if the + finding represents an open firewall, this + property captures the time the detector believes + the firewall became open. The accuracy is + determined by the detector. If the finding is + later resolved, then this time reflects when the + finding was resolved. This must not be set to a + value greater than the current timestamp. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the finding + was created in Security Command Center. + severity (google.cloud.securitycenter_v2.types.Finding.Severity): + The severity of the finding. This field is + managed by the source that writes the finding. + mute (google.cloud.securitycenter_v2.types.Finding.Mute): + Indicates the mute state of a finding (either + muted, unmuted or undefined). Unlike other + attributes of a finding, a finding provider + shouldn't set the value of mute. + mute_info (google.cloud.securitycenter_v2.types.Finding.MuteInfo): + Output only. The mute information regarding + this finding. + finding_class (google.cloud.securitycenter_v2.types.Finding.FindingClass): + The class of the finding. + indicator (google.cloud.securitycenter_v2.types.Indicator): + Represents what's commonly known as an *indicator of + compromise* (IoC) in computer forensics. This is an artifact + observed on a network or in an operating system that, with + high confidence, indicates a computer intrusion. For more + information, see `Indicator of + compromise `__. + vulnerability (google.cloud.securitycenter_v2.types.Vulnerability): + Represents vulnerability-specific fields like + CVE and CVSS scores. CVE stands for Common + Vulnerabilities and Exposures + (https://cve.mitre.org/about/) + mute_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time this + finding was muted or unmuted. + external_systems (MutableMapping[str, google.cloud.securitycenter_v2.types.ExternalSystem]): + Output only. Third party SIEM/SOAR fields + within SCC, contains external system information + and external system finding fields. + mitre_attack (google.cloud.securitycenter_v2.types.MitreAttack): + MITRE ATT&CK tactics and techniques related + to this finding. See: https://attack.mitre.org + access (google.cloud.securitycenter_v2.types.Access): + Access details associated with the finding, + such as more information on the caller, which + method was accessed, and from where. + connections (MutableSequence[google.cloud.securitycenter_v2.types.Connection]): + Contains information about the IP connection + associated with the finding. + mute_initiator (str): + Records additional information about the mute operation, for + example, the `mute + configuration `__ + that muted the finding and the user who muted the finding. + processes (MutableSequence[google.cloud.securitycenter_v2.types.Process]): + Represents operating system processes + associated with the Finding. + contacts (MutableMapping[str, google.cloud.securitycenter_v2.types.ContactDetails]): + Output only. Map containing the points of contact for the + given finding. The key represents the type of contact, while + the value contains a list of all the contacts that pertain. + Please refer to: + https://cloud.google.com/resource-manager/docs/managing-notification-contacts#notification-categories + + :: + + { + "security": { + "contacts": [ + { + "email": "person1@company.com" + }, + { + "email": "person2@company.com" + } + ] + } + } + compliances (MutableSequence[google.cloud.securitycenter_v2.types.Compliance]): + Contains compliance information for security + standards associated to the finding. + parent_display_name (str): + Output only. The human readable display name + of the finding source such as "Event Threat + Detection" or "Security Health Analytics". + description (str): + Contains more details about the finding. + exfiltration (google.cloud.securitycenter_v2.types.Exfiltration): + Represents exfiltrations associated with the + finding. + iam_bindings (MutableSequence[google.cloud.securitycenter_v2.types.IamBinding]): + Represents IAM bindings associated with the + finding. + next_steps (str): + Steps to address the finding. + module_name (str): + Unique identifier of the module which + generated the finding. Example: + + folders/598186756061/securityHealthAnalyticsSettings/customModules/56799441161885 + containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): + Containers associated with the finding. This + field provides information for both Kubernetes + and non-Kubernetes containers. + kubernetes (google.cloud.securitycenter_v2.types.Kubernetes): + Kubernetes resources associated with the + finding. + database (google.cloud.securitycenter_v2.types.Database): + Database associated with the finding. + attack_exposure (google.cloud.securitycenter_v2.types.AttackExposure): + The results of an attack path simulation + relevant to this finding. + files (MutableSequence[google.cloud.securitycenter_v2.types.File]): + File associated with the finding. + cloud_dlp_inspection (google.cloud.securitycenter_v2.types.CloudDlpInspection): + Cloud Data Loss Prevention (Cloud DLP) + inspection results that are associated with the + finding. + cloud_dlp_data_profile (google.cloud.securitycenter_v2.types.CloudDlpDataProfile): + Cloud DLP data profile that is associated + with the finding. + kernel_rootkit (google.cloud.securitycenter_v2.types.KernelRootkit): + Signature of the kernel rootkit. + org_policies (MutableSequence[google.cloud.securitycenter_v2.types.OrgPolicy]): + Contains information about the org policies + associated with the finding. + application (google.cloud.securitycenter_v2.types.Application): + Represents an application associated with the + finding. + backup_disaster_recovery (google.cloud.securitycenter_v2.types.BackupDisasterRecovery): + Fields related to Backup and DR findings. + security_posture (google.cloud.securitycenter_v2.types.SecurityPosture): + The security posture associated with the + finding. + log_entries (MutableSequence[google.cloud.securitycenter_v2.types.LogEntry]): + Log entries that are relevant to the finding. + load_balancers (MutableSequence[google.cloud.securitycenter_v2.types.LoadBalancer]): + The load balancers associated with the + finding. + cloud_armor (google.cloud.securitycenter_v2.types.CloudArmor): + Fields related to Cloud Armor findings. + notebook (google.cloud.securitycenter_v2.types.Notebook): + Notebook associated with the finding. + toxic_combination (google.cloud.securitycenter_v2.types.ToxicCombination): + Contains details about a group of security + issues that, when the issues occur together, + represent a greater risk than when the issues + occur independently. A group of such issues is + referred to as a toxic combination. + This field cannot be updated. Its value is + ignored in all update requests. + group_memberships (MutableSequence[google.cloud.securitycenter_v2.types.GroupMembership]): + Contains details about groups of which this + finding is a member. A group is a collection of + findings that are related in some way. This + field cannot be updated. Its value is ignored in + all update requests. + """ + class State(proto.Enum): + r"""The state of the finding. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + ACTIVE (1): + The finding requires attention and has not + been addressed yet. + INACTIVE (2): + The finding has been fixed, triaged as a + non-issue or otherwise addressed and is no + longer active. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + class Severity(proto.Enum): + r"""The severity of the finding. + + Values: + SEVERITY_UNSPECIFIED (0): + This value is used for findings when a source + doesn't write a severity value. + CRITICAL (1): + Vulnerability: + + A critical vulnerability is easily discoverable + by an external actor, exploitable, and results + in the direct ability to execute arbitrary code, + exfiltrate data, and otherwise gain additional + access and privileges to cloud resources and + workloads. Examples include publicly accessible + unprotected user data and public SSH access with + weak or no passwords. + + Threat: + + Indicates a threat that is able to access, + modify, or delete data or execute unauthorized + code within existing resources. + HIGH (2): + Vulnerability: + + A high risk vulnerability can be easily + discovered and exploited in combination with + other vulnerabilities in order to gain direct + access and the ability to execute arbitrary + code, exfiltrate data, and otherwise gain + additional access and privileges to cloud + resources and workloads. An example is a + database with weak or no passwords that is only + accessible internally. This database could + easily be compromised by an actor that had + access to the internal network. + + Threat: + + Indicates a threat that is able to create new + computational resources in an environment but + not able to access data or execute code in + existing resources. + MEDIUM (3): + Vulnerability: + + A medium risk vulnerability could be used by an + actor to gain access to resources or privileges + that enable them to eventually (through multiple + steps or a complex exploit) gain access and the + ability to execute arbitrary code or exfiltrate + data. An example is a service account with + access to more projects than it should have. If + an actor gains access to the service account, + they could potentially use that access to + manipulate a project the service account was not + intended to. + + Threat: + + Indicates a threat that is able to cause + operational impact but may not access data or + execute unauthorized code. + LOW (4): + Vulnerability: + + A low risk vulnerability hampers a security + organization's ability to detect vulnerabilities + or active threats in their deployment, or + prevents the root cause investigation of + security issues. An example is monitoring and + logs being disabled for resource configurations + and access. + + Threat: + + Indicates a threat that has obtained minimal + access to an environment but is not able to + access data, execute code, or create resources. + """ + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + HIGH = 2 + MEDIUM = 3 + LOW = 4 + + class Mute(proto.Enum): + r"""Mute state a finding can be in. + + Values: + MUTE_UNSPECIFIED (0): + Unspecified. + MUTED (1): + Finding has been muted. + UNMUTED (2): + Finding has been unmuted. + UNDEFINED (3): + Finding has never been muted/unmuted. + """ + MUTE_UNSPECIFIED = 0 + MUTED = 1 + UNMUTED = 2 + UNDEFINED = 3 + + class FindingClass(proto.Enum): + r"""Represents what kind of Finding it is. + + Values: + FINDING_CLASS_UNSPECIFIED (0): + Unspecified finding class. + THREAT (1): + Describes unwanted or malicious activity. + VULNERABILITY (2): + Describes a potential weakness in software + that increases risk to Confidentiality & + Integrity & Availability. + MISCONFIGURATION (3): + Describes a potential weakness in cloud + resource/asset configuration that increases + risk. + OBSERVATION (4): + Describes a security observation that is for + informational purposes. + SCC_ERROR (5): + Describes an error that prevents some SCC + functionality. + POSTURE_VIOLATION (6): + Describes a potential security risk due to a + change in the security posture. + TOXIC_COMBINATION (7): + Describes a combination of security issues + that represent a more severe security problem + when taken together. + """ + FINDING_CLASS_UNSPECIFIED = 0 + THREAT = 1 + VULNERABILITY = 2 + MISCONFIGURATION = 3 + OBSERVATION = 4 + SCC_ERROR = 5 + POSTURE_VIOLATION = 6 + TOXIC_COMBINATION = 7 + + class MuteInfo(proto.Message): + r"""Mute information about the finding, including whether the + finding has a static mute or any matching dynamic mute rules. + + Attributes: + static_mute (google.cloud.securitycenter_v2.types.Finding.MuteInfo.StaticMute): + If set, the static mute applied to this + finding. Static mutes override dynamic mutes. If + unset, there is no static mute. + dynamic_mute_records (MutableSequence[google.cloud.securitycenter_v2.types.Finding.MuteInfo.DynamicMuteRecord]): + The list of dynamic mute rules that currently + match the finding. + """ + + class StaticMute(proto.Message): + r"""Information about the static mute state. A static mute state + overrides any dynamic mute rules that apply to this finding. The + static mute state can be set by a static mute rule or by muting + the finding directly. + + Attributes: + state (google.cloud.securitycenter_v2.types.Finding.Mute): + The static mute state. If the value is ``MUTED`` or + ``UNMUTED``, then the finding's overall mute state will have + the same value. + apply_time (google.protobuf.timestamp_pb2.Timestamp): + When the static mute was applied. + """ + + state: 'Finding.Mute' = proto.Field( + proto.ENUM, + number=1, + enum='Finding.Mute', + ) + apply_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + class DynamicMuteRecord(proto.Message): + r"""The record of a dynamic mute rule that matches the finding. + + Attributes: + mute_config (str): + The relative resource name of the mute rule, represented by + a mute config, that created this record, for example + ``organizations/123/muteConfigs/mymuteconfig`` or + ``organizations/123/locations/global/muteConfigs/mymuteconfig``. + match_time (google.protobuf.timestamp_pb2.Timestamp): + When the dynamic mute rule first matched the + finding. + """ + + mute_config: str = proto.Field( + proto.STRING, + number=1, + ) + match_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + static_mute: 'Finding.MuteInfo.StaticMute' = proto.Field( + proto.MESSAGE, + number=1, + message='Finding.MuteInfo.StaticMute', + ) + dynamic_mute_records: MutableSequence['Finding.MuteInfo.DynamicMuteRecord'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Finding.MuteInfo.DynamicMuteRecord', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=2, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + resource_name: str = proto.Field( + proto.STRING, + number=4, + ) + state: State = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + category: str = proto.Field( + proto.STRING, + number=7, + ) + external_uri: str = proto.Field( + proto.STRING, + number=8, + ) + source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=9, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=10, + message=gcs_security_marks.SecurityMarks, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=14, + enum=Severity, + ) + mute: Mute = proto.Field( + proto.ENUM, + number=15, + enum=Mute, + ) + mute_info: MuteInfo = proto.Field( + proto.MESSAGE, + number=53, + message=MuteInfo, + ) + finding_class: FindingClass = proto.Field( + proto.ENUM, + number=16, + enum=FindingClass, + ) + indicator: gcs_indicator.Indicator = proto.Field( + proto.MESSAGE, + number=17, + message=gcs_indicator.Indicator, + ) + vulnerability: gcs_vulnerability.Vulnerability = proto.Field( + proto.MESSAGE, + number=18, + message=gcs_vulnerability.Vulnerability, + ) + mute_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + external_systems: MutableMapping[str, external_system.ExternalSystem] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=20, + message=external_system.ExternalSystem, + ) + mitre_attack: gcs_mitre_attack.MitreAttack = proto.Field( + proto.MESSAGE, + number=21, + message=gcs_mitre_attack.MitreAttack, + ) + access: gcs_access.Access = proto.Field( + proto.MESSAGE, + number=22, + message=gcs_access.Access, + ) + connections: MutableSequence[connection.Connection] = proto.RepeatedField( + proto.MESSAGE, + number=23, + message=connection.Connection, + ) + mute_initiator: str = proto.Field( + proto.STRING, + number=24, + ) + processes: MutableSequence[process.Process] = proto.RepeatedField( + proto.MESSAGE, + number=25, + message=process.Process, + ) + contacts: MutableMapping[str, contact_details.ContactDetails] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=26, + message=contact_details.ContactDetails, + ) + compliances: MutableSequence[compliance.Compliance] = proto.RepeatedField( + proto.MESSAGE, + number=27, + message=compliance.Compliance, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=29, + ) + description: str = proto.Field( + proto.STRING, + number=30, + ) + exfiltration: gcs_exfiltration.Exfiltration = proto.Field( + proto.MESSAGE, + number=31, + message=gcs_exfiltration.Exfiltration, + ) + iam_bindings: MutableSequence[iam_binding.IamBinding] = proto.RepeatedField( + proto.MESSAGE, + number=32, + message=iam_binding.IamBinding, + ) + next_steps: str = proto.Field( + proto.STRING, + number=33, + ) + module_name: str = proto.Field( + proto.STRING, + number=34, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=35, + message=container.Container, + ) + kubernetes: gcs_kubernetes.Kubernetes = proto.Field( + proto.MESSAGE, + number=36, + message=gcs_kubernetes.Kubernetes, + ) + database: gcs_database.Database = proto.Field( + proto.MESSAGE, + number=37, + message=gcs_database.Database, + ) + attack_exposure: gcs_attack_exposure.AttackExposure = proto.Field( + proto.MESSAGE, + number=38, + message=gcs_attack_exposure.AttackExposure, + ) + files: MutableSequence[file.File] = proto.RepeatedField( + proto.MESSAGE, + number=39, + message=file.File, + ) + cloud_dlp_inspection: gcs_cloud_dlp_inspection.CloudDlpInspection = proto.Field( + proto.MESSAGE, + number=40, + message=gcs_cloud_dlp_inspection.CloudDlpInspection, + ) + cloud_dlp_data_profile: gcs_cloud_dlp_data_profile.CloudDlpDataProfile = proto.Field( + proto.MESSAGE, + number=41, + message=gcs_cloud_dlp_data_profile.CloudDlpDataProfile, + ) + kernel_rootkit: gcs_kernel_rootkit.KernelRootkit = proto.Field( + proto.MESSAGE, + number=42, + message=gcs_kernel_rootkit.KernelRootkit, + ) + org_policies: MutableSequence[org_policy.OrgPolicy] = proto.RepeatedField( + proto.MESSAGE, + number=43, + message=org_policy.OrgPolicy, + ) + application: gcs_application.Application = proto.Field( + proto.MESSAGE, + number=45, + message=gcs_application.Application, + ) + backup_disaster_recovery: gcs_backup_disaster_recovery.BackupDisasterRecovery = proto.Field( + proto.MESSAGE, + number=47, + message=gcs_backup_disaster_recovery.BackupDisasterRecovery, + ) + security_posture: gcs_security_posture.SecurityPosture = proto.Field( + proto.MESSAGE, + number=48, + message=gcs_security_posture.SecurityPosture, + ) + log_entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( + proto.MESSAGE, + number=49, + message=log_entry.LogEntry, + ) + load_balancers: MutableSequence[load_balancer.LoadBalancer] = proto.RepeatedField( + proto.MESSAGE, + number=50, + message=load_balancer.LoadBalancer, + ) + cloud_armor: gcs_cloud_armor.CloudArmor = proto.Field( + proto.MESSAGE, + number=51, + message=gcs_cloud_armor.CloudArmor, + ) + notebook: gcs_notebook.Notebook = proto.Field( + proto.MESSAGE, + number=55, + message=gcs_notebook.Notebook, + ) + toxic_combination: gcs_toxic_combination.ToxicCombination = proto.Field( + proto.MESSAGE, + number=56, + message=gcs_toxic_combination.ToxicCombination, + ) + group_memberships: MutableSequence[group_membership.GroupMembership] = proto.RepeatedField( + proto.MESSAGE, + number=57, + message=group_membership.GroupMembership, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.py new file mode 100644 index 000000000000..2f26d5d13947 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.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.securitycenter.v2', + manifest={ + 'Folder', + }, +) + + +class Folder(proto.Message): + r"""Message that contains the resource name and display name of a + folder resource. + + Attributes: + resource_folder (str): + Full resource name of this folder. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_folder_display_name (str): + The user defined display name for this + folder. + """ + + resource_folder: str = proto.Field( + proto.STRING, + number=1, + ) + resource_folder_display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.py new file mode 100644 index 000000000000..bfe69eac6001 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.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.cloud.securitycenter.v2', + manifest={ + 'GroupMembership', + }, +) + + +class GroupMembership(proto.Message): + r"""Contains details about groups of which this finding is a + member. A group is a collection of findings that are related in + some way. + + Attributes: + group_type (google.cloud.securitycenter_v2.types.GroupMembership.GroupType): + Type of group. + group_id (str): + ID of the group. + """ + class GroupType(proto.Enum): + r"""Possible types of groups. + + Values: + GROUP_TYPE_UNSPECIFIED (0): + Default value. + GROUP_TYPE_TOXIC_COMBINATION (1): + Group represents a toxic combination. + """ + GROUP_TYPE_UNSPECIFIED = 0 + GROUP_TYPE_TOXIC_COMBINATION = 1 + + group_type: GroupType = proto.Field( + proto.ENUM, + number=1, + enum=GroupType, + ) + group_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py new file mode 100644 index 000000000000..17591c35825f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v2', + manifest={ + 'IamBinding', + }, +) + + +class IamBinding(proto.Message): + r"""Represents a particular IAM binding, which captures a + member's role addition, removal, or state. + + Attributes: + action (google.cloud.securitycenter_v2.types.IamBinding.Action): + The action that was performed on a Binding. + role (str): + Role that is assigned to "members". + For example, "roles/viewer", "roles/editor", or + "roles/owner". + member (str): + A single identity requesting access for a + Cloud Platform resource, for example, + "foo@google.com". + """ + class Action(proto.Enum): + r"""The type of action performed on a Binding in a policy. + + Values: + ACTION_UNSPECIFIED (0): + Unspecified. + ADD (1): + Addition of a Binding. + REMOVE (2): + Removal of a Binding. + """ + ACTION_UNSPECIFIED = 0 + ADD = 1 + REMOVE = 2 + + action: Action = proto.Field( + proto.ENUM, + number=1, + enum=Action, + ) + role: str = proto.Field( + proto.STRING, + number=2, + ) + member: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py new file mode 100644 index 000000000000..01b0184ef591 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v2', + manifest={ + 'Indicator', + }, +) + + +class Indicator(proto.Message): + r"""Represents what's commonly known as an *indicator of compromise* + (IoC) in computer forensics. This is an artifact observed on a + network or in an operating system that, with high confidence, + indicates a computer intrusion. For more information, see `Indicator + of + compromise `__. + + Attributes: + ip_addresses (MutableSequence[str]): + The list of IP addresses that are associated + with the finding. + domains (MutableSequence[str]): + List of domains associated to the Finding. + signatures (MutableSequence[google.cloud.securitycenter_v2.types.Indicator.ProcessSignature]): + The list of matched signatures indicating + that the given process is present in the + environment. + uris (MutableSequence[str]): + The list of URIs associated to the Findings. + """ + + class ProcessSignature(proto.Message): + r"""Indicates what signature matched this process. + + 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: + memory_hash_signature (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.MemoryHashSignature): + Signature indicating that a binary family was + matched. + + This field is a member of `oneof`_ ``signature``. + yara_rule_signature (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.YaraRuleSignature): + Signature indicating that a YARA rule was + matched. + + This field is a member of `oneof`_ ``signature``. + signature_type (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.SignatureType): + Describes the type of resource associated + with the signature. + """ + class SignatureType(proto.Enum): + r"""Possible resource types to be associated with a signature. + + Values: + SIGNATURE_TYPE_UNSPECIFIED (0): + The default signature type. + SIGNATURE_TYPE_PROCESS (1): + Used for signatures concerning processes. + SIGNATURE_TYPE_FILE (2): + Used for signatures concerning disks. + """ + SIGNATURE_TYPE_UNSPECIFIED = 0 + SIGNATURE_TYPE_PROCESS = 1 + SIGNATURE_TYPE_FILE = 2 + + class MemoryHashSignature(proto.Message): + r"""A signature corresponding to memory page hashes. + + Attributes: + binary_family (str): + The binary family. + detections (MutableSequence[google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.MemoryHashSignature.Detection]): + The list of memory hash detections + contributing to the binary family match. + """ + + class Detection(proto.Message): + r"""Memory hash detection contributing to the binary family + match. + + Attributes: + binary (str): + The name of the binary associated with the + memory hash signature detection. + percent_pages_matched (float): + The percentage of memory page hashes in the + signature that were matched. + """ + + binary: str = proto.Field( + proto.STRING, + number=2, + ) + percent_pages_matched: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + binary_family: str = proto.Field( + proto.STRING, + number=1, + ) + detections: MutableSequence['Indicator.ProcessSignature.MemoryHashSignature.Detection'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Indicator.ProcessSignature.MemoryHashSignature.Detection', + ) + + class YaraRuleSignature(proto.Message): + r"""A signature corresponding to a YARA rule. + + Attributes: + yara_rule (str): + The name of the YARA rule. + """ + + yara_rule: str = proto.Field( + proto.STRING, + number=5, + ) + + memory_hash_signature: 'Indicator.ProcessSignature.MemoryHashSignature' = proto.Field( + proto.MESSAGE, + number=6, + oneof='signature', + message='Indicator.ProcessSignature.MemoryHashSignature', + ) + yara_rule_signature: 'Indicator.ProcessSignature.YaraRuleSignature' = proto.Field( + proto.MESSAGE, + number=7, + oneof='signature', + message='Indicator.ProcessSignature.YaraRuleSignature', + ) + signature_type: 'Indicator.ProcessSignature.SignatureType' = proto.Field( + proto.ENUM, + number=8, + enum='Indicator.ProcessSignature.SignatureType', + ) + + ip_addresses: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + domains: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + signatures: MutableSequence[ProcessSignature] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=ProcessSignature, + ) + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.py new file mode 100644 index 000000000000..c57d1db94570 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'KernelRootkit', + }, +) + + +class KernelRootkit(proto.Message): + r"""Kernel mode rootkit signatures. + + Attributes: + name (str): + Rootkit name, when available. + unexpected_code_modification (bool): + True if unexpected modifications of kernel + code memory are present. + unexpected_read_only_data_modification (bool): + True if unexpected modifications of kernel + read-only data memory are present. + unexpected_ftrace_handler (bool): + True if ``ftrace`` points are present with callbacks + pointing to regions that are not in the expected kernel or + module code range. + unexpected_kprobe_handler (bool): + True if ``kprobe`` points are present with callbacks + pointing to regions that are not in the expected kernel or + module code range. + unexpected_kernel_code_pages (bool): + True if kernel code pages that are not in the + expected kernel or module code regions are + present. + unexpected_system_call_handler (bool): + True if system call handlers that are are not + in the expected kernel or module code regions + are present. + unexpected_interrupt_handler (bool): + True if interrupt handlers that are are not + in the expected kernel or module code regions + are present. + unexpected_processes_in_runqueue (bool): + True if unexpected processes in the scheduler + run queue are present. Such processes are in the + run queue, but not in the process task list. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + unexpected_code_modification: bool = proto.Field( + proto.BOOL, + number=2, + ) + unexpected_read_only_data_modification: bool = proto.Field( + proto.BOOL, + number=3, + ) + unexpected_ftrace_handler: bool = proto.Field( + proto.BOOL, + number=4, + ) + unexpected_kprobe_handler: bool = proto.Field( + proto.BOOL, + number=5, + ) + unexpected_kernel_code_pages: bool = proto.Field( + proto.BOOL, + number=6, + ) + unexpected_system_call_handler: bool = proto.Field( + proto.BOOL, + number=7, + ) + unexpected_interrupt_handler: bool = proto.Field( + proto.BOOL, + number=8, + ) + unexpected_processes_in_runqueue: bool = proto.Field( + proto.BOOL, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.py new file mode 100644 index 000000000000..8bc758c1f961 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v2.types import container +from google.cloud.securitycenter_v2.types import label + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Kubernetes', + }, +) + + +class Kubernetes(proto.Message): + r"""Kubernetes-related attributes. + + Attributes: + pods (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Pod]): + Kubernetes + `Pods `__ + associated with the finding. This field contains Pod records + for each container that is owned by a Pod. + nodes (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Node]): + Provides Kubernetes + `node `__ + information. + node_pools (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.NodePool]): + GKE `node + pools `__ + associated with the finding. This field contains node pool + information for each node, when it is available. + roles (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Role]): + Provides Kubernetes role information for findings that + involve `Roles or + ClusterRoles `__. + bindings (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Binding]): + Provides Kubernetes role binding information for findings + that involve `RoleBindings or + ClusterRoleBindings `__. + access_reviews (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.AccessReview]): + Provides information on any Kubernetes access + reviews (privilege checks) relevant to the + finding. + objects (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Object]): + Kubernetes objects related to the finding. + """ + + class Pod(proto.Message): + r"""A Kubernetes Pod. + + Attributes: + ns (str): + Kubernetes Pod namespace. + name (str): + Kubernetes Pod name. + labels (MutableSequence[google.cloud.securitycenter_v2.types.Label]): + Pod labels. For Kubernetes containers, these + are applied to the container. + containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): + Pod containers associated with this finding, + if any. + """ + + ns: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + labels: MutableSequence[label.Label] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=label.Label, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=container.Container, + ) + + class Node(proto.Message): + r"""Kubernetes nodes associated with the finding. + + Attributes: + name (str): + `Full resource + name `__ of + the Compute Engine VM running the cluster node. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + class NodePool(proto.Message): + r"""Provides GKE node pool information. + + Attributes: + name (str): + Kubernetes node pool name. + nodes (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Node]): + Nodes associated with the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + nodes: MutableSequence['Kubernetes.Node'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Kubernetes.Node', + ) + + class Role(proto.Message): + r"""Kubernetes Role or ClusterRole. + + Attributes: + kind (google.cloud.securitycenter_v2.types.Kubernetes.Role.Kind): + Role type. + ns (str): + Role namespace. + name (str): + Role name. + """ + class Kind(proto.Enum): + r"""Types of Kubernetes roles. + + Values: + KIND_UNSPECIFIED (0): + Role type is not specified. + ROLE (1): + Kubernetes Role. + CLUSTER_ROLE (2): + Kubernetes ClusterRole. + """ + KIND_UNSPECIFIED = 0 + ROLE = 1 + CLUSTER_ROLE = 2 + + kind: 'Kubernetes.Role.Kind' = proto.Field( + proto.ENUM, + number=1, + enum='Kubernetes.Role.Kind', + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class Binding(proto.Message): + r"""Represents a Kubernetes RoleBinding or ClusterRoleBinding. + + Attributes: + ns (str): + Namespace for the binding. + name (str): + Name for the binding. + role (google.cloud.securitycenter_v2.types.Kubernetes.Role): + The Role or ClusterRole referenced by the + binding. + subjects (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Subject]): + Represents one or more subjects that are + bound to the role. Not always available for + PATCH requests. + """ + + ns: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + role: 'Kubernetes.Role' = proto.Field( + proto.MESSAGE, + number=3, + message='Kubernetes.Role', + ) + subjects: MutableSequence['Kubernetes.Subject'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Kubernetes.Subject', + ) + + class Subject(proto.Message): + r"""Represents a Kubernetes subject. + + Attributes: + kind (google.cloud.securitycenter_v2.types.Kubernetes.Subject.AuthType): + Authentication type for the subject. + ns (str): + Namespace for the subject. + name (str): + Name for the subject. + """ + class AuthType(proto.Enum): + r"""Auth types that can be used for the subject's kind field. + + Values: + AUTH_TYPE_UNSPECIFIED (0): + Authentication is not specified. + USER (1): + User with valid certificate. + SERVICEACCOUNT (2): + Users managed by Kubernetes API with + credentials stored as secrets. + GROUP (3): + Collection of users. + """ + AUTH_TYPE_UNSPECIFIED = 0 + USER = 1 + SERVICEACCOUNT = 2 + GROUP = 3 + + kind: 'Kubernetes.Subject.AuthType' = proto.Field( + proto.ENUM, + number=1, + enum='Kubernetes.Subject.AuthType', + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class AccessReview(proto.Message): + r"""Conveys information about a Kubernetes access review (such as one + returned by a + ```kubectl auth can-i`` `__ + command) that was involved in a finding. + + Attributes: + group (str): + The API group of the resource. "*" means all. + ns (str): + Namespace of the action being requested. + Currently, there is no distinction between no + namespace and all namespaces. Both are + represented by "" (empty). + name (str): + The name of the resource being requested. + Empty means all. + resource (str): + The optional resource type requested. "*" means all. + subresource (str): + The optional subresource type. + verb (str): + A Kubernetes resource API verb, like get, list, watch, + create, update, delete, proxy. "*" means all. + version (str): + The API version of the resource. "*" means all. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + resource: str = proto.Field( + proto.STRING, + number=4, + ) + subresource: str = proto.Field( + proto.STRING, + number=5, + ) + verb: str = proto.Field( + proto.STRING, + number=6, + ) + version: str = proto.Field( + proto.STRING, + number=7, + ) + + class Object(proto.Message): + r"""Kubernetes object related to the finding, uniquely identified + by GKNN. Used if the object Kind is not one of Pod, Node, + NodePool, Binding, or AccessReview. + + Attributes: + group (str): + Kubernetes object group, such as + "policy.k8s.io/v1". + kind (str): + Kubernetes object kind, such as "Namespace". + ns (str): + Kubernetes object namespace. Must be a valid + DNS label. Named "ns" to avoid collision with + C++ namespace keyword. For details see + https://kubernetes.io/docs/tasks/administer-cluster/namespaces/. + name (str): + Kubernetes object name. For details see + https://kubernetes.io/docs/concepts/overview/working-with-objects/names/. + containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): + Pod containers associated with this finding, + if any. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + kind: str = proto.Field( + proto.STRING, + number=2, + ) + ns: str = proto.Field( + proto.STRING, + number=3, + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=container.Container, + ) + + pods: MutableSequence[Pod] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Pod, + ) + nodes: MutableSequence[Node] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Node, + ) + node_pools: MutableSequence[NodePool] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=NodePool, + ) + roles: MutableSequence[Role] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Role, + ) + bindings: MutableSequence[Binding] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Binding, + ) + access_reviews: MutableSequence[AccessReview] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=AccessReview, + ) + objects: MutableSequence[Object] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Object, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.py new file mode 100644 index 000000000000..d2f158e10cf6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.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.securitycenter.v2', + manifest={ + 'Label', + }, +) + + +class Label(proto.Message): + r"""Represents a generic name-value label. A label has separate name and + value fields to support filtering with the ``contains()`` function. + For more information, see `Filtering on array-type + fields `__. + + Attributes: + name (str): + Name of the label. + value (str): + Value that corresponds to the label's name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.py new file mode 100644 index 000000000000..95c16ba76680 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.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.cloud.securitycenter.v2', + manifest={ + 'LoadBalancer', + }, +) + + +class LoadBalancer(proto.Message): + r"""Contains information related to the load balancer associated + with the finding. + + Attributes: + name (str): + The name of the load balancer associated with + the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py new file mode 100644 index 000000000000..673caf996bad --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'LogEntry', + 'CloudLoggingEntry', + }, +) + + +class LogEntry(proto.Message): + r"""An individual entry in a log. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_logging_entry (google.cloud.securitycenter_v2.types.CloudLoggingEntry): + An individual entry in a log stored in Cloud + Logging. + + This field is a member of `oneof`_ ``log_entry``. + """ + + cloud_logging_entry: 'CloudLoggingEntry' = proto.Field( + proto.MESSAGE, + number=1, + oneof='log_entry', + message='CloudLoggingEntry', + ) + + +class CloudLoggingEntry(proto.Message): + r"""Metadata taken from a `Cloud Logging + LogEntry `__ + + Attributes: + insert_id (str): + A unique identifier for the log entry. + log_id (str): + The type of the log (part of ``log_name``. ``log_name`` is + the resource name of the log to which this log entry + belongs). For example: + ``cloudresourcemanager.googleapis.com/activity`` Note that + this field is not URL-encoded, unlike in ``LogEntry``. + resource_container (str): + The organization, folder, or project of the + monitored resource that produced this log entry. + timestamp (google.protobuf.timestamp_pb2.Timestamp): + The time the event described by the log entry + occurred. + """ + + insert_id: str = proto.Field( + proto.STRING, + number=1, + ) + log_id: str = proto.Field( + proto.STRING, + number=2, + ) + resource_container: str = proto.Field( + proto.STRING, + number=3, + ) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.py new file mode 100644 index 000000000000..d0a5c04b7853 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'MitreAttack', + }, +) + + +class MitreAttack(proto.Message): + r"""MITRE ATT&CK tactics and techniques related to this finding. + See: https://attack.mitre.org + + Attributes: + primary_tactic (google.cloud.securitycenter_v2.types.MitreAttack.Tactic): + The MITRE ATT&CK tactic most closely + represented by this finding, if any. + primary_techniques (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Technique]): + The MITRE ATT&CK technique most closely represented by this + finding, if any. primary_techniques is a repeated field + because there are multiple levels of MITRE ATT&CK + techniques. If the technique most closely represented by + this finding is a sub-technique (e.g. + ``SCANNING_IP_BLOCKS``), both the sub-technique and its + parent technique(s) will be listed (e.g. + ``SCANNING_IP_BLOCKS``, ``ACTIVE_SCANNING``). + additional_tactics (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Tactic]): + Additional MITRE ATT&CK tactics related to + this finding, if any. + additional_techniques (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Technique]): + Additional MITRE ATT&CK techniques related to + this finding, if any, along with any of their + respective parent techniques. + version (str): + The MITRE ATT&CK version referenced by the + above fields. E.g. "8". + """ + class Tactic(proto.Enum): + r"""MITRE ATT&CK tactics that can be referenced by SCC findings. + See: https://attack.mitre.org/tactics/enterprise/ + + Values: + TACTIC_UNSPECIFIED (0): + Unspecified value. + RECONNAISSANCE (1): + TA0043 + RESOURCE_DEVELOPMENT (2): + TA0042 + INITIAL_ACCESS (5): + TA0001 + EXECUTION (3): + TA0002 + PERSISTENCE (6): + TA0003 + PRIVILEGE_ESCALATION (8): + TA0004 + DEFENSE_EVASION (7): + TA0005 + CREDENTIAL_ACCESS (9): + TA0006 + DISCOVERY (10): + TA0007 + LATERAL_MOVEMENT (11): + TA0008 + COLLECTION (12): + TA0009 + COMMAND_AND_CONTROL (4): + TA0011 + EXFILTRATION (13): + TA0010 + IMPACT (14): + TA0040 + """ + TACTIC_UNSPECIFIED = 0 + RECONNAISSANCE = 1 + RESOURCE_DEVELOPMENT = 2 + INITIAL_ACCESS = 5 + EXECUTION = 3 + PERSISTENCE = 6 + PRIVILEGE_ESCALATION = 8 + DEFENSE_EVASION = 7 + CREDENTIAL_ACCESS = 9 + DISCOVERY = 10 + LATERAL_MOVEMENT = 11 + COLLECTION = 12 + COMMAND_AND_CONTROL = 4 + EXFILTRATION = 13 + IMPACT = 14 + + class Technique(proto.Enum): + r"""MITRE ATT&CK techniques that can be referenced by SCC + findings. See: https://attack.mitre.org/techniques/enterprise/ + Next ID: 65 + + Values: + TECHNIQUE_UNSPECIFIED (0): + Unspecified value. + MASQUERADING (49): + T1036 + MATCH_LEGITIMATE_NAME_OR_LOCATION (50): + T1036.005 + BOOT_OR_LOGON_INITIALIZATION_SCRIPTS (37): + T1037 + STARTUP_ITEMS (38): + T1037.005 + NETWORK_SERVICE_DISCOVERY (32): + T1046 + PROCESS_DISCOVERY (56): + T1057 + COMMAND_AND_SCRIPTING_INTERPRETER (6): + T1059 + UNIX_SHELL (7): + T1059.004 + PYTHON (59): + T1059.006 + EXPLOITATION_FOR_PRIVILEGE_ESCALATION (63): + T1068 + PERMISSION_GROUPS_DISCOVERY (18): + T1069 + CLOUD_GROUPS (19): + T1069.003 + INDICATOR_REMOVAL_FILE_DELETION (64): + T1070.004 + APPLICATION_LAYER_PROTOCOL (45): + T1071 + DNS (46): + T1071.004 + SOFTWARE_DEPLOYMENT_TOOLS (47): + T1072 + VALID_ACCOUNTS (14): + T1078 + DEFAULT_ACCOUNTS (35): + T1078.001 + LOCAL_ACCOUNTS (15): + T1078.003 + CLOUD_ACCOUNTS (16): + T1078.004 + PROXY (9): + T1090 + EXTERNAL_PROXY (10): + T1090.002 + MULTI_HOP_PROXY (11): + T1090.003 + ACCOUNT_MANIPULATION (22): + T1098 + ADDITIONAL_CLOUD_CREDENTIALS (40): + T1098.001 + SSH_AUTHORIZED_KEYS (23): + T1098.004 + ADDITIONAL_CONTAINER_CLUSTER_ROLES (58): + T1098.006 + INGRESS_TOOL_TRANSFER (3): + T1105 + NATIVE_API (4): + T1106 + BRUTE_FORCE (44): + T1110 + SHARED_MODULES (5): + T1129 + ACCESS_TOKEN_MANIPULATION (33): + T1134 + TOKEN_IMPERSONATION_OR_THEFT (39): + T1134.001 + EXPLOIT_PUBLIC_FACING_APPLICATION (27): + T1190 + DOMAIN_POLICY_MODIFICATION (30): + T1484 + DATA_DESTRUCTION (29): + T1485 + SERVICE_STOP (52): + T1489 + INHIBIT_SYSTEM_RECOVERY (36): + T1490 + RESOURCE_HIJACKING (8): + T1496 + NETWORK_DENIAL_OF_SERVICE (17): + T1498 + CLOUD_SERVICE_DISCOVERY (48): + T1526 + STEAL_APPLICATION_ACCESS_TOKEN (42): + T1528 + ACCOUNT_ACCESS_REMOVAL (51): + T1531 + STEAL_WEB_SESSION_COOKIE (25): + T1539 + CREATE_OR_MODIFY_SYSTEM_PROCESS (24): + T1543 + ABUSE_ELEVATION_CONTROL_MECHANISM (34): + T1548 + UNSECURED_CREDENTIALS (13): + T1552 + MODIFY_AUTHENTICATION_PROCESS (28): + T1556 + IMPAIR_DEFENSES (31): + T1562 + DISABLE_OR_MODIFY_TOOLS (55): + T1562.001 + EXFILTRATION_OVER_WEB_SERVICE (20): + T1567 + EXFILTRATION_TO_CLOUD_STORAGE (21): + T1567.002 + DYNAMIC_RESOLUTION (12): + T1568 + LATERAL_TOOL_TRANSFER (41): + T1570 + MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE (26): + T1578 + CREATE_SNAPSHOT (54): + T1578.001 + CLOUD_INFRASTRUCTURE_DISCOVERY (53): + T1580 + OBTAIN_CAPABILITIES (43): + T1588 + ACTIVE_SCANNING (1): + T1595 + SCANNING_IP_BLOCKS (2): + T1595.001 + CONTAINER_ADMINISTRATION_COMMAND (60): + T1609 + ESCAPE_TO_HOST (61): + T1611 + CONTAINER_AND_RESOURCE_DISCOVERY (57): + T1613 + STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES (62): + T1649 + """ + TECHNIQUE_UNSPECIFIED = 0 + MASQUERADING = 49 + MATCH_LEGITIMATE_NAME_OR_LOCATION = 50 + BOOT_OR_LOGON_INITIALIZATION_SCRIPTS = 37 + STARTUP_ITEMS = 38 + NETWORK_SERVICE_DISCOVERY = 32 + PROCESS_DISCOVERY = 56 + COMMAND_AND_SCRIPTING_INTERPRETER = 6 + UNIX_SHELL = 7 + PYTHON = 59 + EXPLOITATION_FOR_PRIVILEGE_ESCALATION = 63 + PERMISSION_GROUPS_DISCOVERY = 18 + CLOUD_GROUPS = 19 + INDICATOR_REMOVAL_FILE_DELETION = 64 + APPLICATION_LAYER_PROTOCOL = 45 + DNS = 46 + SOFTWARE_DEPLOYMENT_TOOLS = 47 + VALID_ACCOUNTS = 14 + DEFAULT_ACCOUNTS = 35 + LOCAL_ACCOUNTS = 15 + CLOUD_ACCOUNTS = 16 + PROXY = 9 + EXTERNAL_PROXY = 10 + MULTI_HOP_PROXY = 11 + ACCOUNT_MANIPULATION = 22 + ADDITIONAL_CLOUD_CREDENTIALS = 40 + SSH_AUTHORIZED_KEYS = 23 + ADDITIONAL_CONTAINER_CLUSTER_ROLES = 58 + INGRESS_TOOL_TRANSFER = 3 + NATIVE_API = 4 + BRUTE_FORCE = 44 + SHARED_MODULES = 5 + ACCESS_TOKEN_MANIPULATION = 33 + TOKEN_IMPERSONATION_OR_THEFT = 39 + EXPLOIT_PUBLIC_FACING_APPLICATION = 27 + DOMAIN_POLICY_MODIFICATION = 30 + DATA_DESTRUCTION = 29 + SERVICE_STOP = 52 + INHIBIT_SYSTEM_RECOVERY = 36 + RESOURCE_HIJACKING = 8 + NETWORK_DENIAL_OF_SERVICE = 17 + CLOUD_SERVICE_DISCOVERY = 48 + STEAL_APPLICATION_ACCESS_TOKEN = 42 + ACCOUNT_ACCESS_REMOVAL = 51 + STEAL_WEB_SESSION_COOKIE = 25 + CREATE_OR_MODIFY_SYSTEM_PROCESS = 24 + ABUSE_ELEVATION_CONTROL_MECHANISM = 34 + UNSECURED_CREDENTIALS = 13 + MODIFY_AUTHENTICATION_PROCESS = 28 + IMPAIR_DEFENSES = 31 + DISABLE_OR_MODIFY_TOOLS = 55 + EXFILTRATION_OVER_WEB_SERVICE = 20 + EXFILTRATION_TO_CLOUD_STORAGE = 21 + DYNAMIC_RESOLUTION = 12 + LATERAL_TOOL_TRANSFER = 41 + MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE = 26 + CREATE_SNAPSHOT = 54 + CLOUD_INFRASTRUCTURE_DISCOVERY = 53 + OBTAIN_CAPABILITIES = 43 + ACTIVE_SCANNING = 1 + SCANNING_IP_BLOCKS = 2 + CONTAINER_ADMINISTRATION_COMMAND = 60 + ESCAPE_TO_HOST = 61 + CONTAINER_AND_RESOURCE_DISCOVERY = 57 + STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES = 62 + + primary_tactic: Tactic = proto.Field( + proto.ENUM, + number=1, + enum=Tactic, + ) + primary_techniques: MutableSequence[Technique] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=Technique, + ) + additional_tactics: MutableSequence[Tactic] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=Tactic, + ) + additional_techniques: MutableSequence[Technique] = proto.RepeatedField( + proto.ENUM, + number=4, + enum=Technique, + ) + version: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.py new file mode 100644 index 000000000000..47f95ac38c38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.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.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'MuteConfig', + }, +) + + +class MuteConfig(proto.Message): + r"""A mute config is a Cloud SCC resource that contains the + configuration to mute create/update events of findings. + + Attributes: + name (str): + Identifier. This field will be ignored if provided on config + creation. The following list shows some examples of the + format: + + - ``organizations/{organization}/muteConfigs/{mute_config}`` + - + + ``organizations/{organization}locations/{location}//muteConfigs/{mute_config}`` + + - ``folders/{folder}/muteConfigs/{mute_config}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{mute_config}`` + - ``projects/{project}/muteConfigs/{mute_config}`` + - ``projects/{project}/locations/{location}/muteConfigs/{mute_config}`` + description (str): + A description of the mute config. + filter (str): + Required. An expression that defines the filter to apply + across create/update events of findings. While creating a + filter string, be mindful of the scope in which the mute + configuration is being created. E.g., If a filter contains + project = X but is created under the project = Y scope, it + might not match any findings. + + The following field and operator combinations are supported: + + - severity: ``=``, ``:`` + - category: ``=``, ``:`` + - resource.name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.folders.resource_folder: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + - finding_class: ``=``, ``:`` + - indicator.ip_addresses: ``=``, ``:`` + - indicator.domains: ``=``, ``:`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the mute + config was created. This field is set by the + server and will be ignored if provided on config + creation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time at which + the mute config was updated. This field is set + by the server and will be ignored if provided on + config creation or update. + most_recent_editor (str): + Output only. Email address of the user who + last edited the mute config. This field is set + by the server and will be ignored if provided on + config creation or update. + type_ (google.cloud.securitycenter_v2.types.MuteConfig.MuteConfigType): + Required. The type of the mute config, which + determines what type of mute state the config + affects. Immutable after creation. + expiry_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The expiry of the mute config. Only + applicable for dynamic configs. If the expiry is + set, when the config expires, it is removed from + all findings. + """ + class MuteConfigType(proto.Enum): + r"""The type of MuteConfig. + + Values: + MUTE_CONFIG_TYPE_UNSPECIFIED (0): + Unused. + STATIC (1): + A static mute config, which sets the static + mute state of future matching findings to muted. + Once the static mute state has been set, finding + or config modifications will not affect the + state. + DYNAMIC (2): + A dynamic mute config, which is applied to + existing and future matching findings, setting + their dynamic mute state to "muted". If the + config is updated or deleted, or a matching + finding is updated, such that the finding + doesn't match the config, the config will be + removed from the finding, and the finding's + dynamic mute state may become "unmuted" (unless + other configs still match). + """ + MUTE_CONFIG_TYPE_UNSPECIFIED = 0 + STATIC = 1 + DYNAMIC = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + most_recent_editor: str = proto.Field( + proto.STRING, + number=6, + ) + type_: MuteConfigType = proto.Field( + proto.ENUM, + number=8, + enum=MuteConfigType, + ) + expiry_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py new file mode 100644 index 000000000000..6fe873edc33e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter.v2', + manifest={ + 'Notebook', + }, +) + + +class Notebook(proto.Message): + r"""Represents a Jupyter notebook IPYNB file, such as a `Colab + Enterprise + notebook `__ file, + that is associated with a finding. + + Attributes: + name (str): + The name of the notebook. + service (str): + The source notebook service, for example, + "Colab Enterprise". + last_author (str): + The user ID of the latest author to modify + the notebook. + notebook_update_time (google.protobuf.timestamp_pb2.Timestamp): + The most recent time the notebook was + updated. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + service: str = proto.Field( + proto.STRING, + number=2, + ) + last_author: str = proto.Field( + proto.STRING, + number=3, + ) + notebook_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py new file mode 100644 index 000000000000..73797dfbbbb8 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v2', + manifest={ + 'NotificationConfig', + }, +) + + +class NotificationConfig(proto.Message): + r"""Cloud Security Command Center (Cloud SCC) notification + configs. + A notification config is a Cloud SCC resource that contains the + configuration to send notifications for create/update events of + findings, assets and etc. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The relative resource name of this notification + config. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + The following list shows some examples: + + ``organizations/{organization_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` + + + ``folders/{folder_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` + + + ``projects/{project_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` + description (str): + The description of the notification config + (max of 1024 characters). + pubsub_topic (str): + The Pub/Sub topic to send notifications to. Its format is + "projects/[project_id]/topics/[topic]". + service_account (str): + Output only. The service account that needs + "pubsub.topics.publish" permission to publish to + the Pub/Sub topic. + streaming_config (google.cloud.securitycenter_v2.types.NotificationConfig.StreamingConfig): + The config for triggering streaming-based + notifications. + + This field is a member of `oneof`_ ``notify_config``. + """ + + class StreamingConfig(proto.Message): + r"""The config for streaming-based notifications, which send each + event as soon as it is detected. + + Attributes: + filter (str): + Expression that defines the filter to apply across + create/update events of assets or findings as specified by + the event type. The expression is a list of zero or more + restrictions combined via logical operators ``AND`` and + ``OR``. Parentheses are supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + """ + + filter: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + pubsub_topic: str = proto.Field( + proto.STRING, + number=3, + ) + service_account: str = proto.Field( + proto.STRING, + number=4, + ) + streaming_config: StreamingConfig = proto.Field( + proto.MESSAGE, + number=5, + oneof='notify_config', + message=StreamingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.py new file mode 100644 index 000000000000..cbe17b52c42a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import resource as gcs_resource + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'NotificationMessage', + }, +) + + +class NotificationMessage(proto.Message): + r"""Cloud SCC's Notification + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + notification_config_name (str): + Name of the notification config that + generated current notification. + finding (google.cloud.securitycenter_v2.types.Finding): + If it's a Finding based notification config, + this field will be populated. + + This field is a member of `oneof`_ ``event``. + resource (google.cloud.securitycenter_v2.types.Resource): + The Cloud resource tied to this + notification's Finding. + """ + + notification_config_name: str = proto.Field( + proto.STRING, + number=1, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=2, + oneof='event', + message=gcs_finding.Finding, + ) + resource: gcs_resource.Resource = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_resource.Resource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.py new file mode 100644 index 000000000000..afd2ecb275f7 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.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.cloud.securitycenter.v2', + manifest={ + 'OrgPolicy', + }, +) + + +class OrgPolicy(proto.Message): + r"""Contains information about the org policies associated with + the finding. + + Attributes: + name (str): + The resource name of the org policy. Example: + "organizations/{organization_id}/policies/{constraint_name}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py new file mode 100644 index 000000000000..567e7cceaa35 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v2.types import file + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Process', + 'EnvironmentVariable', + }, +) + + +class Process(proto.Message): + r"""Represents an operating system process. + + Attributes: + name (str): + The process name, as displayed in utilities like ``top`` and + ``ps``. This name can be accessed through + ``/proc/[pid]/comm`` and changed with + ``prctl(PR_SET_NAME)``. + binary (google.cloud.securitycenter_v2.types.File): + File information for the process executable. + libraries (MutableSequence[google.cloud.securitycenter_v2.types.File]): + File information for libraries loaded by the + process. + script (google.cloud.securitycenter_v2.types.File): + When the process represents the invocation of a script, + ``binary`` provides information about the interpreter, while + ``script`` provides information about the script file + provided to the interpreter. + args (MutableSequence[str]): + Process arguments as JSON encoded strings. + arguments_truncated (bool): + True if ``args`` is incomplete. + env_variables (MutableSequence[google.cloud.securitycenter_v2.types.EnvironmentVariable]): + Process environment variables. + env_variables_truncated (bool): + True if ``env_variables`` is incomplete. + pid (int): + The process ID. + parent_pid (int): + The parent process ID. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + binary: file.File = proto.Field( + proto.MESSAGE, + number=2, + message=file.File, + ) + libraries: MutableSequence[file.File] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=file.File, + ) + script: file.File = proto.Field( + proto.MESSAGE, + number=4, + message=file.File, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + arguments_truncated: bool = proto.Field( + proto.BOOL, + number=6, + ) + env_variables: MutableSequence['EnvironmentVariable'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='EnvironmentVariable', + ) + env_variables_truncated: bool = proto.Field( + proto.BOOL, + number=8, + ) + pid: int = proto.Field( + proto.INT64, + number=9, + ) + parent_pid: int = proto.Field( + proto.INT64, + number=10, + ) + + +class EnvironmentVariable(proto.Message): + r"""A name-value pair representing an environment variable used + in an operating system process. + + Attributes: + name (str): + Environment variable name as a JSON encoded + string. + val (str): + Environment variable value as a JSON encoded + string. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + val: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.py new file mode 100644 index 000000000000..491062813849 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.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 + +from google.cloud.securitycenter_v2.types import folder + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'CloudProvider', + 'Resource', + 'GcpMetadata', + 'AwsMetadata', + 'AzureMetadata', + 'ResourcePath', + }, +) + + +class CloudProvider(proto.Enum): + r"""The cloud provider the finding pertains to. + + Values: + CLOUD_PROVIDER_UNSPECIFIED (0): + The cloud provider is unspecified. + GOOGLE_CLOUD_PLATFORM (1): + The cloud provider is Google Cloud Platform. + AMAZON_WEB_SERVICES (2): + The cloud provider is Amazon Web Services. + MICROSOFT_AZURE (3): + The cloud provider is Microsoft Azure. + """ + CLOUD_PROVIDER_UNSPECIFIED = 0 + GOOGLE_CLOUD_PLATFORM = 1 + AMAZON_WEB_SERVICES = 2 + MICROSOFT_AZURE = 3 + + +class Resource(proto.Message): + r"""Information related to the Google Cloud 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): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + display_name (str): + The human readable name of the resource. + type_ (str): + The full resource type of the resource. + cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): + Indicates which cloud provider the finding is + from. + service (str): + The service or resource provider associated + with the resource. + location (str): + The region or location of the service (if + applicable). + gcp_metadata (google.cloud.securitycenter_v2.types.GcpMetadata): + The GCP metadata associated with the finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + aws_metadata (google.cloud.securitycenter_v2.types.AwsMetadata): + The AWS metadata associated with the finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + azure_metadata (google.cloud.securitycenter_v2.types.AzureMetadata): + The Azure metadata associated with the + finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + resource_path (google.cloud.securitycenter_v2.types.ResourcePath): + Provides the path to the resource within the + resource hierarchy. + resource_path_string (str): + A string representation of the resource path. For Google + Cloud, it has the format of + ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` + where there can be any number of folders. For AWS, it has + the format of + ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` + where there can be any number of organizational units. For + Azure, it has the format of + ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` + where there can be any number of management groups. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + type_: str = proto.Field( + proto.STRING, + number=3, + ) + cloud_provider: 'CloudProvider' = proto.Field( + proto.ENUM, + number=4, + enum='CloudProvider', + ) + service: str = proto.Field( + proto.STRING, + number=5, + ) + location: str = proto.Field( + proto.STRING, + number=6, + ) + gcp_metadata: 'GcpMetadata' = proto.Field( + proto.MESSAGE, + number=7, + oneof='cloud_provider_metadata', + message='GcpMetadata', + ) + aws_metadata: 'AwsMetadata' = proto.Field( + proto.MESSAGE, + number=8, + oneof='cloud_provider_metadata', + message='AwsMetadata', + ) + azure_metadata: 'AzureMetadata' = proto.Field( + proto.MESSAGE, + number=9, + oneof='cloud_provider_metadata', + message='AzureMetadata', + ) + resource_path: 'ResourcePath' = proto.Field( + proto.MESSAGE, + number=10, + message='ResourcePath', + ) + resource_path_string: str = proto.Field( + proto.STRING, + number=11, + ) + + +class GcpMetadata(proto.Message): + r"""GCP metadata associated with the resource, only applicable if + the finding's cloud provider is Google Cloud Platform. + + Attributes: + project (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The project ID that the resource belongs to. + parent (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (MutableSequence[google.cloud.securitycenter_v2.types.Folder]): + Output only. Contains a Folder message for + each folder in the assets ancestry. The first + folder is the deepest nested folder, and the + last folder is the folder directly under the + Organization. + organization (str): + The name of the organization that the + resource belongs to. + """ + + project: str = proto.Field( + proto.STRING, + number=1, + ) + project_display_name: str = proto.Field( + proto.STRING, + number=2, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=4, + ) + folders: MutableSequence[folder.Folder] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=folder.Folder, + ) + organization: str = proto.Field( + proto.STRING, + number=6, + ) + + +class AwsMetadata(proto.Message): + r"""AWS metadata associated with the resource, only applicable if + the finding's cloud provider is Amazon Web Services. + + Attributes: + organization (google.cloud.securitycenter_v2.types.AwsMetadata.AwsOrganization): + The AWS organization associated with the + resource. + organizational_units (MutableSequence[google.cloud.securitycenter_v2.types.AwsMetadata.AwsOrganizationalUnit]): + A list of AWS organizational units associated + with the resource, ordered from lowest level + (closest to the account) to highest level. + account (google.cloud.securitycenter_v2.types.AwsMetadata.AwsAccount): + The AWS account associated with the resource. + """ + + class AwsOrganization(proto.Message): + r"""An organization is a collection of accounts that are + centrally managed together using consolidated billing, organized + hierarchically with organizational units (OUs), and controlled + with policies. + + Attributes: + id (str): + The unique identifier (ID) for the + organization. The regex pattern for an + organization ID string requires "o-" followed by + from 10 to 32 lowercase letters or digits. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + + class AwsOrganizationalUnit(proto.Message): + r"""An Organizational Unit (OU) is a container of AWS accounts + within a root of an organization. Policies that are attached to + an OU apply to all accounts contained in that OU and in any + child OUs. + + Attributes: + id (str): + The unique identifier (ID) associated with + this OU. The regex pattern for an organizational + unit ID string requires "ou-" followed by from 4 + to 32 lowercase letters or digits (the ID of the + root that contains the OU). This string is + followed by a second "-" dash and from 8 to 32 + additional lowercase letters or digits. For + example, "ou-ab12-cd34ef56". + name (str): + The friendly name of the OU. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + + class AwsAccount(proto.Message): + r"""An AWS account that is a member of an organization. + + Attributes: + id (str): + The unique identifier (ID) of the account, + containing exactly 12 digits. + name (str): + The friendly name of this account. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + + organization: AwsOrganization = proto.Field( + proto.MESSAGE, + number=1, + message=AwsOrganization, + ) + organizational_units: MutableSequence[AwsOrganizationalUnit] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=AwsOrganizationalUnit, + ) + account: AwsAccount = proto.Field( + proto.MESSAGE, + number=3, + message=AwsAccount, + ) + + +class AzureMetadata(proto.Message): + r"""Azure metadata associated with the resource, only applicable + if the finding's cloud provider is Microsoft Azure. + + Attributes: + management_groups (MutableSequence[google.cloud.securitycenter_v2.types.AzureMetadata.AzureManagementGroup]): + A list of Azure management groups associated + with the resource, ordered from lowest level + (closest to the subscription) to highest level. + subscription (google.cloud.securitycenter_v2.types.AzureMetadata.AzureSubscription): + The Azure subscription associated with the + resource. + resource_group (google.cloud.securitycenter_v2.types.AzureMetadata.AzureResourceGroup): + The Azure resource group associated with the + resource. + """ + + class AzureManagementGroup(proto.Message): + r"""Represents an Azure management group. + + Attributes: + id (str): + The UUID of the Azure management group, for example, + ``20000000-0001-0000-0000-000000000000``. + display_name (str): + The display name of the Azure management + group. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + class AzureSubscription(proto.Message): + r"""Represents an Azure subscription. + + Attributes: + id (str): + The UUID of the Azure subscription, for example, + ``291bba3f-e0a5-47bc-a099-3bdcb2a50a05``. + display_name (str): + The display name of the Azure subscription. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + class AzureResourceGroup(proto.Message): + r"""Represents an Azure resource group. + + Attributes: + name (str): + The name of the Azure resource group. This is + not a UUID. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + management_groups: MutableSequence[AzureManagementGroup] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=AzureManagementGroup, + ) + subscription: AzureSubscription = proto.Field( + proto.MESSAGE, + number=2, + message=AzureSubscription, + ) + resource_group: AzureResourceGroup = proto.Field( + proto.MESSAGE, + number=3, + message=AzureResourceGroup, + ) + + +class ResourcePath(proto.Message): + r"""Represents the path of resources leading up to the resource + this finding is about. + + Attributes: + nodes (MutableSequence[google.cloud.securitycenter_v2.types.ResourcePath.ResourcePathNode]): + The list of nodes that make the up resource + path, ordered from lowest level to highest + level. + """ + class ResourcePathNodeType(proto.Enum): + r"""The type of resource the node represents. + + Values: + RESOURCE_PATH_NODE_TYPE_UNSPECIFIED (0): + Node type is unspecified. + GCP_ORGANIZATION (1): + The node represents a Google Cloud + organization. + GCP_FOLDER (2): + The node represents a Google Cloud folder. + GCP_PROJECT (3): + The node represents a Google Cloud project. + AWS_ORGANIZATION (4): + The node represents an AWS organization. + AWS_ORGANIZATIONAL_UNIT (5): + The node represents an AWS organizational + unit. + AWS_ACCOUNT (6): + The node represents an AWS account. + AZURE_MANAGEMENT_GROUP (7): + The node represents an Azure management + group. + AZURE_SUBSCRIPTION (8): + The node represents an Azure subscription. + AZURE_RESOURCE_GROUP (9): + The node represents an Azure resource group. + """ + RESOURCE_PATH_NODE_TYPE_UNSPECIFIED = 0 + GCP_ORGANIZATION = 1 + GCP_FOLDER = 2 + GCP_PROJECT = 3 + AWS_ORGANIZATION = 4 + AWS_ORGANIZATIONAL_UNIT = 5 + AWS_ACCOUNT = 6 + AZURE_MANAGEMENT_GROUP = 7 + AZURE_SUBSCRIPTION = 8 + AZURE_RESOURCE_GROUP = 9 + + class ResourcePathNode(proto.Message): + r"""A node within the resource path. Each node represents a + resource within the resource hierarchy. + + Attributes: + node_type (google.cloud.securitycenter_v2.types.ResourcePath.ResourcePathNodeType): + The type of resource this node represents. + id (str): + The ID of the resource this node represents. + display_name (str): + The display name of the resource this node + represents. + """ + + node_type: 'ResourcePath.ResourcePathNodeType' = proto.Field( + proto.ENUM, + number=1, + enum='ResourcePath.ResourcePathNodeType', + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + + nodes: MutableSequence[ResourcePathNode] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ResourcePathNode, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py new file mode 100644 index 000000000000..49a600dd79e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py @@ -0,0 +1,190 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v2.types import resource +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'ResourceValue', + 'ResourceValueConfig', + }, +) + + +class ResourceValue(proto.Enum): + r"""Value enum to map to a resource + + Values: + RESOURCE_VALUE_UNSPECIFIED (0): + Unspecific value + HIGH (1): + High resource value + MEDIUM (2): + Medium resource value + LOW (3): + Low resource value + NONE (4): + No resource value, e.g. ignore these + resources + """ + RESOURCE_VALUE_UNSPECIFIED = 0 + HIGH = 1 + MEDIUM = 2 + LOW = 3 + NONE = 4 + + +class ResourceValueConfig(proto.Message): + r"""A resource value configuration (RVC) is a mapping + configuration of user's resources to resource values. Used in + Attack path simulations. + + Attributes: + name (str): + Identifier. Name for the resource value + configuration + resource_value (google.cloud.securitycenter_v2.types.ResourceValue): + Resource value level this expression + represents Only required when there is no + Sensitive Data Protection mapping in the request + tag_values (MutableSequence[str]): + Tag values combined with ``AND`` to check against. Values in + the form "tagValues/123" Example: + ``[ "tagValues/123", "tagValues/456", "tagValues/789" ]`` + https://cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing + resource_type (str): + Apply resource_value only to resources that match + resource_type. resource_type will be checked with ``AND`` of + other resources. For example, + "storage.googleapis.com/Bucket" with resource_value "HIGH" + will apply "HIGH" value only to + "storage.googleapis.com/Bucket" resources. + scope (str): + Project or folder to scope this configuration to. For + example, "project/456" would apply this configuration only + to resources in "project/456" scope and will be checked with + ``AND`` of other resources. + resource_labels_selector (MutableMapping[str, str]): + List of resource labels to search for, evaluated with + ``AND``. For example, "resource_labels_selector": {"key": + "value", "env": "prod"} will match resources with labels + "key": "value" ``AND`` "env": "prod" + https://cloud.google.com/resource-manager/docs/creating-managing-labels + description (str): + Description of the resource value + configuration. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp this resource value + configuration was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp this resource value + configuration was last updated. + cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): + Cloud provider this configuration applies to + sensitive_data_protection_mapping (google.cloud.securitycenter_v2.types.ResourceValueConfig.SensitiveDataProtectionMapping): + A mapping of the sensitivity on Sensitive Data Protection + finding to resource values. This mapping can only be used in + combination with a resource_type that is related to + BigQuery, e.g. "bigquery.googleapis.com/Dataset". + """ + + class SensitiveDataProtectionMapping(proto.Message): + r"""Resource value mapping for Sensitive Data Protection findings If any + of these mappings have a resource value that is not unspecified, the + resource_value field will be ignored when reading this + configuration. + + Attributes: + high_sensitivity_mapping (google.cloud.securitycenter_v2.types.ResourceValue): + Resource value mapping for high-sensitivity + Sensitive Data Protection findings + medium_sensitivity_mapping (google.cloud.securitycenter_v2.types.ResourceValue): + Resource value mapping for medium-sensitivity + Sensitive Data Protection findings + """ + + high_sensitivity_mapping: 'ResourceValue' = proto.Field( + proto.ENUM, + number=1, + enum='ResourceValue', + ) + medium_sensitivity_mapping: 'ResourceValue' = proto.Field( + proto.ENUM, + number=2, + enum='ResourceValue', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_value: 'ResourceValue' = proto.Field( + proto.ENUM, + number=2, + enum='ResourceValue', + ) + tag_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + resource_type: str = proto.Field( + proto.STRING, + number=4, + ) + scope: str = proto.Field( + proto.STRING, + number=5, + ) + resource_labels_selector: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + description: str = proto.Field( + proto.STRING, + number=7, + ) + 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, + ) + cloud_provider: resource.CloudProvider = proto.Field( + proto.ENUM, + number=10, + enum=resource.CloudProvider, + ) + sensitive_data_protection_mapping: SensitiveDataProtectionMapping = proto.Field( + proto.MESSAGE, + number=11, + message=SensitiveDataProtectionMapping, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py new file mode 100644 index 000000000000..69a449132422 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.securitycenter.v2', + manifest={ + 'SecurityMarks', + }, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + The following list shows some examples: + + - ``organizations/{organization_id}/assets/{asset_id}/securityMarks`` + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` + marks (MutableMapping[str, str]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + canonical_name (str): + The canonical name of the marks. The following list shows + some examples: + + - ``organizations/{organization_id}/assets/{asset_id}/securityMarks`` + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` + + - ``folders/{folder_id}/assets/{asset_id}/securityMarks`` + - + + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks`` + + + ``folders/{folder_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` + + - ``projects/{project_number}/assets/{asset_id}/securityMarks`` + - + + ``projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks`` + + + ``projects/{project_number}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + marks: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.py new file mode 100644 index 000000000000..efa7cfc0b14d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'SecurityPosture', + }, +) + + +class SecurityPosture(proto.Message): + r"""Represents a posture that is deployed on Google Cloud by the + Security Command Center Posture Management service. A posture + contains one or more policy sets. A policy set is a group of + policies that enforce a set of security rules on Google Cloud. + + Attributes: + name (str): + Name of the posture, for example, ``CIS-Posture``. + revision_id (str): + The version of the posture, for example, ``c7cfa2a8``. + posture_deployment_resource (str): + The project, folder, or organization on which the posture is + deployed, for example, ``projects/{project_number}``. + posture_deployment (str): + The name of the posture deployment, for example, + ``organizations/{org_id}/posturedeployments/{posture_deployment_id}``. + changed_policy (str): + The name of the updated policy, for example, + ``projects/{project_id}/policies/{constraint_name}``. + policy_set (str): + The name of the updated policy set, for example, + ``cis-policyset``. + policy (str): + The ID of the updated policy, for example, + ``compute-policy-1``. + policy_drift_details (MutableSequence[google.cloud.securitycenter_v2.types.SecurityPosture.PolicyDriftDetails]): + The details about a change in an updated + policy that violates the deployed posture. + """ + + class PolicyDriftDetails(proto.Message): + r"""The policy field that violates the deployed posture and its + expected and detected values. + + Attributes: + field (str): + The name of the updated field, for example + constraint.implementation.policy_rules[0].enforce + expected_value (str): + The value of this field that was configured in a posture, + for example, ``true`` or + ``allowed_values={"projects/29831892"}``. + detected_value (str): + The detected value that violates the deployed posture, for + example, ``false`` or + ``allowed_values={"projects/22831892"}``. + """ + + field: str = proto.Field( + proto.STRING, + number=1, + ) + expected_value: str = proto.Field( + proto.STRING, + number=2, + ) + detected_value: str = proto.Field( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + ) + posture_deployment_resource: str = proto.Field( + proto.STRING, + number=3, + ) + posture_deployment: str = proto.Field( + proto.STRING, + number=4, + ) + changed_policy: str = proto.Field( + proto.STRING, + number=5, + ) + policy_set: str = proto.Field( + proto.STRING, + number=6, + ) + policy: str = proto.Field( + proto.STRING, + number=7, + ) + policy_drift_details: MutableSequence[PolicyDriftDetails] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=PolicyDriftDetails, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py new file mode 100644 index 000000000000..fdc56c6556a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py @@ -0,0 +1,1932 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v2.types import attack_path +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import resource as gcs_resource +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'BatchCreateResourceValueConfigsRequest', + 'BatchCreateResourceValueConfigsResponse', + 'BulkMuteFindingsRequest', + 'BulkMuteFindingsResponse', + 'CreateBigQueryExportRequest', + 'CreateFindingRequest', + 'CreateMuteConfigRequest', + 'CreateNotificationConfigRequest', + 'CreateResourceValueConfigRequest', + 'CreateSourceRequest', + 'DeleteBigQueryExportRequest', + 'DeleteMuteConfigRequest', + 'DeleteNotificationConfigRequest', + 'DeleteResourceValueConfigRequest', + 'GetBigQueryExportRequest', + 'GetMuteConfigRequest', + 'GetNotificationConfigRequest', + 'GetResourceValueConfigRequest', + 'GetSourceRequest', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAttackPathsRequest', + 'ListAttackPathsResponse', + 'GetSimulationRequest', + 'GetValuedResourceRequest', + 'ListBigQueryExportsRequest', + 'ListBigQueryExportsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListMuteConfigsRequest', + 'ListMuteConfigsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListResourceValueConfigsRequest', + 'ListResourceValueConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListValuedResourcesRequest', + 'ListValuedResourcesResponse', + 'SetFindingStateRequest', + 'SetMuteRequest', + 'UpdateBigQueryExportRequest', + 'UpdateExternalSystemRequest', + 'UpdateFindingRequest', + 'UpdateMuteConfigRequest', + 'UpdateNotificationConfigRequest', + 'UpdateResourceValueConfigRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + }, +) + + +class BatchCreateResourceValueConfigsRequest(proto.Message): + r"""Request message to create multiple resource value configs + + Attributes: + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. The parent field + in the CreateResourceValueConfigRequest messages + must either be empty or match this field. + requests (MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]): + Required. The resource value configs to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence['CreateResourceValueConfigRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='CreateResourceValueConfigRequest', + ) + + +class BatchCreateResourceValueConfigsResponse(proto.Message): + r"""Response message for BatchCreateResourceValueConfigs + + Attributes: + resource_value_configs (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfig]): + The resource value configs created + """ + + resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + + +class BulkMuteFindingsRequest(proto.Message): + r"""Request message for bulk findings update. + + Note: + + 1. If multiple bulk update requests match the same resource, the + order in which they get executed is not defined. + 2. Once a bulk operation is started, there is no way to stop it. + + Attributes: + parent (str): + Required. The parent, at which bulk action needs to be + applied. If no location is specified, findings are updated + in global. The following list shows some examples: + + - ``organizations/[organization_id]`` + - ``organizations/[organization_id]/locations/[location_id]`` + - ``folders/[folder_id]`` + - ``folders/[folder_id]/locations/[location_id]`` + - ``projects/[project_id]`` + - ``projects/[project_id]/locations/[location_id]`` + filter (str): + Expression that identifies findings that should be updated. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + mute_state (google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest.MuteState): + Optional. All findings matching the given filter will have + their mute state set to this value. The default value is + ``MUTED``. Setting this to ``UNDEFINED`` will clear the mute + state on all matching findings. + """ + class MuteState(proto.Enum): + r"""The mute state. + + Values: + MUTE_STATE_UNSPECIFIED (0): + Unused. + MUTED (1): + Matching findings will be muted (default). + UNDEFINED (2): + Matching findings will have their mute state + cleared. + """ + MUTE_STATE_UNSPECIFIED = 0 + MUTED = 1 + UNDEFINED = 2 + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + mute_state: MuteState = proto.Field( + proto.ENUM, + number=3, + enum=MuteState, + ) + + +class BulkMuteFindingsResponse(proto.Message): + r"""The response to a BulkMute request. Contains the LRO + information. + + """ + + +class CreateBigQueryExportRequest(proto.Message): + r"""Request message for creating a BigQuery export. + + Attributes: + parent (str): + Required. The name of the parent resource of the new + BigQuery export. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): + Required. The BigQuery export being created. + big_query_export_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must consist + of only lowercase letters, numbers, and hyphens, + must start with a letter, must end with either a + letter or a number, and must be 63 characters or + less. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + big_query_export: bigquery_export.BigQueryExport = proto.Field( + proto.MESSAGE, + number=2, + message=bigquery_export.BigQueryExport, + ) + big_query_export_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + + Attributes: + parent (str): + Required. Resource name of the new finding's parent. The + following list shows some examples of the format: + + ``organizations/[organization_id]/sources/[source_id]`` + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + alphanumeric and less than or equal to 32 + characters and greater than 0 characters in + length. + finding (google.cloud.securitycenter_v2.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + finding_id: str = proto.Field( + proto.STRING, + number=2, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_finding.Finding, + ) + + +class CreateMuteConfigRequest(proto.Message): + r"""Request message for creating a mute config. + + Attributes: + parent (str): + Required. Resource name of the new mute configs's parent. + Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + mute_config (google.cloud.securitycenter_v2.types.MuteConfig): + Required. The mute config being created. + mute_config_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must consist + of only lowercase letters, numbers, and hyphens, + must start with a letter, must end with either a + letter or a number, and must be 63 characters or + less. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + mute_config: gcs_mute_config.MuteConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_mute_config.MuteConfig, + ) + mute_config_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateNotificationConfigRequest(proto.Message): + r"""Request message for creating a notification config. + + Attributes: + parent (str): + Required. Resource name of the new notification config's + parent. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + config_id (str): + Required. + Unique identifier provided by the client within + the parent scope. It must be between 1 and 128 + characters and contain alphanumeric characters, + underscores, or hyphens only. + notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): + Required. The notification config being + created. The name and the service account will + be ignored as they are both output only fields + on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + config_id: str = proto.Field( + proto.STRING, + number=2, + ) + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_notification_config.NotificationConfig, + ) + + +class CreateResourceValueConfigRequest(proto.Message): + r"""Request message to create single resource value config + + Attributes: + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. + resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): + Required. The resource value config being + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_resource_value_config.ResourceValueConfig, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be ``organizations/[organization_id]``. + source (google.cloud.securitycenter_v2.types.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_source.Source, + ) + + +class DeleteBigQueryExportRequest(proto.Message): + r"""Request message for deleting a BigQuery export. + + Attributes: + name (str): + Required. The name of the BigQuery export to delete. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}/locations/{location}/bigQueryExports/{export_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteMuteConfigRequest(proto.Message): + r"""Request message for deleting a mute config. If no location is + specified, default is global. + + Attributes: + name (str): + Required. Name of the mute config to delete. The following + list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteNotificationConfigRequest(proto.Message): + r"""Request message for deleting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to delete. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_id]`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteResourceValueConfigRequest(proto.Message): + r"""Request message to delete resource value config + + Attributes: + name (str): + Required. Name of the ResourceValueConfig to + delete + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetBigQueryExportRequest(proto.Message): + r"""Request message for retrieving a BigQuery export. + + Attributes: + name (str): + Required. Name of the BigQuery export to retrieve. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}locations/{location}//bigQueryExports/{export_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetMuteConfigRequest(proto.Message): + r"""Request message for retrieving a mute config. If no location + is specified, default is global. + + Attributes: + name (str): + Required. Name of the mute config to retrieve. The following + list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetNotificationConfigRequest(proto.Message): + r"""Request message for getting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to get. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_id]`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetResourceValueConfigRequest(proto.Message): + r"""Request message to get resource value config + + Attributes: + name (str): + Required. Name of the resource value config to retrieve. Its + format is + organizations/{organization}/resourceValueConfigs/{config_id}. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is ``organizations/[organization_id]/source/[source_id]``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + + Attributes: + parent (str): + Required. Name of the source to groupBy. If no location is + specified, finding is assumed to be in global. The following + list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To groupBy across all sources provide a source_id of ``-``. + The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/[location_id]`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-/locations/[location_id]`` + - ``projects/{project_id}/sources/-`` + - ``projects/{project_id}/sources/-/locations/[location_id]`` + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - severity: ``=``, ``:`` + + - security_marks.marks: ``=``, ``:`` + + - resource: + + - resource.name: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "parent,resource_name". + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v2.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=struct_pb2.Value, + ) + count: int = proto.Field( + proto.INT64, + number=2, + ) + + +class ListAttackPathsRequest(proto.Message): + r"""Request message for listing the attack paths for a given + simulation or valued resource. + + Attributes: + parent (str): + Required. Name of parent to list attack paths. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + filter (str): + The filter expression that filters the attack path in the + response. Supported fields: + + - ``valued_resources`` supports = + page_token (str): + The value returned by the last ``ListAttackPathsResponse``; + indicates that this is a continuation of a prior + ``ListAttackPaths`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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 ListAttackPathsResponse(proto.Message): + r"""Response message for listing the attack paths for a given + simulation or valued resource. + + Attributes: + attack_paths (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath]): + The attack paths that the attack path + simulation identified. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + attack_paths: MutableSequence[attack_path.AttackPath] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=attack_path.AttackPath, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetSimulationRequest(proto.Message): + r"""Request message for getting simulation. + Simulation name can include "latest" to retrieve the latest + simulation For example, "organizations/123/simulations/latest" + + Attributes: + name (str): + Required. The organization name or simulation name of this + simulation + + Valid format: + ``organizations/{organization}/simulations/latest`` + ``organizations/{organization}/simulations/{simulation}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetValuedResourceRequest(proto.Message): + r"""Request message for getting a valued resource. + + Attributes: + name (str): + Required. The name of this valued resource + + Valid format: + ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListBigQueryExportsRequest(proto.Message): + r"""Request message for listing BigQuery exports at a given scope + e.g. organization, folder or project. + + Attributes: + parent (str): + Required. The parent, which owns the collection of BigQuery + exports. Its format is + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, or + ``projects/[project_id]/locations/[location_id]``. + page_size (int): + The maximum number of configs to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous + ``ListBigQueryExports`` call. Provide this to retrieve the + subsequent page. When paginating, all other parameters + provided to ``ListBigQueryExports`` 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 ListBigQueryExportsResponse(proto.Message): + r"""Response message for listing BigQuery exports. + + Attributes: + big_query_exports (MutableSequence[google.cloud.securitycenter_v2.types.BigQueryExport]): + The BigQuery exports from the specified + parent. + 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 + + big_query_exports: MutableSequence[bigquery_export.BigQueryExport] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=bigquery_export.BigQueryExport, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + + Attributes: + parent (str): + Required. Name of the source the findings belong to. If no + location is specified, the default is global. The following + list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To list across all sources provide a source_id of ``-``. The + following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/{location_id}`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-locations/{location_id}`` + - ``projects/{projects_id}/sources/-`` + - ``projects/{projects_id}/sources/-/locations/{location_id}`` + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - severity: ``=``, ``:`` + + - security_marks.marks: ``=``, ``:`` + + - resource: + + - resource.name: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + - resource.folders.resource_folder: ``=``, ``:`` + - resource.display_name: ``=``, ``:`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: "name,parent". The + default sorting order is ascending. To specify descending + order for a field, a suffix " desc" should be appended to + the field name. For example: "name desc,parent". Redundant + space characters in the syntax are insignificant. "name + desc,parent" and " name desc , parent " are equivalent. + + The following fields are supported: name parent state + category resource_name event_time security_marks.marks + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the Finding fields to + be listed in the response. An empty field mask + will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=9, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + + Attributes: + list_findings_results (MutableSequence[google.cloud.securitycenter_v2.types.ListFindingsResponse.ListFindingsResult]): + Findings matching the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + class ListFindingsResult(proto.Message): + r"""Result containing the Finding. + + Attributes: + finding (google.cloud.securitycenter_v2.types.Finding): + Finding matching the search request. + resource (google.cloud.securitycenter_v2.types.ListFindingsResponse.ListFindingsResult.Resource): + Output only. Resource that is associated with + this finding. + """ + + class Resource(proto.Message): + r"""Information related to the Google Cloud resource that is + associated with this finding. + + 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): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + display_name (str): + The human readable name of the resource. + type_ (str): + The full resource type of the resource. + cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): + Indicates which cloud provider the finding is + from. + service (str): + The service or resource provider associated + with the resource. + location (str): + The region or location of the service (if + applicable). + gcp_metadata (google.cloud.securitycenter_v2.types.GcpMetadata): + The GCP metadata associated with the finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + aws_metadata (google.cloud.securitycenter_v2.types.AwsMetadata): + The AWS metadata associated with the finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + azure_metadata (google.cloud.securitycenter_v2.types.AzureMetadata): + The Azure metadata associated with the + finding. + + This field is a member of `oneof`_ ``cloud_provider_metadata``. + resource_path (google.cloud.securitycenter_v2.types.ResourcePath): + Provides the path to the resource within the + resource hierarchy. + resource_path_string (str): + A string representation of the resource path. For Google + Cloud, it has the format of + ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` + where there can be any number of folders. For AWS, it has + the format of + ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` + where there can be any number of organizational units. For + Azure, it has the format of + ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` + where there can be any number of management groups. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + type_: str = proto.Field( + proto.STRING, + number=3, + ) + cloud_provider: gcs_resource.CloudProvider = proto.Field( + proto.ENUM, + number=4, + enum=gcs_resource.CloudProvider, + ) + service: str = proto.Field( + proto.STRING, + number=5, + ) + location: str = proto.Field( + proto.STRING, + number=6, + ) + gcp_metadata: gcs_resource.GcpMetadata = proto.Field( + proto.MESSAGE, + number=7, + oneof='cloud_provider_metadata', + message=gcs_resource.GcpMetadata, + ) + aws_metadata: gcs_resource.AwsMetadata = proto.Field( + proto.MESSAGE, + number=8, + oneof='cloud_provider_metadata', + message=gcs_resource.AwsMetadata, + ) + azure_metadata: gcs_resource.AzureMetadata = proto.Field( + proto.MESSAGE, + number=9, + oneof='cloud_provider_metadata', + message=gcs_resource.AzureMetadata, + ) + resource_path: gcs_resource.ResourcePath = proto.Field( + proto.MESSAGE, + number=10, + message=gcs_resource.ResourcePath, + ) + resource_path_string: str = proto.Field( + proto.STRING, + number=11, + ) + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + resource: 'ListFindingsResponse.ListFindingsResult.Resource' = proto.Field( + proto.MESSAGE, + number=3, + message='ListFindingsResponse.ListFindingsResult.Resource', + ) + + @property + def raw_page(self): + return self + + list_findings_results: MutableSequence[ListFindingsResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListFindingsResult, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListMuteConfigsRequest(proto.Message): + r"""Request message for listing mute configs at a given scope + e.g. organization, folder or project. If no location is + specified, default is global. + + Attributes: + parent (str): + Required. The parent, which owns the collection of mute + configs. Its format is + ``organizations/[organization_id]", "folders/[folder_id]``, + ``projects/[project_id]``, + ``organizations/[organization_id]/locations/[location_id]``, + ``folders/[folder_id]/locations/[location_id]``, + ``projects/[project_id]/locations/[location_id]``. + page_size (int): + The maximum number of configs to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListMuteConfigs`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListMuteConfigs`` 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 ListMuteConfigsResponse(proto.Message): + r"""Response message for listing mute configs. + + Attributes: + mute_configs (MutableSequence[google.cloud.securitycenter_v2.types.MuteConfig]): + The mute configs from the specified parent. + 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 + + mute_configs: MutableSequence[gcs_mute_config.MuteConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_mute_config.MuteConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListNotificationConfigsRequest(proto.Message): + r"""Request message for listing notification configs. + + Attributes: + parent (str): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + page_token (str): + The value returned by the last + ``ListNotificationConfigsResponse``; indicates that this is + a continuation of a prior ``ListNotificationConfigs`` call, + and that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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 ListNotificationConfigsResponse(proto.Message): + r"""Response message for listing notification configs. + + Attributes: + notification_configs (MutableSequence[google.cloud.securitycenter_v2.types.NotificationConfig]): + Notification configs belonging to the + requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + notification_configs: MutableSequence[gcs_notification_config.NotificationConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListResourceValueConfigsRequest(proto.Message): + r"""Request message to list resource value configs of a parent + + Attributes: + parent (str): + Required. The parent, which owns the collection of resource + value configs. Its format is + ``organizations/[organization_id]`` + page_size (int): + The maximum number of configs to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous + ``ListResourceValueConfigs`` call. Provide this to retrieve + the subsequent page. + + When paginating, all other parameters provided to + ``ListResourceValueConfigs`` must match the call that + provided the page token. + + page_size can be specified, and the new page_size 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, + ) + + +class ListResourceValueConfigsResponse(proto.Message): + r"""Response message to list resource value configs + + Attributes: + resource_value_configs (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfig]): + The resource value configs from the specified + parent. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is empty, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be ``organizations/[organization_id]``, + ``folders/[folder_id]``, or ``projects/[project_id]``. + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + 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=7, + ) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v2.types.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListValuedResourcesRequest(proto.Message): + r"""Request message for listing the valued resources for a given + simulation. + + Attributes: + parent (str): + Required. Name of parent to list exposed resources. + + Valid formats: ``organizations/{organization}``, + ``organizations/{organization}/simulations/{simulation}`` + ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` + filter (str): + The filter expression that filters the valued resources in + the response. Supported fields: + + - ``resource_value`` supports = + - ``resource_type`` supports = + page_token (str): + The value returned by the last + ``ListValuedResourcesResponse``; indicates that this is a + continuation of a prior ``ListValuedResources`` call, and + that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + order_by (str): + Optional. The fields by which to order the valued resources + response. + + Supported fields: + + - ``exposed_score`` + + - ``resource_value`` + + - ``resource_type`` + + Values should be a comma separated list of fields. For + example: ``exposed_score,resource_value``. + + The default sorting order is descending. To specify + ascending or descending order for a field, append a " ASC" + or a " DESC" suffix, respectively; for example: + ``exposed_score DESC``. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListValuedResourcesResponse(proto.Message): + r"""Response message for listing the valued resources for a given + simulation. + + Attributes: + valued_resources (MutableSequence[google.cloud.securitycenter_v2.types.ValuedResource]): + The valued resources that the attack path + simulation identified. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The estimated total number of results + matching the query. + """ + + @property + def raw_page(self): + return self + + valued_resources: MutableSequence[valued_resource.ValuedResource] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=valued_resource.ValuedResource, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + + Attributes: + name (str): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + state (google.cloud.securitycenter_v2.types.Finding.State): + Required. The desired State of the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: gcs_finding.Finding.State = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.State, + ) + + +class SetMuteRequest(proto.Message): + r"""Request message for updating a finding's mute status. + + Attributes: + name (str): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + mute (google.cloud.securitycenter_v2.types.Finding.Mute): + Required. The desired state of the Mute. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + mute: gcs_finding.Finding.Mute = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.Mute, + ) + + +class UpdateBigQueryExportRequest(proto.Message): + r"""Request message for updating a BigQuery export. + + Attributes: + big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): + Required. The BigQuery export being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + big_query_export: bigquery_export.BigQueryExport = proto.Field( + proto.MESSAGE, + number=1, + message=bigquery_export.BigQueryExport, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateExternalSystemRequest(proto.Message): + r"""Request message for updating a ExternalSystem resource. + + Attributes: + external_system (google.cloud.securitycenter_v2.types.ExternalSystem): + Required. The external system resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + external system resource. + If empty all mutable fields will be updated. + """ + + external_system: gcs_external_system.ExternalSystem = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_external_system.ExternalSystem, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + + Attributes: + finding (google.cloud.securitycenter_v2.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must be alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing source_properties. + Individual source_properties can be added/updated by using + "source_properties." in the field mask. + """ + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateMuteConfigRequest(proto.Message): + r"""Request message for updating a mute config. + + Attributes: + mute_config (google.cloud.securitycenter_v2.types.MuteConfig): + Required. The mute config being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + mute_config: gcs_mute_config.MuteConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_mute_config.MuteConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateNotificationConfigRequest(proto.Message): + r"""Request message for updating a notification config. + + Attributes: + notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): + Required. The notification config to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + notification config. + If empty all mutable fields will be updated. + """ + + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateResourceValueConfigRequest(proto.Message): + r"""Request message to update resource value config + + Attributes: + resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): + Required. The resource value config being + updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If empty all mutable + fields will be updated. + + To update nested fields, include the top level field in the + mask For example, to update gcp_metadata.resource_type, + include the "gcp_metadata" field mask + """ + + resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): + Required. The security marks resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If empty + or set to "marks", all marks will be replaced. Individual + marks can be updated using "marks.". + """ + + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_marks.SecurityMarks, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (google.cloud.securitycenter_v2.types.Source): + Required. The source resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the source + resource. + If empty all mutable fields will be updated. + """ + + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + 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-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py new file mode 100644 index 000000000000..5c64646490da --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the 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.securitycenter_v2.types import resource +from google.cloud.securitycenter_v2.types import valued_resource +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Simulation', + }, +) + + +class Simulation(proto.Message): + r"""Attack path simulation + + Attributes: + name (str): + Full resource name of the Simulation: + ``organizations/123/simulations/456`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time simulation was created + resource_value_configs_metadata (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfigMetadata]): + Resource value configurations' metadata used + in this simulation. Maximum of 100. + cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): + Indicates which cloud provider was used in + this simulation. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + resource_value_configs_metadata: MutableSequence[valued_resource.ResourceValueConfigMetadata] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=valued_resource.ResourceValueConfigMetadata, + ) + cloud_provider: resource.CloudProvider = proto.Field( + proto.ENUM, + number=4, + enum=resource.CloudProvider, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.py new file mode 100644 index 000000000000..006e16a02f4a --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'Source', + }, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, and other tools. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and outdated or + insecure libraries.". + canonical_name (str): + The canonical name of the finding source. It's either + "organizations/{organization_id}/sources/{source_id}", + "folders/{folder_id}/sources/{source_id}", or + "projects/{project_number}/sources/{source_id}", depending + on the closest CRM ancestor of the resource associated with + the finding. + """ + + 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, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.py new file mode 100644 index 000000000000..e70d9aa2e281 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'ToxicCombination', + }, +) + + +class ToxicCombination(proto.Message): + r"""Contains details about a group of security issues that, when + the issues occur together, represent a greater risk than when + the issues occur independently. A group of such issues is + referred to as a toxic combination. + + Attributes: + attack_exposure_score (float): + The `Attack exposure + score `__ + of this toxic combination. The score is a measure of how + much this toxic combination exposes one or more high-value + resources to potential attack. + related_findings (MutableSequence[str]): + List of resource names of findings associated with this + toxic combination. For example, + ``organizations/123/sources/456/findings/789``. + """ + + attack_exposure_score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + related_findings: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.py new file mode 100644 index 000000000000..ed481ba587b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v2', + manifest={ + 'ValuedResource', + 'ResourceValueConfigMetadata', + }, +) + + +class ValuedResource(proto.Message): + r"""A resource that is determined to have value to a user's + system + + Attributes: + name (str): + Valued resource name, for example, e.g.: + ``organizations/123/simulations/456/valuedResources/789`` + resource (str): + The `full resource + name `__ + of the valued resource. + resource_type (str): + The `resource + type `__ + of the valued resource. + display_name (str): + Human-readable name of the valued resource. + resource_value (google.cloud.securitycenter_v2.types.ValuedResource.ResourceValue): + How valuable this resource is. + exposed_score (float): + Exposed score for this valued resource. A + value of 0 means no exposure was detected + exposure. + resource_value_configs_used (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfigMetadata]): + List of resource value configurations' + metadata used to determine the value of this + resource. Maximum of 100. + """ + class ResourceValue(proto.Enum): + r"""How valuable the resource is. + + Values: + RESOURCE_VALUE_UNSPECIFIED (0): + The resource value isn't specified. + RESOURCE_VALUE_LOW (1): + This is a low-value resource. + RESOURCE_VALUE_MEDIUM (2): + This is a medium-value resource. + RESOURCE_VALUE_HIGH (3): + This is a high-value resource. + """ + RESOURCE_VALUE_UNSPECIFIED = 0 + RESOURCE_VALUE_LOW = 1 + RESOURCE_VALUE_MEDIUM = 2 + RESOURCE_VALUE_HIGH = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource: str = proto.Field( + proto.STRING, + number=2, + ) + resource_type: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + resource_value: ResourceValue = proto.Field( + proto.ENUM, + number=5, + enum=ResourceValue, + ) + exposed_score: float = proto.Field( + proto.DOUBLE, + number=6, + ) + resource_value_configs_used: MutableSequence['ResourceValueConfigMetadata'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='ResourceValueConfigMetadata', + ) + + +class ResourceValueConfigMetadata(proto.Message): + r"""Metadata about a ResourceValueConfig. For example, id and + name. + + Attributes: + name (str): + Resource value config name + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.py new file mode 100644 index 000000000000..79c7e06db637 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.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. +# +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.securitycenter.v2', + manifest={ + 'Vulnerability', + 'Cve', + 'Reference', + 'Cvssv3', + 'Package', + 'SecurityBulletin', + }, +) + + +class Vulnerability(proto.Message): + r"""Refers to common vulnerability fields e.g. cve, cvss, cwe + etc. + + Attributes: + cve (google.cloud.securitycenter_v2.types.Cve): + CVE stands for Common Vulnerabilities and + Exposures (https://cve.mitre.org/about/) + offending_package (google.cloud.securitycenter_v2.types.Package): + The offending package is relevant to the + finding. + fixed_package (google.cloud.securitycenter_v2.types.Package): + The fixed package is relevant to the finding. + security_bulletin (google.cloud.securitycenter_v2.types.SecurityBulletin): + The security bulletin is relevant to this + finding. + """ + + cve: 'Cve' = proto.Field( + proto.MESSAGE, + number=1, + message='Cve', + ) + offending_package: 'Package' = proto.Field( + proto.MESSAGE, + number=2, + message='Package', + ) + fixed_package: 'Package' = proto.Field( + proto.MESSAGE, + number=3, + message='Package', + ) + security_bulletin: 'SecurityBulletin' = proto.Field( + proto.MESSAGE, + number=4, + message='SecurityBulletin', + ) + + +class Cve(proto.Message): + r"""CVE stands for Common Vulnerabilities and Exposures. Information + from the `CVE + record `__ that + describes this vulnerability. + + Attributes: + id (str): + The unique identifier for the vulnerability. + e.g. CVE-2021-34527 + references (MutableSequence[google.cloud.securitycenter_v2.types.Reference]): + Additional information about the CVE. + e.g. + https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527 + cvssv3 (google.cloud.securitycenter_v2.types.Cvssv3): + Describe Common Vulnerability Scoring System + specified at + https://www.first.org/cvss/v3.1/specification-document + upstream_fix_available (bool): + Whether upstream fix is available for the + CVE. + impact (google.cloud.securitycenter_v2.types.Cve.RiskRating): + The potential impact of the vulnerability if + it was to be exploited. + exploitation_activity (google.cloud.securitycenter_v2.types.Cve.ExploitationActivity): + The exploitation activity of the + vulnerability in the wild. + observed_in_the_wild (bool): + Whether or not the vulnerability has been + observed in the wild. + zero_day (bool): + Whether or not the vulnerability was zero day + when the finding was published. + exploit_release_date (google.protobuf.timestamp_pb2.Timestamp): + Date the first publicly available exploit or + PoC was released. + """ + class RiskRating(proto.Enum): + r"""The possible values of impact of the vulnerability if it was + to be exploited. + + Values: + RISK_RATING_UNSPECIFIED (0): + Invalid or empty value. + LOW (1): + Exploitation would have little to no security + impact. + MEDIUM (2): + Exploitation would enable attackers to + perform activities, or could allow attackers to + have a direct impact, but would require + additional steps. + HIGH (3): + Exploitation would enable attackers to have a + notable direct impact without needing to + overcome any major mitigating factors. + CRITICAL (4): + Exploitation would fundamentally undermine + the security of affected systems, enable actors + to perform significant attacks with minimal + effort, with little to no mitigating factors to + overcome. + """ + RISK_RATING_UNSPECIFIED = 0 + LOW = 1 + MEDIUM = 2 + HIGH = 3 + CRITICAL = 4 + + class ExploitationActivity(proto.Enum): + r"""The possible values of exploitation activity of the + vulnerability in the wild. + + Values: + EXPLOITATION_ACTIVITY_UNSPECIFIED (0): + Invalid or empty value. + WIDE (1): + Exploitation has been reported or confirmed + to widely occur. + CONFIRMED (2): + Limited reported or confirmed exploitation + activities. + AVAILABLE (3): + Exploit is publicly available. + ANTICIPATED (4): + No known exploitation activity, but has a + high potential for exploitation. + NO_KNOWN (5): + No known exploitation activity. + """ + EXPLOITATION_ACTIVITY_UNSPECIFIED = 0 + WIDE = 1 + CONFIRMED = 2 + AVAILABLE = 3 + ANTICIPATED = 4 + NO_KNOWN = 5 + + id: str = proto.Field( + proto.STRING, + number=1, + ) + references: MutableSequence['Reference'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Reference', + ) + cvssv3: 'Cvssv3' = proto.Field( + proto.MESSAGE, + number=3, + message='Cvssv3', + ) + upstream_fix_available: bool = proto.Field( + proto.BOOL, + number=4, + ) + impact: RiskRating = proto.Field( + proto.ENUM, + number=5, + enum=RiskRating, + ) + exploitation_activity: ExploitationActivity = proto.Field( + proto.ENUM, + number=6, + enum=ExploitationActivity, + ) + observed_in_the_wild: bool = proto.Field( + proto.BOOL, + number=7, + ) + zero_day: bool = proto.Field( + proto.BOOL, + number=8, + ) + exploit_release_date: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + + +class Reference(proto.Message): + r"""Additional Links + + Attributes: + source (str): + Source of the reference e.g. NVD + uri (str): + Uri for the mentioned source e.g. + https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527. + """ + + source: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Cvssv3(proto.Message): + r"""Common Vulnerability Scoring System version 3. + + Attributes: + base_score (float): + The base score is a function of the base + metric scores. + attack_vector (google.cloud.securitycenter_v2.types.Cvssv3.AttackVector): + Base Metrics + Represents the intrinsic characteristics of a + vulnerability that are constant over time and + across user environments. This metric reflects + the context by which vulnerability exploitation + is possible. + attack_complexity (google.cloud.securitycenter_v2.types.Cvssv3.AttackComplexity): + This metric describes the conditions beyond + the attacker's control that must exist in order + to exploit the vulnerability. + privileges_required (google.cloud.securitycenter_v2.types.Cvssv3.PrivilegesRequired): + This metric describes the level of privileges + an attacker must possess before successfully + exploiting the vulnerability. + user_interaction (google.cloud.securitycenter_v2.types.Cvssv3.UserInteraction): + This metric captures the requirement for a + human user, other than the attacker, to + participate in the successful compromise of the + vulnerable component. + scope (google.cloud.securitycenter_v2.types.Cvssv3.Scope): + The Scope metric captures whether a + vulnerability in one vulnerable component + impacts resources in components beyond its + security scope. + confidentiality_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): + This metric measures the impact to the + confidentiality of the information resources + managed by a software component due to a + successfully exploited vulnerability. + integrity_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): + This metric measures the impact to integrity + of a successfully exploited vulnerability. + availability_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): + This metric measures the impact to the + availability of the impacted component resulting + from a successfully exploited vulnerability. + """ + class AttackVector(proto.Enum): + r"""This metric reflects the context by which vulnerability + exploitation is possible. + + Values: + ATTACK_VECTOR_UNSPECIFIED (0): + Invalid value. + ATTACK_VECTOR_NETWORK (1): + The vulnerable component is bound to the + network stack and the set of possible attackers + extends beyond the other options listed below, + up to and including the entire Internet. + ATTACK_VECTOR_ADJACENT (2): + The vulnerable component is bound to the + network stack, but the attack is limited at the + protocol level to a logically adjacent topology. + ATTACK_VECTOR_LOCAL (3): + The vulnerable component is not bound to the + network stack and the attacker's path is via + read/write/execute capabilities. + ATTACK_VECTOR_PHYSICAL (4): + The attack requires the attacker to + physically touch or manipulate the vulnerable + component. + """ + ATTACK_VECTOR_UNSPECIFIED = 0 + ATTACK_VECTOR_NETWORK = 1 + ATTACK_VECTOR_ADJACENT = 2 + ATTACK_VECTOR_LOCAL = 3 + ATTACK_VECTOR_PHYSICAL = 4 + + class AttackComplexity(proto.Enum): + r"""This metric describes the conditions beyond the attacker's + control that must exist in order to exploit the vulnerability. + + Values: + ATTACK_COMPLEXITY_UNSPECIFIED (0): + Invalid value. + ATTACK_COMPLEXITY_LOW (1): + Specialized access conditions or extenuating + circumstances do not exist. An attacker can + expect repeatable success when attacking the + vulnerable component. + ATTACK_COMPLEXITY_HIGH (2): + A successful attack depends on conditions + beyond the attacker's control. That is, a + successful attack cannot be accomplished at + will, but requires the attacker to invest in + some measurable amount of effort in preparation + or execution against the vulnerable component + before a successful attack can be expected. + """ + ATTACK_COMPLEXITY_UNSPECIFIED = 0 + ATTACK_COMPLEXITY_LOW = 1 + ATTACK_COMPLEXITY_HIGH = 2 + + class PrivilegesRequired(proto.Enum): + r"""This metric describes the level of privileges an attacker + must possess before successfully exploiting the vulnerability. + + Values: + PRIVILEGES_REQUIRED_UNSPECIFIED (0): + Invalid value. + PRIVILEGES_REQUIRED_NONE (1): + The attacker is unauthorized prior to attack, + and therefore does not require any access to + settings or files of the vulnerable system to + carry out an attack. + PRIVILEGES_REQUIRED_LOW (2): + The attacker requires privileges that provide + basic user capabilities that could normally + affect only settings and files owned by a user. + Alternatively, an attacker with Low privileges + has the ability to access only non-sensitive + resources. + PRIVILEGES_REQUIRED_HIGH (3): + The attacker requires privileges that provide + significant (e.g., administrative) control over + the vulnerable component allowing access to + component-wide settings and files. + """ + PRIVILEGES_REQUIRED_UNSPECIFIED = 0 + PRIVILEGES_REQUIRED_NONE = 1 + PRIVILEGES_REQUIRED_LOW = 2 + PRIVILEGES_REQUIRED_HIGH = 3 + + class UserInteraction(proto.Enum): + r"""This metric captures the requirement for a human user, other + than the attacker, to participate in the successful compromise + of the vulnerable component. + + Values: + USER_INTERACTION_UNSPECIFIED (0): + Invalid value. + USER_INTERACTION_NONE (1): + The vulnerable system can be exploited + without interaction from any user. + USER_INTERACTION_REQUIRED (2): + Successful exploitation of this vulnerability + requires a user to take some action before the + vulnerability can be exploited. + """ + USER_INTERACTION_UNSPECIFIED = 0 + USER_INTERACTION_NONE = 1 + USER_INTERACTION_REQUIRED = 2 + + class Scope(proto.Enum): + r"""The Scope metric captures whether a vulnerability in one + vulnerable component impacts resources in components beyond its + security scope. + + Values: + SCOPE_UNSPECIFIED (0): + Invalid value. + SCOPE_UNCHANGED (1): + An exploited vulnerability can only affect + resources managed by the same security + authority. + SCOPE_CHANGED (2): + An exploited vulnerability can affect + resources beyond the security scope managed by + the security authority of the vulnerable + component. + """ + SCOPE_UNSPECIFIED = 0 + SCOPE_UNCHANGED = 1 + SCOPE_CHANGED = 2 + + class Impact(proto.Enum): + r"""The Impact metrics capture the effects of a successfully + exploited vulnerability on the component that suffers the worst + outcome that is most directly and predictably associated with + the attack. + + Values: + IMPACT_UNSPECIFIED (0): + Invalid value. + IMPACT_HIGH (1): + High impact. + IMPACT_LOW (2): + Low impact. + IMPACT_NONE (3): + No impact. + """ + IMPACT_UNSPECIFIED = 0 + IMPACT_HIGH = 1 + IMPACT_LOW = 2 + IMPACT_NONE = 3 + + base_score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + attack_vector: AttackVector = proto.Field( + proto.ENUM, + number=2, + enum=AttackVector, + ) + attack_complexity: AttackComplexity = proto.Field( + proto.ENUM, + number=3, + enum=AttackComplexity, + ) + privileges_required: PrivilegesRequired = proto.Field( + proto.ENUM, + number=4, + enum=PrivilegesRequired, + ) + user_interaction: UserInteraction = proto.Field( + proto.ENUM, + number=5, + enum=UserInteraction, + ) + scope: Scope = proto.Field( + proto.ENUM, + number=6, + enum=Scope, + ) + confidentiality_impact: Impact = proto.Field( + proto.ENUM, + number=7, + enum=Impact, + ) + integrity_impact: Impact = proto.Field( + proto.ENUM, + number=8, + enum=Impact, + ) + availability_impact: Impact = proto.Field( + proto.ENUM, + number=9, + enum=Impact, + ) + + +class Package(proto.Message): + r"""Package is a generic definition of a package. + + Attributes: + package_name (str): + The name of the package where the + vulnerability was detected. + cpe_uri (str): + The CPE URI where the vulnerability was + detected. + package_type (str): + Type of package, for example, os, maven, or + go. + package_version (str): + The version of the package. + """ + + package_name: str = proto.Field( + proto.STRING, + number=1, + ) + cpe_uri: str = proto.Field( + proto.STRING, + number=2, + ) + package_type: str = proto.Field( + proto.STRING, + number=3, + ) + package_version: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SecurityBulletin(proto.Message): + r"""SecurityBulletin are notifications of vulnerabilities of + Google products. + + Attributes: + bulletin_id (str): + ID of the bulletin corresponding to the + vulnerability. + submission_time (google.protobuf.timestamp_pb2.Timestamp): + Submission time of this Security Bulletin. + suggested_upgrade_version (str): + This represents a version that the cluster + receiving this notification should be upgraded + to, based on its current version. For example, + 1.15.0 + """ + + bulletin_id: str = proto.Field( + proto.STRING, + number=1, + ) + submission_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + suggested_upgrade_version: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v2/noxfile.py new file mode 100644 index 000000000000..cd78e7c39a06 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-securitycenter' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +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"): + 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/securitycenter_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"): + 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", + "grpcio", + "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/securitycenter_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( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): + # Ignore release of mypy 1.11.0 which may have a regression + 'mypy!=1.11.0', + '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-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py new file mode 100644 index 000000000000..e74e57a22631 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + requests = securitycenter_v2.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + + request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py new file mode 100644 index 000000000000..d6c2ad8428ff --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + requests = securitycenter_v2.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + + request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py new file mode 100644 index 000000000000..4b2fd03c3f02 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_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 BulkMuteFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py new file mode 100644 index 000000000000..743d1302b400 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_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 BulkMuteFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py new file mode 100644 index 000000000000..1698ad6adc92 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_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 CreateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_create_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = await client.create_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py new file mode 100644 index 000000000000..becab1857b3c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_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 CreateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_create_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = client.create_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py new file mode 100644 index 000000000000..3a2c089e9019 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_create_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py new file mode 100644 index 000000000000..4294f4ffd397 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_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 CreateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_create_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py new file mode 100644 index 000000000000..c858b59a6586 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_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 CreateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_create_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = await client.create_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py new file mode 100644 index 000000000000..a0de28b38bbd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_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 CreateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_create_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = client.create_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py new file mode 100644 index 000000000000..ae681f4e8f3e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_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 CreateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_create_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py new file mode 100644 index 000000000000..0bf75d6458fd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_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 CreateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_create_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py new file mode 100644 index 000000000000..9afb50b6e83e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_create_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py new file mode 100644 index 000000000000..af9c2b763cc6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_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 CreateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_create_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py new file mode 100644 index 000000000000..4aac72fa5605 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + await client.delete_big_query_export(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py new file mode 100644 index 000000000000..b278bde5e5ae --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + client.delete_big_query_export(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py new file mode 100644 index 000000000000..10ceee02e146 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_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 DeleteMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_delete_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_mute_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py new file mode 100644 index 000000000000..a051c7c17741 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_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 DeleteMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_delete_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_mute_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py new file mode 100644 index 000000000000..fceb0255c2bd --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_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 DeleteNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py new file mode 100644 index 000000000000..906f2a39092c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_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 DeleteNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_delete_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py new file mode 100644 index 000000000000..191842b98c8f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_resource_value_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py new file mode 100644 index 000000000000..e8aac97d4f8d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_resource_value_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py new file mode 100644 index 000000000000..14de594a963c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_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 GetBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py new file mode 100644 index 000000000000..a8d4416456ab --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_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 GetBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = client.get_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py new file mode 100644 index 000000000000..04061abcf9a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py new file mode 100644 index 000000000000..4d9d6d45b825 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_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 GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py new file mode 100644 index 000000000000..348376a0b9b4 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_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 GetMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py new file mode 100644 index 000000000000..84adb2a92f59 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_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 GetMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py new file mode 100644 index 000000000000..73885369a61e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_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 GetNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py new file mode 100644 index 000000000000..84d892dabf5f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_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 GetNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py new file mode 100644 index 000000000000..4076aa39fbc6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_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 GetResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py new file mode 100644 index 000000000000..814ba5a717d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_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 GetResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py new file mode 100644 index 000000000000..4cf61313cb96 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_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 GetSimulation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetSimulation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_simulation(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_simulation(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetSimulation_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py new file mode 100644 index 000000000000..572655cf48c9 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_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 GetSimulation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetSimulation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_simulation(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = client.get_simulation(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetSimulation_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py new file mode 100644 index 000000000000..685b7f0cc423 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py new file mode 100644 index 000000000000..a33bef8b910d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_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 GetSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py new file mode 100644 index 000000000000..b0601f503c25 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_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 GetValuedResource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetValuedResource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_get_valued_resource(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_valued_resource(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetValuedResource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py new file mode 100644 index 000000000000..ed7d7630288d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_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 GetValuedResource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetValuedResource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_get_valued_resource(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_valued_resource(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetValuedResource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py new file mode 100644 index 000000000000..d829f16c868e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GroupFindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_group_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py new file mode 100644 index 000000000000..d7e8c0a21523 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_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 GroupFindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GroupFindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_group_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py new file mode 100644 index 000000000000..ed648fdea30d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_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 ListAttackPaths +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListAttackPaths_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_attack_paths(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListAttackPaths_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py new file mode 100644 index 000000000000..bdecd1972ff1 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_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 ListAttackPaths +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListAttackPaths_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_attack_paths(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListAttackPaths_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py new file mode 100644 index 000000000000..405bc21b0f37 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_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 ListBigQueryExports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py new file mode 100644 index 000000000000..ccb98f95fa3c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_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 ListBigQueryExports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py new file mode 100644 index 000000000000..bb6c9e3c9bc9 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_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 securitycenter_v2 + + +async def sample_list_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py new file mode 100644 index 000000000000..190548636c6f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_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 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_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 securitycenter_v2 + + +def sample_list_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py new file mode 100644 index 000000000000..50ec2b1fd631 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_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 ListMuteConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_mute_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py new file mode 100644 index 000000000000..d28a0e6adb61 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_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 ListMuteConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_mute_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py new file mode 100644 index 000000000000..7b12a639c763 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_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 ListNotificationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py new file mode 100644 index 000000000000..d1cffc2d7793 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_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 ListNotificationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_notification_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py new file mode 100644 index 000000000000..9f8a6124f4d6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_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 ListResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py new file mode 100644 index 000000000000..cfc3651b5540 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_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 ListResourceValueConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py new file mode 100644 index 000000000000..447f27ccaa16 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListSources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_sources(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py new file mode 100644 index 000000000000..9447d7eb91ee --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_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 ListSources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListSources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_sources(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py new file mode 100644 index 000000000000..1c17d84f91cb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_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 ListValuedResources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListValuedResources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_list_valued_resources(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListValuedResources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py new file mode 100644 index 000000000000..616675828d82 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_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 ListValuedResources +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListValuedResources_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_list_valued_resources(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListValuedResources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py new file mode 100644 index 000000000000..905eb5d7db22 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetFindingState_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_set_finding_state(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py new file mode 100644 index 000000000000..339e22bde563 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_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 SetFindingState +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetFindingState_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_set_finding_state(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py new file mode 100644 index 000000000000..2c74d459d83f --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py new file mode 100644 index 000000000000..4e5ef3b13cbf --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_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 SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py new file mode 100644 index 000000000000..fa80c37c66ca --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_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 SetMute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetMute_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_set_mute(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = await client.set_mute(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetMute_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py new file mode 100644 index 000000000000..9355527a6bac --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_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 SetMute +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetMute_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_set_mute(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = client.set_mute(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetMute_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py new file mode 100644 index 000000000000..3ccd4f4848bb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py new file mode 100644 index 000000000000..6df1fda9cf90 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_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 TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py new file mode 100644 index 000000000000..365c17bd2756 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_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 UpdateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateBigQueryExportRequest( + ) + + # Make the request + response = await client.update_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py new file mode 100644 index 000000000000..18b99ec2462e --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_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 UpdateBigQueryExport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateBigQueryExportRequest( + ) + + # Make the request + response = client.update_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py new file mode 100644 index 000000000000..179da29467bb --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_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 UpdateExternalSystem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_external_system(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateExternalSystemRequest( + ) + + # Make the request + response = await client.update_external_system(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py new file mode 100644 index 000000000000..6a68970514cc --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_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 UpdateExternalSystem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_external_system(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateExternalSystemRequest( + ) + + # Make the request + response = client.update_external_system(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py new file mode 100644 index 000000000000..245e358b0eea --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateFinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py new file mode 100644 index 000000000000..512e315aa049 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_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 UpdateFinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateFinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py new file mode 100644 index 000000000000..7796c39566e2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_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 UpdateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = await client.update_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py new file mode 100644 index 000000000000..920f6986fb3b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_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 UpdateMuteConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "DYNAMIC" + + request = securitycenter_v2.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = client.update_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py new file mode 100644 index 000000000000..bed9621bb2ea --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_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 UpdateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py new file mode 100644 index 000000000000..ed5516437b4d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_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 UpdateNotificationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py new file mode 100644 index 000000000000..0ecd6b7d2fd5 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_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 UpdateResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateResourceValueConfigRequest( + ) + + # Make the request + response = await client.update_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py new file mode 100644 index 000000000000..2508104c843d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_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 UpdateResourceValueConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateResourceValueConfigRequest( + ) + + # Make the request + response = client.update_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py new file mode 100644 index 000000000000..faf2900ce05c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_security_marks(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py new file mode 100644 index 000000000000..9843735d4ad6 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_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 UpdateSecurityMarks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_security_marks(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py new file mode 100644 index 000000000000..39f5bd6e19c2 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +async def sample_update_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py new file mode 100644 index 000000000000..f138fd97e1ec --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_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 UpdateSource +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateSource_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 + + +def sample_update_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json new file mode 100644 index 000000000000..3ebbbfe28b50 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json @@ -0,0 +1,6607 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.securitycenter.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-cloud-securitycenter", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.batch_create_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BatchCreateResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BatchCreateResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse", + "shortName": "batch_create_resource_value_configs" + }, + "description": "Sample for BatchCreateResourceValueConfigs", + "file": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.batch_create_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BatchCreateResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BatchCreateResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse", + "shortName": "batch_create_resource_value_configs" + }, + "description": "Sample for BatchCreateResourceValueConfigs", + "file": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.bulk_mute_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BulkMuteFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BulkMuteFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "bulk_mute_findings" + }, + "description": "Sample for BulkMuteFindings", + "file": "securitycenter_v2_generated_security_center_bulk_mute_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v2_generated_security_center_bulk_mute_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.bulk_mute_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BulkMuteFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BulkMuteFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "bulk_mute_findings" + }, + "description": "Sample for BulkMuteFindings", + "file": "securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v2.types.BigQueryExport" + }, + { + "name": "big_query_export_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.BigQueryExport", + "shortName": "create_big_query_export" + }, + "description": "Sample for CreateBigQueryExport", + "file": "securitycenter_v2_generated_security_center_create_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v2_generated_security_center_create_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v2.types.BigQueryExport" + }, + { + "name": "big_query_export_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.BigQueryExport", + "shortName": "create_big_query_export" + }, + "description": "Sample for CreateBigQueryExport", + "file": "securitycenter_v2_generated_security_center_create_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v2_generated_security_center_create_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v2.types.Finding" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v2_generated_security_center_create_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateFinding_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": "securitycenter_v2_generated_security_center_create_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v2.types.Finding" + }, + { + "name": "finding_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v2_generated_security_center_create_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateFinding_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": "securitycenter_v2_generated_security_center_create_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateMuteConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v2.types.MuteConfig" + }, + { + "name": "mute_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.cloud.securitycenter_v2.types.MuteConfig", + "shortName": "create_mute_config" + }, + "description": "Sample for CreateMuteConfig", + "file": "securitycenter_v2_generated_security_center_create_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v2_generated_security_center_create_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateMuteConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v2.types.MuteConfig" + }, + { + "name": "mute_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.cloud.securitycenter_v2.types.MuteConfig", + "shortName": "create_mute_config" + }, + "description": "Sample for CreateMuteConfig", + "file": "securitycenter_v2_generated_security_center_create_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v2_generated_security_center_create_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v2.types.NotificationConfig" + }, + { + "name": "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.cloud.securitycenter_v2.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v2_generated_security_center_create_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v2_generated_security_center_create_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v2.types.NotificationConfig" + }, + { + "name": "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.cloud.securitycenter_v2.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v2_generated_security_center_create_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v2_generated_security_center_create_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v2.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v2_generated_security_center_create_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_create_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v2.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v2_generated_security_center_create_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_create_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest" + }, + { + "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_big_query_export" + }, + "description": "Sample for DeleteBigQueryExport", + "file": "securitycenter_v2_generated_security_center_delete_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v2_generated_security_center_delete_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest" + }, + { + "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_big_query_export" + }, + "description": "Sample for DeleteBigQueryExport", + "file": "securitycenter_v2_generated_security_center_delete_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v2_generated_security_center_delete_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest" + }, + { + "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_mute_config" + }, + "description": "Sample for DeleteMuteConfig", + "file": "securitycenter_v2_generated_security_center_delete_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v2_generated_security_center_delete_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest" + }, + { + "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_mute_config" + }, + "description": "Sample for DeleteMuteConfig", + "file": "securitycenter_v2_generated_security_center_delete_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v2_generated_security_center_delete_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest" + }, + { + "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_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v2_generated_security_center_delete_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v2_generated_security_center_delete_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest" + }, + { + "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_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v2_generated_security_center_delete_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v2_generated_security_center_delete_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest" + }, + { + "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_resource_value_config" + }, + "description": "Sample for DeleteResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_delete_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v2_generated_security_center_delete_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest" + }, + { + "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_resource_value_config" + }, + "description": "Sample for DeleteResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetBigQueryExportRequest" + }, + { + "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.securitycenter_v2.types.BigQueryExport", + "shortName": "get_big_query_export" + }, + "description": "Sample for GetBigQueryExport", + "file": "securitycenter_v2_generated_security_center_get_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetBigQueryExportRequest" + }, + { + "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.securitycenter_v2.types.BigQueryExport", + "shortName": "get_big_query_export" + }, + "description": "Sample for GetBigQueryExport", + "file": "securitycenter_v2_generated_security_center_get_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v2_generated_security_center_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v2_generated_security_center_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetMuteConfigRequest" + }, + { + "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.securitycenter_v2.types.MuteConfig", + "shortName": "get_mute_config" + }, + "description": "Sample for GetMuteConfig", + "file": "securitycenter_v2_generated_security_center_get_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetMuteConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetMuteConfigRequest" + }, + { + "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.securitycenter_v2.types.MuteConfig", + "shortName": "get_mute_config" + }, + "description": "Sample for GetMuteConfig", + "file": "securitycenter_v2_generated_security_center_get_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetMuteConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v2.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v2_generated_security_center_get_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v2.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v2_generated_security_center_get_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest" + }, + { + "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.securitycenter_v2.types.ResourceValueConfig", + "shortName": "get_resource_value_config" + }, + "description": "Sample for GetResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_get_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest" + }, + { + "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.securitycenter_v2.types.ResourceValueConfig", + "shortName": "get_resource_value_config" + }, + "description": "Sample for GetResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_get_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_simulation", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSimulation", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSimulation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetSimulationRequest" + }, + { + "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.securitycenter_v2.types.Simulation", + "shortName": "get_simulation" + }, + "description": "Sample for GetSimulation", + "file": "securitycenter_v2_generated_security_center_get_simulation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSimulation_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_simulation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_simulation", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSimulation", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSimulation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetSimulationRequest" + }, + { + "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.securitycenter_v2.types.Simulation", + "shortName": "get_simulation" + }, + "description": "Sample for GetSimulation", + "file": "securitycenter_v2_generated_security_center_get_simulation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSimulation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_simulation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetSourceRequest" + }, + { + "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.securitycenter_v2.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v2_generated_security_center_get_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetSourceRequest" + }, + { + "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.securitycenter_v2.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v2_generated_security_center_get_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_valued_resource", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetValuedResource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetValuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetValuedResourceRequest" + }, + { + "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.securitycenter_v2.types.ValuedResource", + "shortName": "get_valued_resource" + }, + "description": "Sample for GetValuedResource", + "file": "securitycenter_v2_generated_security_center_get_valued_resource_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetValuedResource_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_valued_resource_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_valued_resource", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetValuedResource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetValuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetValuedResourceRequest" + }, + { + "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.securitycenter_v2.types.ValuedResource", + "shortName": "get_valued_resource" + }, + "description": "Sample for GetValuedResource", + "file": "securitycenter_v2_generated_security_center_get_valued_resource_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetValuedResource_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_valued_resource_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsAsyncPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v2_generated_security_center_group_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GroupFindings_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": "securitycenter_v2_generated_security_center_group_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v2_generated_security_center_group_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GroupFindings_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": "securitycenter_v2_generated_security_center_group_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_attack_paths", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListAttackPaths", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAttackPaths" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListAttackPathsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListAttackPathsAsyncPager", + "shortName": "list_attack_paths" + }, + "description": "Sample for ListAttackPaths", + "file": "securitycenter_v2_generated_security_center_list_attack_paths_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v2_generated_security_center_list_attack_paths_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_attack_paths", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListAttackPaths", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAttackPaths" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListAttackPathsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListAttackPathsPager", + "shortName": "list_attack_paths" + }, + "description": "Sample for ListAttackPaths", + "file": "securitycenter_v2_generated_security_center_list_attack_paths_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v2_generated_security_center_list_attack_paths_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_big_query_exports", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListBigQueryExports", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListBigQueryExports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsAsyncPager", + "shortName": "list_big_query_exports" + }, + "description": "Sample for ListBigQueryExports", + "file": "securitycenter_v2_generated_security_center_list_big_query_exports_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v2_generated_security_center_list_big_query_exports_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_big_query_exports", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListBigQueryExports", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListBigQueryExports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsPager", + "shortName": "list_big_query_exports" + }, + "description": "Sample for ListBigQueryExports", + "file": "securitycenter_v2_generated_security_center_list_big_query_exports_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v2_generated_security_center_list_big_query_exports_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListFindingsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListFindingsAsyncPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v2_generated_security_center_list_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListFindings_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": "securitycenter_v2_generated_security_center_list_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListFindingsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListFindingsPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v2_generated_security_center_list_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListFindings_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": "securitycenter_v2_generated_security_center_list_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_mute_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListMuteConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListMuteConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListMuteConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsAsyncPager", + "shortName": "list_mute_configs" + }, + "description": "Sample for ListMuteConfigs", + "file": "securitycenter_v2_generated_security_center_list_mute_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v2_generated_security_center_list_mute_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_mute_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListMuteConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListMuteConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListMuteConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsPager", + "shortName": "list_mute_configs" + }, + "description": "Sample for ListMuteConfigs", + "file": "securitycenter_v2_generated_security_center_list_mute_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v2_generated_security_center_list_mute_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsAsyncPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v2_generated_security_center_list_notification_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v2_generated_security_center_list_notification_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v2_generated_security_center_list_notification_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v2_generated_security_center_list_notification_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsAsyncPager", + "shortName": "list_resource_value_configs" + }, + "description": "Sample for ListResourceValueConfigs", + "file": "securitycenter_v2_generated_security_center_list_resource_value_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v2_generated_security_center_list_resource_value_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsPager", + "shortName": "list_resource_value_configs" + }, + "description": "Sample for ListResourceValueConfigs", + "file": "securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListSourcesRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListSourcesAsyncPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v2_generated_security_center_list_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListSources_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": "securitycenter_v2_generated_security_center_list_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListSourcesRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListSourcesPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v2_generated_security_center_list_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListSources_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": "securitycenter_v2_generated_security_center_list_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_valued_resources", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListValuedResources", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListValuedResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListValuedResourcesRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesAsyncPager", + "shortName": "list_valued_resources" + }, + "description": "Sample for ListValuedResources", + "file": "securitycenter_v2_generated_security_center_list_valued_resources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v2_generated_security_center_list_valued_resources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_valued_resources", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListValuedResources", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListValuedResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListValuedResourcesRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesPager", + "shortName": "list_valued_resources" + }, + "description": "Sample for ListValuedResources", + "file": "securitycenter_v2_generated_security_center_list_valued_resources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v2_generated_security_center_list_valued_resources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v2.types.Finding.State" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v2_generated_security_center_set_finding_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetFindingState_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": "securitycenter_v2_generated_security_center_set_finding_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v2.types.Finding.State" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v2_generated_security_center_set_finding_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetFindingState_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": "securitycenter_v2_generated_security_center_set_finding_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v2_generated_security_center_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v2_generated_security_center_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_mute", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetMute", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetMute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.SetMuteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "mute", + "type": "google.cloud.securitycenter_v2.types.Finding.Mute" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "set_mute" + }, + "description": "Sample for SetMute", + "file": "securitycenter_v2_generated_security_center_set_mute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetMute_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": "securitycenter_v2_generated_security_center_set_mute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_mute", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetMute", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetMute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.SetMuteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "mute", + "type": "google.cloud.securitycenter_v2.types.Finding.Mute" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "set_mute" + }, + "description": "Sample for SetMute", + "file": "securitycenter_v2_generated_security_center_set_mute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetMute_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": "securitycenter_v2_generated_security_center_set_mute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v2_generated_security_center_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v2_generated_security_center_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v2.types.BigQueryExport" + }, + { + "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.securitycenter_v2.types.BigQueryExport", + "shortName": "update_big_query_export" + }, + "description": "Sample for UpdateBigQueryExport", + "file": "securitycenter_v2_generated_security_center_update_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v2_generated_security_center_update_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v2.types.BigQueryExport" + }, + { + "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.securitycenter_v2.types.BigQueryExport", + "shortName": "update_big_query_export" + }, + "description": "Sample for UpdateBigQueryExport", + "file": "securitycenter_v2_generated_security_center_update_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v2_generated_security_center_update_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_external_system", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateExternalSystem", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateExternalSystem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest" + }, + { + "name": "external_system", + "type": "google.cloud.securitycenter_v2.types.ExternalSystem" + }, + { + "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.securitycenter_v2.types.ExternalSystem", + "shortName": "update_external_system" + }, + "description": "Sample for UpdateExternalSystem", + "file": "securitycenter_v2_generated_security_center_update_external_system_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v2_generated_security_center_update_external_system_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_external_system", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateExternalSystem", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateExternalSystem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest" + }, + { + "name": "external_system", + "type": "google.cloud.securitycenter_v2.types.ExternalSystem" + }, + { + "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.securitycenter_v2.types.ExternalSystem", + "shortName": "update_external_system" + }, + "description": "Sample for UpdateExternalSystem", + "file": "securitycenter_v2_generated_security_center_update_external_system_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v2_generated_security_center_update_external_system_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v2.types.Finding" + }, + { + "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.securitycenter_v2.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v2_generated_security_center_update_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v2_generated_security_center_update_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v2.types.Finding" + }, + { + "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.securitycenter_v2.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v2_generated_security_center_update_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v2_generated_security_center_update_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v2.types.MuteConfig" + }, + { + "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.securitycenter_v2.types.MuteConfig", + "shortName": "update_mute_config" + }, + "description": "Sample for UpdateMuteConfig", + "file": "securitycenter_v2_generated_security_center_update_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v2_generated_security_center_update_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v2.types.MuteConfig" + }, + { + "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.securitycenter_v2.types.MuteConfig", + "shortName": "update_mute_config" + }, + "description": "Sample for UpdateMuteConfig", + "file": "securitycenter_v2_generated_security_center_update_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v2_generated_security_center_update_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v2.types.NotificationConfig" + }, + { + "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.securitycenter_v2.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v2_generated_security_center_update_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v2_generated_security_center_update_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v2.types.NotificationConfig" + }, + { + "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.securitycenter_v2.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v2_generated_security_center_update_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v2_generated_security_center_update_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest" + }, + { + "name": "resource_value_config", + "type": "google.cloud.securitycenter_v2.types.ResourceValueConfig" + }, + { + "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.securitycenter_v2.types.ResourceValueConfig", + "shortName": "update_resource_value_config" + }, + "description": "Sample for UpdateResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_update_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v2_generated_security_center_update_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest" + }, + { + "name": "resource_value_config", + "type": "google.cloud.securitycenter_v2.types.ResourceValueConfig" + }, + { + "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.securitycenter_v2.types.ResourceValueConfig", + "shortName": "update_resource_value_config" + }, + "description": "Sample for UpdateResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_update_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v2_generated_security_center_update_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v2.types.SecurityMarks" + }, + { + "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.securitycenter_v2.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v2_generated_security_center_update_security_marks_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v2_generated_security_center_update_security_marks_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v2.types.SecurityMarks" + }, + { + "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.securitycenter_v2.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v2_generated_security_center_update_security_marks_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v2_generated_security_center_update_security_marks_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v2.types.Source" + }, + { + "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.securitycenter_v2.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v2_generated_security_center_update_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSource_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": "securitycenter_v2_generated_security_center_update_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v2.types.Source" + }, + { + "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.securitycenter_v2.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v2_generated_security_center_update_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSource_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": "securitycenter_v2_generated_security_center_update_source_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py new file mode 100644 index 000000000000..f95da838422b --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py @@ -0,0 +1,215 @@ +#! /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 securitycenterCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_create_resource_value_configs': ('parent', 'requests', ), + 'bulk_mute_findings': ('parent', 'filter', 'mute_state', ), + 'create_big_query_export': ('parent', 'big_query_export', 'big_query_export_id', ), + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_mute_config': ('parent', 'mute_config', 'mute_config_id', ), + 'create_notification_config': ('parent', 'config_id', 'notification_config', ), + 'create_source': ('parent', 'source', ), + 'delete_big_query_export': ('name', ), + 'delete_mute_config': ('name', ), + 'delete_notification_config': ('name', ), + 'delete_resource_value_config': ('name', ), + 'get_big_query_export': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_mute_config': ('name', ), + 'get_notification_config': ('name', ), + 'get_resource_value_config': ('name', ), + 'get_simulation': ('name', ), + 'get_source': ('name', ), + 'get_valued_resource': ('name', ), + 'group_findings': ('parent', 'group_by', 'filter', 'page_token', 'page_size', ), + 'list_attack_paths': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_big_query_exports': ('parent', 'page_size', 'page_token', ), + 'list_findings': ('parent', 'filter', 'order_by', 'field_mask', 'page_token', 'page_size', ), + 'list_mute_configs': ('parent', 'page_size', 'page_token', ), + 'list_notification_configs': ('parent', 'page_token', 'page_size', ), + 'list_resource_value_configs': ('parent', 'page_size', 'page_token', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'list_valued_resources': ('parent', 'filter', 'page_token', 'page_size', 'order_by', ), + 'set_finding_state': ('name', 'state', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'set_mute': ('name', 'mute', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_big_query_export': ('big_query_export', 'update_mask', ), + 'update_external_system': ('external_system', 'update_mask', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_mute_config': ('mute_config', 'update_mask', ), + 'update_notification_config': ('notification_config', 'update_mask', ), + 'update_resource_value_config': ('resource_value_config', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', ), + 'update_source': ('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=securitycenterCallTransformer(), +): + """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 securitycenter 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-securitycenter/v2/setup.py b/owl-bot-staging/google-cloud-securitycenter/v2/setup.py new file mode 100644 index 000000000000..c4538ec101f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/setup.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. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-securitycenter' + + +description = "Google Cloud Securitycenter API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/securitycenter/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", + "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", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" + +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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 +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_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-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py new file mode 100644 index 000000000000..6104ead93daa --- /dev/null +++ b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py @@ -0,0 +1,31716 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR 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 +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 + +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.securitycenter_v2.services.security_center import SecurityCenterAsyncClient +from google.cloud.securitycenter_v2.services.security_center import SecurityCenterClient +from google.cloud.securitycenter_v2.services.security_center import pagers +from google.cloud.securitycenter_v2.services.security_center import transports +from google.cloud.securitycenter_v2.types import access +from google.cloud.securitycenter_v2.types import application +from google.cloud.securitycenter_v2.types import attack_exposure +from google.cloud.securitycenter_v2.types import attack_path +from google.cloud.securitycenter_v2.types import backup_disaster_recovery +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import cloud_armor +from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile +from google.cloud.securitycenter_v2.types import cloud_dlp_inspection +from google.cloud.securitycenter_v2.types import compliance +from google.cloud.securitycenter_v2.types import connection +from google.cloud.securitycenter_v2.types import contact_details +from google.cloud.securitycenter_v2.types import container +from google.cloud.securitycenter_v2.types import database +from google.cloud.securitycenter_v2.types import exfiltration +from google.cloud.securitycenter_v2.types import external_system +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import file +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import group_membership +from google.cloud.securitycenter_v2.types import iam_binding +from google.cloud.securitycenter_v2.types import indicator +from google.cloud.securitycenter_v2.types import kernel_rootkit +from google.cloud.securitycenter_v2.types import kubernetes +from google.cloud.securitycenter_v2.types import label +from google.cloud.securitycenter_v2.types import load_balancer +from google.cloud.securitycenter_v2.types import log_entry +from google.cloud.securitycenter_v2.types import mitre_attack +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notebook +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v2.types import org_policy +from google.cloud.securitycenter_v2.types import process +from google.cloud.securitycenter_v2.types import resource +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config +from google.cloud.securitycenter_v2.types import security_marks +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import security_posture +from google.cloud.securitycenter_v2.types import securitycenter_service +from google.cloud.securitycenter_v2.types import simulation +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import toxic_combination +from google.cloud.securitycenter_v2.types import valued_resource +from google.cloud.securitycenter_v2.types import vulnerability +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 duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None + assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SecurityCenterClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source + assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SecurityCenterGrpcTransport, "grpc"), + (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + 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", [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), +]) +def test_security_center_client_from_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 == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://securitycenter.googleapis.com' + ) + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + available_transports = [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterRestTransport, + ] + assert transport in available_transports + + transport = SecurityCenterClient.get_transport_class("grpc") + assert transport == transports.SecurityCenterGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, 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", [ + SecurityCenterClient, SecurityCenterAsyncClient +]) +@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) +def test_security_center_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), +]) +def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), +]) +def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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_security_center_client_client_options_from_dict(): + with mock.patch('google.cloud.securitycenter_v2.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.BatchCreateResourceValueConfigsRequest, + dict, +]) +def test_batch_create_resource_value_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse( + ) + response = client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) + + +def test_batch_create_resource_value_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_create_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() + + +def test_batch_create_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.BatchCreateResourceValueConfigsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_create_resource_value_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest( + parent='parent_value', + ) + +def test_batch_create_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc + request = {} + client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_resource_value_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_batch_create_resource_value_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( + )) + response = await client.batch_create_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() + +@pytest.mark.asyncio +async def test_batch_create_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.batch_create_resource_value_configs] = mock_object + + request = {} + await client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.batch_create_resource_value_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( + )) + response = await client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) + + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_async_from_dict(): + await test_batch_create_resource_value_configs_async(request_type=dict) + + +def test_batch_create_resource_value_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + client.batch_create_resource_value_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_batch_create_resource_value_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) + await client.batch_create_resource_value_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_batch_create_resource_value_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_resource_value_configs( + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(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 + arg = args[0].requests + mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] + assert arg == mock_val + + +def test_batch_create_resource_value_configs_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], + ) + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_resource_value_configs( + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(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 + arg = args[0].requests + mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.BulkMuteFindingsRequest, + dict, +]) +def test_bulk_mute_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BulkMuteFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_bulk_mute_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.bulk_mute_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest() + + +def test_bulk_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.BulkMuteFindingsRequest( + parent='parent_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.bulk_mute_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest( + parent='parent_value', + filter='filter_value', + ) + +def test_bulk_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc + request = {} + client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest() + +@pytest.mark.asyncio +async def test_bulk_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.bulk_mute_findings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.bulk_mute_findings] = mock_object + + request = {} + await client.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.bulk_mute_findings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_bulk_mute_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BulkMuteFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.BulkMuteFindingsRequest() + 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_bulk_mute_findings_async_from_dict(): + await test_bulk_mute_findings_async(request_type=dict) + + +def test_bulk_mute_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BulkMuteFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.bulk_mute_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_bulk_mute_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.BulkMuteFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.bulk_mute_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_bulk_mute_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings( + 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_bulk_mute_findings_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_bulk_mute_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), + '__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.bulk_mute_findings( + 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_bulk_mute_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateBigQueryExportRequest, + dict, +]) +def test_create_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + response = client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +def test_create_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest() + + +def test_create_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateBigQueryExportRequest( + parent='parent_value', + big_query_export_id='big_query_export_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest( + parent='parent_value', + big_query_export_id='big_query_export_id_value', + ) + +def test_create_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + request = {} + client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_big_query_export(request) + + # Establish that a new wrapper 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_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.create_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_create_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_big_query_export] = mock_object + + request = {} + await client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +@pytest.mark.asyncio +async def test_create_big_query_export_async_from_dict(): + await test_create_big_query_export_async(request_type=dict) + + +def test_create_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateBigQueryExportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value = bigquery_export.BigQueryExport() + client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateBigQueryExportRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + await client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_big_query_export( + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_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].big_query_export + mock_val = bigquery_export.BigQueryExport(name='name_value') + assert arg == mock_val + arg = args[0].big_query_export_id + mock_val = 'big_query_export_id_value' + assert arg == mock_val + + +def test_create_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_id_value', + ) + +@pytest.mark.asyncio +async def test_create_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_big_query_export( + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_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].big_query_export + mock_val = bigquery_export.BigQueryExport(name='name_value') + assert arg == mock_val + arg = args[0].big_query_export_id + mock_val = 'big_query_export_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_create_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest( + parent='parent_value', + finding_id='finding_id_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.create_finding] = mock_rpc + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object + + request = {} + await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_create_finding_async_from_dict(): + await test_create_finding_async(request_type=dict) + + +def test_create_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_finding( + parent='parent_value', + finding=gcs_finding.Finding(name='name_value'), + finding_id='finding_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].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + + +def test_create_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding=gcs_finding.Finding(name='name_value'), + finding_id='finding_id_value', + ) + +@pytest.mark.asyncio +async def test_create_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_finding( + parent='parent_value', + finding=gcs_finding.Finding(name='name_value'), + finding_id='finding_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].finding + mock_val = gcs_finding.Finding(name='name_value') + assert arg == mock_val + arg = args[0].finding_id + mock_val = 'finding_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding=gcs_finding.Finding(name='name_value'), + finding_id='finding_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateMuteConfigRequest, + dict, +]) +def test_create_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + response = client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_create_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest() + + +def test_create_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateMuteConfigRequest( + parent='parent_value', + mute_config_id='mute_config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest( + parent='parent_value', + mute_config_id='mute_config_id_value', + ) + +def test_create_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + request = {} + client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.create_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest() + +@pytest.mark.asyncio +async def test_create_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_mute_config] = mock_object + + request = {} + await client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +@pytest.mark.asyncio +async def test_create_mute_config_async_from_dict(): + await test_create_mute_config_async(request_type=dict) + +def test_create_mute_config_routing_parameters(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateMuteConfigRequest(**{"parent": "projects/sample1/locations/sample2"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.create_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateMuteConfigRequest(**{"parent": "organizations/sample1/locations/sample2"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.create_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateMuteConfigRequest(**{"parent": "folders/sample1/locations/sample2"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.create_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + + +def test_create_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_mute_config( + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_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].mute_config + mock_val = gcs_mute_config.MuteConfig(name='name_value') + assert arg == mock_val + arg = args[0].mute_config_id + mock_val = 'mute_config_id_value' + assert arg == mock_val + + +def test_create_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_mute_config( + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_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].mute_config + mock_val = gcs_mute_config.MuteConfig(name='name_value') + assert arg == mock_val + arg = args[0].mute_config_id + mock_val = 'mute_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateNotificationConfigRequest, + dict, +]) +def test_create_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_create_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateNotificationConfigRequest( + parent='parent_value', + config_id='config_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest( + parent='parent_value', + config_id='config_id_value', + ) + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_create_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_notification_config] = mock_object + + request = {} + await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_create_notification_config_async_from_dict(): + await test_create_notification_config_async(request_type=dict) + + +def test_create_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.create_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.create_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_notification_config( + parent='parent_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + config_id='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].notification_config + mock_val = gcs_notification_config.NotificationConfig(name='name_value') + assert arg == mock_val + arg = args[0].config_id + mock_val = 'config_id_value' + assert arg == mock_val + + +def test_create_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + config_id='config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_notification_config( + parent='parent_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + config_id='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].notification_config + mock_val = gcs_notification_config.NotificationConfig(name='name_value') + assert arg == mock_val + arg = args[0].config_id + mock_val = 'config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_notification_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + config_id='config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_create_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest( + parent='parent_value', + ) + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + +@pytest.mark.asyncio +async def test_create_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object + + request = {} + await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.CreateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_create_source_async_from_dict(): + await test_create_source_async(request_type=dict) + + +def test_create_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.create_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.create_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + + +def test_create_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_source( + parent='parent_value', + source=gcs_source.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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteBigQueryExportRequest, + dict, +]) +def test_delete_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() + + +def test_delete_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteBigQueryExportRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest( + name='name_value', + ) + +def test_delete_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + request = {} + client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_big_query_export(request) + + # Establish that a new wrapper 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_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_delete_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_big_query_export] = mock_object + + request = {} + await client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteBigQueryExportRequest() + 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_big_query_export_async_from_dict(): + await test_delete_big_query_export_async(request_type=dict) + + +def test_delete_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value = None + client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__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_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), + '__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_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteMuteConfigRequest, + dict, +]) +def test_delete_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest() + + +def test_delete_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteMuteConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest( + name='name_value', + ) + +def test_delete_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + request = {} + client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest() + +@pytest.mark.asyncio +async def test_delete_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_mute_config] = mock_object + + request = {} + await client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteMuteConfigRequest() + 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_mute_config_async_from_dict(): + await test_delete_mute_config_async(request_type=dict) + +def test_delete_mute_config_routing_parameters(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteMuteConfigRequest(**{"name": "projects/sample1/locations/sample2/muteConfigs/sample3"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value = None + client.delete_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteMuteConfigRequest(**{"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value = None + client.delete_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteMuteConfigRequest(**{"name": "folders/sample1/locations/sample2/muteConfigs/sample3"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), + '__call__') as call: + call.return_value = None + client.delete_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + + +def test_delete_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, +]) +def test_delete_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteNotificationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest( + name='name_value', + ) + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_delete_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_notification_config] = mock_object + + request = {} + await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteNotificationConfigRequest() + 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_config_async_from_dict(): + await test_delete_notification_config_async(request_type=dict) + + +def test_delete_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = None + client.delete_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_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_notification_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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_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_notification_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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_notification_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteResourceValueConfigRequest, + dict, +]) +def test_delete_resource_value_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() + + +def test_delete_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.DeleteResourceValueConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_resource_value_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest( + name='name_value', + ) + +def test_delete_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + request = {} + client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_resource_value_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_resource_value_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() + +@pytest.mark.asyncio +async def test_delete_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_resource_value_config] = mock_object + + request = {} + await client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_resource_value_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteResourceValueConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.DeleteResourceValueConfigRequest() + 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_resource_value_config_async_from_dict(): + await test_delete_resource_value_config_async(request_type=dict) + + +def test_delete_resource_value_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value = None + client.delete_resource_value_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_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_resource_value_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_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetBigQueryExportRequest, + dict, +]) +def test_get_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + response = client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +def test_get_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest() + + +def test_get_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetBigQueryExportRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest( + name='name_value', + ) + +def test_get_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc + request = {} + client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.get_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_get_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_big_query_export] = mock_object + + request = {} + await client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +@pytest.mark.asyncio +async def test_get_big_query_export_async_from_dict(): + await test_get_big_query_export_async(request_type=dict) + + +def test_get_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value = bigquery_export.BigQueryExport() + client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetBigQueryExportRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + await client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_big_query_export( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSimulationRequest, + dict, +]) +def test_get_simulation(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + response = client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSimulationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == 'name_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +def test_get_simulation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_simulation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest() + + +def test_get_simulation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSimulationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_simulation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest( + name='name_value', + ) + +def test_get_simulation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_simulation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc + request = {} + client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_simulation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_simulation_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_simulation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest() + +@pytest.mark.asyncio +async def test_get_simulation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_simulation in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_simulation] = mock_object + + request = {} + await client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_simulation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_simulation_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSimulationRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSimulationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == 'name_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +@pytest.mark.asyncio +async def test_get_simulation_async_from_dict(): + await test_get_simulation_async(request_type=dict) + + +def test_get_simulation_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSimulationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value = simulation.Simulation() + client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_simulation_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSimulationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) + await client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_simulation_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_simulation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_simulation_flattened_error(): + client = SecurityCenterClient( + credentials=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_simulation( + securitycenter_service.GetSimulationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_simulation_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_simulation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_simulation( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_simulation_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_simulation( + securitycenter_service.GetSimulationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetValuedResourceRequest, + dict, +]) +def test_get_valued_resource(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + ) + response = client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetValuedResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == 'name_value' + assert response.resource == 'resource_value' + assert response.resource_type == 'resource_type_value' + assert response.display_name == 'display_name_value' + assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + + +def test_get_valued_resource_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_valued_resource() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest() + + +def test_get_valued_resource_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetValuedResourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_valued_resource(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest( + name='name_value', + ) + +def test_get_valued_resource_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_valued_resource in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc + request = {} + client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_valued_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_valued_resource_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + )) + response = await client.get_valued_resource() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest() + +@pytest.mark.asyncio +async def test_get_valued_resource_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_valued_resource in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_valued_resource] = mock_object + + request = {} + await client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_valued_resource(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_valued_resource_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetValuedResourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + )) + response = await client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetValuedResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == 'name_value' + assert response.resource == 'resource_value' + assert response.resource_type == 'resource_type_value' + assert response.display_name == 'display_name_value' + assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + + +@pytest.mark.asyncio +async def test_get_valued_resource_async_from_dict(): + await test_get_valued_resource_async(request_type=dict) + + +def test_get_valued_resource_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetValuedResourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value = valued_resource.ValuedResource() + client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_valued_resource_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetValuedResourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) + await client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_valued_resource_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_valued_resource( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_valued_resource_flattened_error(): + client = SecurityCenterClient( + credentials=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_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_valued_resource_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_valued_resource( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_valued_resource_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.GetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest( + resource='resource_value', + ) + +def test_get_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object + + request = {} + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.GetIamPolicyRequest() + 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetMuteConfigRequest, + dict, +]) +def test_get_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + ) + response = client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_get_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest() + + +def test_get_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetMuteConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest( + name='name_value', + ) + +def test_get_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_mute_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_mute_config] = mock_rpc + request = {} + client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.get_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest() + +@pytest.mark.asyncio +async def test_get_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_mute_config] = mock_object + + request = {} + await client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC + + +@pytest.mark.asyncio +async def test_get_mute_config_async_from_dict(): + await test_get_mute_config_async(request_type=dict) + +def test_get_mute_config_routing_parameters(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetMuteConfigRequest(**{"name": "projects/sample1/locations/sample2/muteConfigs/sample3"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value = mute_config.MuteConfig() + client.get_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetMuteConfigRequest(**{"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value = mute_config.MuteConfig() + client.get_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetMuteConfigRequest(**{"name": "folders/sample1/locations/sample2/muteConfigs/sample3"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + call.return_value = mute_config.MuteConfig() + client.get_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + + +def test_get_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_mute_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_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_mute_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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetNotificationConfigRequest, + dict, +]) +def test_get_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_get_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetNotificationConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest( + name='name_value', + ) + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_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_notification_config] = mock_rpc + request = {} + client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_get_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_notification_config] = mock_object + + request = {} + await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_get_notification_config_async_from_dict(): + await test_get_notification_config_async(request_type=dict) + + +def test_get_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = notification_config.NotificationConfig() + client.get_notification_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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + 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_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + await client.get_notification_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_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_notification_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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_notification_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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_notification_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetResourceValueConfigRequest, + dict, +]) +def test_get_resource_value_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + response = client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +def test_get_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest() + + +def test_get_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetResourceValueConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_resource_value_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest( + name='name_value', + ) + +def test_get_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc + request = {} + client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_resource_value_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_resource_value_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest() + +@pytest.mark.asyncio +async def test_get_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_resource_value_config] = mock_object + + request = {} + await client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_resource_value_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetResourceValueConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +@pytest.mark.asyncio +async def test_get_resource_value_config_async_from_dict(): + await test_get_resource_value_config_async(request_type=dict) + + +def test_get_resource_value_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value = resource_value_config.ResourceValueConfig() + client.get_resource_value_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_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetResourceValueConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) + await client.get_resource_value_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_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_resource_value_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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_resource_value_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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_get_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GetSourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest( + name='name_value', + ) + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + +@pytest.mark.asyncio +async def test_get_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object + + request = {} + await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GetSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_get_source_async_from_dict(): + await test_get_source_async(request_type=dict) + + +def test_get_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = source.Source() + client.get_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + await client.get_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_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_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_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.group_findings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.group_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest( + parent='parent_value', + filter='filter_value', + group_by='group_by_value', + page_token='page_token_value', + ) + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + +@pytest.mark.asyncio +async def test_group_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.group_findings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object + + request = {} + await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.group_findings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.GroupFindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_findings_async_from_dict(): + await test_group_findings_async(request_type=dict) + + +def test_group_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = securitycenter_service.GroupFindingsResponse() + client.group_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_group_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + await client.group_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_group_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that the 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + + +def test_group_findings_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + +@pytest.mark.asyncio +async def test_group_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that 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].group_by + mock_val = 'group_by_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_group_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_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, securitycenter_service.GroupResult) + for i in results) +def test_group_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_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_group_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_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, securitycenter_service.GroupResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_group_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_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", [ + securitycenter_service.ListAttackPathsRequest, + dict, +]) +def test_list_attack_paths(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAttackPathsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_attack_paths_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_attack_paths() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest() + + +def test_list_attack_paths_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListAttackPathsRequest( + 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_attack_paths), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_attack_paths(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_attack_paths_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_attack_paths in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc + request = {} + client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_attack_paths(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_attack_paths_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_attack_paths() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest() + +@pytest.mark.asyncio +async def test_list_attack_paths_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_attack_paths in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_attack_paths] = mock_object + + request = {} + await client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_attack_paths(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_attack_paths_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAttackPathsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListAttackPathsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_attack_paths_async_from_dict(): + await test_list_attack_paths_async(request_type=dict) + + +def test_list_attack_paths_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAttackPathsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + call.return_value = securitycenter_service.ListAttackPathsResponse() + client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_attack_paths_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAttackPathsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) + await client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_attack_paths_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_attack_paths( + 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_attack_paths_flattened_error(): + client = SecurityCenterClient( + credentials=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_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_attack_paths_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_attack_paths( + 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_attack_paths_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent='parent_value', + ) + + +def test_list_attack_paths_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_attack_paths(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, attack_path.AttackPath) + for i in results) +def test_list_attack_paths_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + pages = list(client.list_attack_paths(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_attack_paths_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_attack_paths(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, attack_path.AttackPath) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_attack_paths_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + 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_attack_paths(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", [ + securitycenter_service.ListBigQueryExportsRequest, + dict, +]) +def test_list_big_query_exports(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListBigQueryExportsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_big_query_exports_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_big_query_exports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest() + + +def test_list_big_query_exports_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListBigQueryExportsRequest( + 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_big_query_exports), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_big_query_exports(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_big_query_exports_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_big_query_exports in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc + request = {} + client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_big_query_exports(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_big_query_exports_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_big_query_exports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest() + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_exports in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_big_query_exports] = mock_object + + request = {} + await client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_big_query_exports(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_big_query_exports_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListBigQueryExportsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListBigQueryExportsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_from_dict(): + await test_list_big_query_exports_async(request_type=dict) + + +def test_list_big_query_exports_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListBigQueryExportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_big_query_exports_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListBigQueryExportsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) + await client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_big_query_exports_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_big_query_exports( + 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_big_query_exports_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_big_query_exports_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_big_query_exports( + 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_big_query_exports_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent='parent_value', + ) + + +def test_list_big_query_exports_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_big_query_exports(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, bigquery_export.BigQueryExport) + for i in results) +def test_list_big_query_exports_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + pages = list(client.list_big_query_exports(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_big_query_exports_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_big_query_exports(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, bigquery_export.BigQueryExport) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + 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_big_query_exports(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", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +def test_list_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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] == securitycenter_service.ListFindingsRequest( + parent='parent_value', + filter='filter_value', + order_by='order_by_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + +@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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object + + request = {} + await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + 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 = securitycenter_service.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' + assert response.total_size == 1086 + + +@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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( + 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 = securitycenter_service.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', + ) + + # Establish that the 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_findings_flattened_error(): + client = SecurityCenterClient( + credentials=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( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_findings_flattened_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.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', + ) + + # Establish that 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_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_findings( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + + +def test_list_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in results) +def test_list_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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 = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_findings_async_pages(): + client = SecurityCenterAsyncClient( + 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__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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", [ + securitycenter_service.ListMuteConfigsRequest, + dict, +]) +def test_list_mute_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListMuteConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_mute_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_mute_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest() + + +def test_list_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListMuteConfigsRequest( + 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_mute_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_mute_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_mute_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_mute_configs] = mock_rpc + request = {} + client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_mute_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_mute_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_mute_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest() + +@pytest.mark.asyncio +async def test_list_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_mute_configs] = mock_object + + request = {} + await client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_mute_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_mute_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListMuteConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListMuteConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_mute_configs_async_from_dict(): + await test_list_mute_configs_async(request_type=dict) + +def test_list_mute_configs_routing_parameters(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListMuteConfigsRequest(**{"parent": "projects/sample1/locations/sample2/muteConfigs"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListMuteConfigsResponse() + client.list_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListMuteConfigsRequest(**{"parent": "organizations/sample1/locations/sample2/muteConfigs"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListMuteConfigsResponse() + client.list_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListMuteConfigsRequest(**{"parent": "folders/sample1/locations/sample2/muteConfigs"}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListMuteConfigsResponse() + client.list_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + + +def test_list_mute_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_mute_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_mute_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_mute_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_mute_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_mute_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent='parent_value', + ) + + +def test_list_mute_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_mute_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, mute_config.MuteConfig) + for i in results) +def test_list_mute_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_mute_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_mute_configs_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_mute_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, mute_config.MuteConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_mute_configs_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + 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_mute_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", [ + securitycenter_service.ListNotificationConfigsRequest, + dict, +]) +def test_list_notification_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListNotificationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_notification_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListNotificationConfigsRequest( + 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_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_notification_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_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_notification_configs] = mock_rpc + request = {} + client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_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_notification_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + +@pytest.mark.asyncio +async def test_list_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_notification_configs] = mock_object + + request = {} + await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_notification_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListNotificationConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_from_dict(): + await test_list_notification_configs_async(request_type=dict) + + +def test_list_notification_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + 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_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + client.list_notification_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_notification_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + 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_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + await client.list_notification_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_notification_configs_flattened(): + client = SecurityCenterClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_notification_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_notification_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_notification_configs_flattened_async(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_notification_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_notification_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_notification_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + 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_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, notification_config.NotificationConfig) + for i in results) +def test_list_notification_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_notification_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_notification_configs_async_pager(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_notification_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, notification_config.NotificationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_pages(): + client = SecurityCenterAsyncClient( + 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_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + 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_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", [ + securitycenter_service.ListResourceValueConfigsRequest, + dict, +]) +def test_list_resource_value_configs(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_resource_value_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() + + +def test_list_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListResourceValueConfigsRequest( + 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_resource_value_configs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_resource_value_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc + request = {} + client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_value_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_resource_value_configs_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() + +@pytest.mark.asyncio +async def test_list_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_resource_value_configs] = mock_object + + request = {} + await client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_resource_value_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListResourceValueConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListResourceValueConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async_from_dict(): + await test_list_resource_value_configs_async(request_type=dict) + + +def test_list_resource_value_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + client.list_resource_value_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_resource_value_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListResourceValueConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) + await client.list_resource_value_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_resource_value_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_resource_value_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_resource_value_configs_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_resource_value_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_resource_value_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_resource_value_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent='parent_value', + ) + + +def test_list_resource_value_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_resource_value_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, resource_value_config.ResourceValueConfig) + for i in results) +def test_list_resource_value_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_resource_value_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_resource_value_configs_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_resource_value_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, resource_value_config.ResourceValueConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + 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_resource_value_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", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListSourcesRequest( + 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_sources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + +@pytest.mark.asyncio +async def test_list_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_sources in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object + + request = {} + await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_sources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sources_async_from_dict(): + await test_list_sources_async(request_type=dict) + + +def test_list_sources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = securitycenter_service.ListSourcesResponse() + client.list_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_sources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + await client.list_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_sources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_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_sources_flattened_error(): + client = SecurityCenterClient( + credentials=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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_sources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_sources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_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, source.Source) + for i in results) +def test_list_sources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = list(client.list_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_sources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_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, source.Source) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_sources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + 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_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", [ + securitycenter_service.ListValuedResourcesRequest, + dict, +]) +def test_list_valued_resources(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListValuedResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_valued_resources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_valued_resources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest() + + +def test_list_valued_resources_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.ListValuedResourcesRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_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_valued_resources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_valued_resources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest( + parent='parent_value', + filter='filter_value', + page_token='page_token_value', + order_by='order_by_value', + ) + +def test_list_valued_resources_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_valued_resources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc + request = {} + client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_valued_resources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_valued_resources_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_valued_resources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest() + +@pytest.mark.asyncio +async def test_list_valued_resources_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_valued_resources in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_valued_resources] = mock_object + + request = {} + await client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_valued_resources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_valued_resources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListValuedResourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.ListValuedResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_valued_resources_async_from_dict(): + await test_list_valued_resources_async(request_type=dict) + + +def test_list_valued_resources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListValuedResourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + call.return_value = securitycenter_service.ListValuedResourcesResponse() + client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_valued_resources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListValuedResourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) + await client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_valued_resources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_valued_resources( + 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_valued_resources_flattened_error(): + client = SecurityCenterClient( + credentials=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_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_valued_resources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_valued_resources( + 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_valued_resources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent='parent_value', + ) + + +def test_list_valued_resources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_valued_resources(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, valued_resource.ValuedResource) + for i in results) +def test_list_valued_resources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_valued_resources(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_valued_resources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_valued_resources(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, valued_resource.ValuedResource) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_valued_resources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + 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_valued_resources(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", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_set_finding_state_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_finding_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest( + name='name_value', + ) + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + +@pytest.mark.asyncio +async def test_set_finding_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object + + request = {} + await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_finding_state(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetFindingStateRequest() + 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.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_set_finding_state_async_from_dict(): + await test_set_finding_state_async(request_type=dict) + + +def test_set_finding_state_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = finding.Finding() + client.set_finding_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_set_finding_state_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_finding_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_set_finding_state_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + ) + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__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.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.SetIamPolicyRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest( + resource='resource_value', + ) + +def test_set_iam_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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( + version=774, + etag=b'etag_blob', + )) + response = await client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object + + request = {} + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.SetIamPolicyRequest() + 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = SecurityCenterClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetMuteRequest, + dict, +]) +def test_set_mute(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetMuteRequest() + 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.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_set_mute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_mute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest() + + +def test_set_mute_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.SetMuteRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_mute(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest( + name='name_value', + ) + +def test_set_mute_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_mute in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc + request = {} + client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_mute(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_set_mute_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_mute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest() + +@pytest.mark.asyncio +async def test_set_mute_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_mute in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_mute] = mock_object + + request = {} + await client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_mute(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_mute_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetMuteRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.SetMuteRequest() + 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.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_set_mute_async_from_dict(): + await test_set_mute_async(request_type=dict) + + +def test_set_mute_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetMuteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value = finding.Finding() + client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_mute_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetMuteRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_set_mute_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__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.set_mute( + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].mute + mock_val = finding.Finding.Mute.MUTED + assert arg == mock_val + + +def test_set_mute_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_mute( + securitycenter_service.SetMuteRequest(), + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + +@pytest.mark.asyncio +async def test_set_mute_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_mute), + '__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.set_mute( + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].mute + mock_val = finding.Finding.Mute.MUTED + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_mute_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_mute( + securitycenter_service.SetMuteRequest(), + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.TestIamPermissionsRequest( + 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.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.test_iam_permissions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( + resource='resource_value', + ) + +def test_test_iam_permissions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # 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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object + + request = {} + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] + request = iam_policy_pb2.TestIamPermissionsRequest() + 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateBigQueryExportRequest, + dict, +]) +def test_update_big_query_export(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + response = client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +def test_update_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() + + +def test_update_big_query_export_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateBigQueryExportRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_big_query_export(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest( + ) + +def test_update_big_query_export_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc + request = {} + client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_big_query_export(request) + + # Establish that a new wrapper 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_big_query_export_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.update_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() + +@pytest.mark.asyncio +async def test_update_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_big_query_export in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_big_query_export] = mock_object + + request = {} + await client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_big_query_export(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateBigQueryExportRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + )) + response = await client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateBigQueryExportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + + +@pytest.mark.asyncio +async def test_update_big_query_export_async_from_dict(): + await test_update_big_query_export_async(request_type=dict) + + +def test_update_big_query_export_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateBigQueryExportRequest() + + request.big_query_export.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value = bigquery_export.BigQueryExport() + client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'big_query_export.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateBigQueryExportRequest() + + request.big_query_export.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + await client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'big_query_export.name=name_value', + ) in kw['metadata'] + + +def test_update_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_big_query_export( + big_query_export=bigquery_export.BigQueryExport(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].big_query_export + mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error(): + client = SecurityCenterClient( + credentials=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_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_big_query_export( + big_query_export=bigquery_export.BigQueryExport(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].big_query_export + mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateExternalSystemRequest, + dict, +]) +def test_update_external_system(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + ) + response = client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateExternalSystemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == 'name_value' + assert response.assignees == ['assignees_value'] + assert response.external_uid == 'external_uid_value' + assert response.status == 'status_value' + assert response.case_uri == 'case_uri_value' + assert response.case_priority == 'case_priority_value' + + +def test_update_external_system_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_external_system() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest() + + +def test_update_external_system_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateExternalSystemRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_external_system(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest( + ) + +def test_update_external_system_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_external_system in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc + request = {} + client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_external_system(request) + + # Establish that a new wrapper 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_external_system_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + )) + response = await client.update_external_system() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest() + +@pytest.mark.asyncio +async def test_update_external_system_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_external_system in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_external_system] = mock_object + + request = {} + await client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_external_system(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_external_system_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateExternalSystemRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + )) + response = await client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateExternalSystemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == 'name_value' + assert response.assignees == ['assignees_value'] + assert response.external_uid == 'external_uid_value' + assert response.status == 'status_value' + assert response.case_uri == 'case_uri_value' + assert response.case_priority == 'case_priority_value' + + +@pytest.mark.asyncio +async def test_update_external_system_async_from_dict(): + await test_update_external_system_async(request_type=dict) + + +def test_update_external_system_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateExternalSystemRequest() + + request.external_system.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value = gcs_external_system.ExternalSystem() + client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'external_system.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_external_system_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateExternalSystemRequest() + + request.external_system.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) + await client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'external_system.name=name_value', + ) in kw['metadata'] + + +def test_update_external_system_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_external_system( + external_system=gcs_external_system.ExternalSystem(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].external_system + mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error(): + client = SecurityCenterClient( + credentials=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_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_external_system_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_external_system( + external_system=gcs_external_system.ExternalSystem(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].external_system + mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + response = client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +def test_update_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateFindingRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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.update_finding] = mock_rpc + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_finding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object + + request = {} + await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_finding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + )) + response = await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + + +@pytest.mark.asyncio +async def test_update_finding_async_from_dict(): + await test_update_finding_async(request_type=dict) + + +def test_update_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.update_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', + 'finding.name=name_value', + ) in kw['metadata'] + + +def test_update_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_finding( + finding=gcs_finding.Finding(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].finding + mock_val = gcs_finding.Finding(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_finding_flattened_error(): + client = SecurityCenterClient( + credentials=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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_finding( + finding=gcs_finding.Finding(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].finding + mock_val = gcs_finding.Finding(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_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateMuteConfigRequest, + dict, +]) +def test_update_mute_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + response = client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_update_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest() + + +def test_update_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateMuteConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_mute_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest( + ) + +def test_update_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + request = {} + client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_mute_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_mute_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.update_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest() + +@pytest.mark.asyncio +async def test_update_mute_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_mute_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_mute_config] = mock_object + + request = {} + await client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_mute_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateMuteConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + )) + response = await client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateMuteConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +@pytest.mark.asyncio +async def test_update_mute_config_async_from_dict(): + await test_update_mute_config_async(request_type=dict) + +def test_update_mute_config_routing_parameters(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateMuteConfigRequest(**{"mute_config": {"name": "projects/sample1/locations/sample2/muteConfigs/sample3"}}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.update_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateMuteConfigRequest(**{"mute_config": {"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"}}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.update_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateMuteConfigRequest(**{"mute_config": {"name": "folders/sample1/locations/sample2/muteConfigs/sample3"}}) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + call.return_value = gcs_mute_config.MuteConfig() + client.update_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw['metadata'] + + +def test_update_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_mute_config( + mute_config=gcs_mute_config.MuteConfig(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].mute_config + mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_mute_config( + mute_config=gcs_mute_config.MuteConfig(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].mute_config + mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, +]) +def test_update_notification_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + response = client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_update_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateNotificationConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_notification_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest( + ) + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_notification_config] = mock_rpc + request = {} + client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_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_notification_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + +@pytest.mark.asyncio +async def test_update_notification_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_notification_config] = mock_object + + request = {} + await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_notification_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateNotificationConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_update_notification_config_async_from_dict(): + await test_update_notification_config_async(request_type=dict) + + +def test_update_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.update_notification_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', + 'notification_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.update_notification_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', + 'notification_config.name=name_value', + ) in kw['metadata'] + + +def test_update_notification_config_flattened(): + client = SecurityCenterClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + 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_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_notification_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateResourceValueConfigRequest, + dict, +]) +def test_update_resource_value_config(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + response = client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +def test_update_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() + + +def test_update_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateResourceValueConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_resource_value_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest( + ) + +def test_update_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + request = {} + client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_resource_value_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_resource_value_config_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.update_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() + +@pytest.mark.asyncio +async def test_update_resource_value_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_resource_value_config] = mock_object + + request = {} + await client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_resource_value_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateResourceValueConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + )) + response = await client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateResourceValueConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + + +@pytest.mark.asyncio +async def test_update_resource_value_config_async_from_dict(): + await test_update_resource_value_config_async(request_type=dict) + + +def test_update_resource_value_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateResourceValueConfigRequest() + + request.resource_value_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value = gcs_resource_value_config.ResourceValueConfig() + client.update_resource_value_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', + 'resource_value_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateResourceValueConfigRequest() + + request.resource_value_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) + await client.update_resource_value_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', + 'resource_value_config.name=name_value', + ) in kw['metadata'] + + +def test_update_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_resource_value_config( + resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config + mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + credentials=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_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_resource_value_config( + resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config + mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + response = client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_security_marks_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + +def test_update_security_marks_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSecurityMarksRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_security_marks(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( + ) + +def test_update_security_marks_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish that a new wrapper 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_security_marks_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + +@pytest.mark.asyncio +async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_security_marks in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object + + request = {} + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_security_marks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSecurityMarksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_security_marks_async_from_dict(): + await test_update_security_marks_async(request_type=dict) + + +def test_update_security_marks_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = gcs_security_marks.SecurityMarks() + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_marks_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_marks.name=name_value', + ) in kw['metadata'] + + +def test_update_security_marks_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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].security_marks + mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error(): + client = SecurityCenterClient( + credentials=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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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].security_marks + mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source(request_type, transport: str = 'grpc'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = securitycenter_service.UpdateSourceRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest( + ) + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should 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_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_source] = mock_rpc + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + +@pytest.mark.asyncio +async def test_update_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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap 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_source in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object + + request = {} + await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = securitycenter_service.UpdateSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_source_async_from_dict(): + await test_update_source_async(request_type=dict) + + +def test_update_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.update_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', + 'source.name=name_value', + ) in kw['metadata'] + + +def test_update_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_source( + source=gcs_source.Source(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].source + mock_val = gcs_source.Source(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_source_flattened_error(): + client = SecurityCenterClient( + credentials=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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_source( + source=gcs_source.Source(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].source + mock_val = gcs_source.Source(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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.BatchCreateResourceValueConfigsRequest, + dict, +]) +def test_batch_create_resource_value_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.BatchCreateResourceValueConfigsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) + +def test_batch_create_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc + + request = {} + client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_resource_value_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_batch_create_resource_value_configs_rest_required_fields(request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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()).batch_create_resource_value_configs._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_create_resource_value_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_create_resource_value_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_resource_value_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_batch_create_resource_value_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_batch_create_resource_value_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(securitycenter_service.BatchCreateResourceValueConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.BatchCreateResourceValueConfigsResponse.to_json(securitycenter_service.BatchCreateResourceValueConfigsResponse()) + + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + client.batch_create_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_create_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_create_resource_value_configs(request) + + +def test_batch_create_resource_value_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(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.batch_create_resource_value_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/v2/{parent=organizations/*}/resourceValueConfigs:batchCreate" % client.transport._host, args[1]) + + +def test_batch_create_resource_value_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent='parent_value', + requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], + ) + + +def test_batch_create_resource_value_configs_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.BulkMuteFindingsRequest, + dict, +]) +def test_bulk_mute_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') + + # 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 + response = client.bulk_mute_findings(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +def test_bulk_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc + + request = {} + client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_rest_required_fields(request_type=securitycenter_service.BulkMuteFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).bulk_mute_findings._get_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()).bulk_mute_findings._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 = SecurityCenterClient( + 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.bulk_mute_findings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_bulk_mute_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.bulk_mute_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_bulk_mute_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_bulk_mute_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_bulk_mute_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.BulkMuteFindingsRequest.pb(securitycenter_service.BulkMuteFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = securitycenter_service.BulkMuteFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.bulk_mute_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_bulk_mute_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BulkMuteFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.bulk_mute_findings(request) + + +def test_bulk_mute_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.bulk_mute_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/v2/{parent=organizations/*}/findings:bulkMute" % client.transport._host, args[1]) + + +def test_bulk_mute_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent='parent_value', + ) + + +def test_bulk_mute_findings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateBigQueryExportRequest, + dict, +]) +def test_create_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/locations/sample2'} + request_init["big_query_export"] = {'name': 'name_value', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.CreateBigQueryExportRequest.meta.fields["big_query_export"] + + 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["big_query_export"].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["big_query_export"][field])): + del request_init["big_query_export"][field][i][subfield] + else: + del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + +def test_create_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + + request = {} + client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.CreateBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["big_query_export_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 "bigQueryExportId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "bigQueryExportId" in jsonified_request + assert jsonified_request["bigQueryExportId"] == request_init["big_query_export_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["bigQueryExportId"] = 'big_query_export_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("big_query_export_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 "bigQueryExportId" in jsonified_request + assert jsonified_request["bigQueryExportId"] == 'big_query_export_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + expected_params = [ + ( + "bigQueryExportId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(("bigQueryExportId", )) & set(("parent", "bigQueryExport", "bigQueryExportId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_big_query_export") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_big_query_export") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateBigQueryExportRequest.pb(securitycenter_service.CreateBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) + + request = securitycenter_service.CreateBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.create_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_big_query_export(request) + + +def test_create_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{parent=organizations/*/locations/*}/bigQueryExports" % client.transport._host, args[1]) + + +def test_create_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent='parent_value', + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + big_query_export_id='big_query_export_id_value', + ) + + +def test_create_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateFindingRequest, + dict, +]) +def test_create_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2/locations/sample3'} + request_init["finding"] = {'name': 'name_value', 'canonical_name': 'canonical_name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'mute': 1, 'mute_info': {'static_mute': {'state': 1, 'apply_time': {}}, 'dynamic_mute_records': [{'mute_config': 'mute_config_value', 'match_time': {}}]}, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True, 'exploit_release_date': {}}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.create_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.create_finding] = mock_rpc + + request = {} + client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["finding_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 "findingId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "findingId" in jsonified_request + assert jsonified_request["findingId"] == request_init["finding_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["findingId"] = 'finding_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request + assert jsonified_request["findingId"] == 'finding_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.create_finding(request) + + expected_params = [ + ( + "findingId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.CreateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2/locations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_finding(request) + + +def test_create_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2/locations/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + finding=gcs_finding.Finding(name='name_value'), + finding_id='finding_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 = gcs_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.create_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/v2/{parent=organizations/*/sources/*/locations/*}/findings" % client.transport._host, args[1]) + + +def test_create_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding=gcs_finding.Finding(name='name_value'), + finding_id='finding_id_value', + ) + + +def test_create_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateMuteConfigRequest, + dict, +]) +def test_create_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/locations/sample2'} + request_init["mute_config"] = {'name': 'name_value', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'type_': 1, 'expiry_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 = securitycenter_service.CreateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): + del request_init["mute_config"][field][i][subfield] + else: + del request_init["mute_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 = gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + +def test_create_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + + request = {} + client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.CreateMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["mute_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 "muteConfigId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "muteConfigId" in jsonified_request + assert jsonified_request["muteConfigId"] == request_init["mute_config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["muteConfigId"] = 'mute_config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("mute_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 "muteConfigId" in jsonified_request + assert jsonified_request["muteConfigId"] == 'mute_config_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + expected_params = [ + ( + "muteConfigId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("muteConfigId", )) & set(("parent", "muteConfig", "muteConfigId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_mute_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_mute_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateMuteConfigRequest.pb(securitycenter_service.CreateMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) + + request = securitycenter_service.CreateMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_mute_config.MuteConfig() + + client.create_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_mute_config(request) + + +def test_create_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_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 = gcs_mute_config.MuteConfig.pb(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_mute_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/v2/{parent=organizations/*/locations/*}/muteConfigs" % client.transport._host, args[1]) + + +def test_create_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent='parent_value', + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + mute_config_id='mute_config_id_value', + ) + + +def test_create_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateNotificationConfigRequest, + dict, +]) +def test_create_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/locations/sample2'} + request_init["notification_config"] = {'name': 'name_value', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.CreateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_create_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.CreateNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["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 "configId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "configId" in jsonified_request + assert jsonified_request["configId"] == request_init["config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["configId"] = 'config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("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 "configId" in jsonified_request + assert jsonified_request["configId"] == 'config_id_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ( + "configId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("configId", )) & set(("parent", "configId", "notificationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateNotificationConfigRequest.pb(securitycenter_service.CreateNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) + + request = securitycenter_service.CreateNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.create_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_notification_config(request) + + +def test_create_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + config_id='config_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 = gcs_notification_config.NotificationConfig.pb(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_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/v2/{parent=organizations/*/locations/*}/notificationConfigs" % client.transport._host, args[1]) + + +def test_create_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + config_id='config_id_value', + ) + + +def test_create_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.CreateSourceRequest, + dict, +]) +def test_create_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1'} + request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_create_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.CreateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_source(request) + + +def test_create_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v2/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_create_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +def test_create_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteBigQueryExportRequest, + dict, +]) +def test_delete_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_big_query_export] = mock_rpc + + request = {} + client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.DeleteBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + 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_big_query_export(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_big_query_export") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteBigQueryExportRequest.pb(securitycenter_service.DeleteBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_big_query_export(request) + + +def test_delete_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/locations/sample2/bigQueryExports/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_big_query_export(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{name=organizations/*/locations/*/bigQueryExports/*}" % client.transport._host, args[1]) + + +def test_delete_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name='name_value', + ) + + +def test_delete_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteMuteConfigRequest, + dict, +]) +def test_delete_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/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 = 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + + request = {} + client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.DeleteMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( + 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_mute_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_mute_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteMuteConfigRequest.pb(securitycenter_service.DeleteMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_mute_config(request) + + +def test_delete_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/muteConfigs/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_mute_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/v2/{name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name='name_value', + ) + + +def test_delete_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, +]) +def test_delete_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = 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_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.DeleteNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_notification_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteNotificationConfigRequest.pb(securitycenter_service.DeleteNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_notification_config(request) + + +def test_delete_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/locations/sample2/notificationConfigs/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_notification_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/v2/{name=organizations/*/locations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +def test_delete_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.DeleteResourceValueConfigRequest, + dict, +]) +def test_delete_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = 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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + + request = {} + client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.DeleteResourceValueConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( + 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_resource_value_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_resource_value_config") as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteResourceValueConfigRequest.pb(securitycenter_service.DeleteResourceValueConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteResourceValueConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteResourceValueConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_resource_value_config(request) + + +def test_delete_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/resourceValueConfigs/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_resource_value_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/v2/{name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_resource_value_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name='name_value', + ) + + +def test_delete_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetBigQueryExportRequest, + dict, +]) +def test_get_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + +def test_get_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc + + request = {} + client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.GetBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_big_query_export") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_big_query_export") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetBigQueryExportRequest.pb(securitycenter_service.GetBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) + + request = securitycenter_service.GetBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.get_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_big_query_export(request) + + +def test_get_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{name=organizations/*/locations/*/bigQueryExports/*}" % client.transport._host, args[1]) + + +def test_get_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name='name_value', + ) + + +def test_get_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSimulationRequest, + dict, +]) +def test_get_simulation_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation( + name='name_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = simulation.Simulation.pb(return_value) + 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_simulation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == 'name_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + +def test_get_simulation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_simulation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc + + request = {} + client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_simulation(request) + + # Establish 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_simulation_rest_required_fields(request_type=securitycenter_service.GetSimulationRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_simulation._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_simulation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = simulation.Simulation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = simulation.Simulation.pb(return_value) + 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_simulation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_simulation_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_simulation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_simulation_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_simulation") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_simulation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSimulationRequest.pb(securitycenter_service.GetSimulationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = simulation.Simulation.to_json(simulation.Simulation()) + + request = securitycenter_service.GetSimulationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = simulation.Simulation() + + client.get_simulation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_simulation_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSimulationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_simulation(request) + + +def test_get_simulation_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = simulation.Simulation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation.pb(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_simulation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{name=organizations/*/simulations/*}" % client.transport._host, args[1]) + + +def test_get_simulation_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_simulation( + securitycenter_service.GetSimulationRequest(), + name='name_value', + ) + + +def test_get_simulation_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetValuedResourceRequest, + dict, +]) +def test_get_valued_resource_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource( + name='name_value', + resource='resource_value', + resource_type='resource_type_value', + display_name='display_name_value', + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = valued_resource.ValuedResource.pb(return_value) + 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_valued_resource(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == 'name_value' + assert response.resource == 'resource_value' + assert response.resource_type == 'resource_type_value' + assert response.display_name == 'display_name_value' + assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + +def test_get_valued_resource_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_valued_resource in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc + + request = {} + client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_valued_resource(request) + + # Establish 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_valued_resource_rest_required_fields(request_type=securitycenter_service.GetValuedResourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_valued_resource._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_valued_resource._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = valued_resource.ValuedResource() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = valued_resource.ValuedResource.pb(return_value) + 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_valued_resource(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_valued_resource_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_valued_resource._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_valued_resource_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_valued_resource") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_valued_resource") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetValuedResourceRequest.pb(securitycenter_service.GetValuedResourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = valued_resource.ValuedResource.to_json(valued_resource.ValuedResource()) + + request = securitycenter_service.GetValuedResourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = valued_resource.ValuedResource() + + client.get_valued_resource(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_valued_resource_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetValuedResourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_valued_resource(request) + + +def test_get_valued_resource_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = valued_resource.ValuedResource() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource.pb(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_valued_resource(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{name=organizations/*/simulations/*/valuedResources/*}" % client.transport._host, args[1]) + + +def test_get_valued_resource_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name='name_value', + ) + + +def test_get_valued_resource_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_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_iam_policy] = mock_rpc + + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.get_iam_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/v2/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetMuteConfigRequest, + dict, +]) +def test_get_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC + +def test_get_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_mute_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_mute_config] = mock_rpc + + request = {} + client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.GetMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = mute_config.MuteConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_mute_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_mute_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetMuteConfigRequest.pb(securitycenter_service.GetMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = mute_config.MuteConfig.to_json(mute_config.MuteConfig()) + + request = securitycenter_service.GetMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = mute_config.MuteConfig() + + client.get_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_mute_config(request) + + +def test_get_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig.pb(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_mute_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/v2/{name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) + + +def test_get_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name='name_value', + ) + + +def test_get_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetNotificationConfigRequest, + dict, +]) +def test_get_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_get_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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_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_notification_config] = mock_rpc + + request = {} + client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.GetNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetNotificationConfigRequest.pb(securitycenter_service.GetNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = notification_config.NotificationConfig.to_json(notification_config.NotificationConfig()) + + request = securitycenter_service.GetNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = notification_config.NotificationConfig() + + client.get_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_notification_config(request) + + +def test_get_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = notification_config.NotificationConfig.pb(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_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/v2/{name=organizations/*/locations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_get_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +def test_get_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetResourceValueConfigRequest, + dict, +]) +def test_get_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + +def test_get_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc + + request = {} + client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.GetResourceValueConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource_value_config.ResourceValueConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_resource_value_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_resource_value_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetResourceValueConfigRequest.pb(securitycenter_service.GetResourceValueConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource_value_config.ResourceValueConfig.to_json(resource_value_config.ResourceValueConfig()) + + request = securitycenter_service.GetResourceValueConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource_value_config.ResourceValueConfig() + + client.get_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetResourceValueConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_resource_value_config(request) + + +def test_get_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resource_value_config.ResourceValueConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig.pb(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_resource_value_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/v2/{name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) + + +def test_get_resource_value_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name='name_value', + ) + + +def test_get_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GetSourceRequest, + dict, +]) +def test_get_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/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 = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_get_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_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_source] = mock_rpc + + request = {} + client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = source.Source.to_json(source.Source()) + + request = securitycenter_service.GetSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = source.Source() + + client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_source(request) + + +def test_get_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v2/{name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_get_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +def test_get_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.GroupFindingsRequest, + dict, +]) +def test_group_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.group_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_group_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.group_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.group_findings] = mock_rpc + + request = {} + client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["groupBy"] = 'group_by_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == 'group_by_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.group_findings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_group_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.group_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) + + request = securitycenter_service.GroupFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupFindingsResponse() + + client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_findings(request) + + +def test_group_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + group_by='group_by_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v2/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) + + +def test_group_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} + + pager = client.group_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + + pages = list(client.group_findings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListAttackPathsRequest, + dict, +]) +def test_list_attack_paths_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) + 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_attack_paths(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_attack_paths_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_attack_paths in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc + + request = {} + client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_attack_paths(request) + + # Establish 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_attack_paths_rest_required_fields(request_type=securitycenter_service.ListAttackPathsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_attack_paths._get_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_attack_paths._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAttackPathsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) + 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_attack_paths(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_attack_paths_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_attack_paths._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_attack_paths_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_attack_paths") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_attack_paths") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListAttackPathsRequest.pb(securitycenter_service.ListAttackPathsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListAttackPathsResponse.to_json(securitycenter_service.ListAttackPathsResponse()) + + request = securitycenter_service.ListAttackPathsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListAttackPathsResponse() + + client.list_attack_paths(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_attack_paths_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAttackPathsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_attack_paths(request) + + +def test_list_attack_paths_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAttackPathsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse.pb(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_attack_paths(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{parent=organizations/*/simulations/*}/attackPaths" % client.transport._host, args[1]) + + +def test_list_attack_paths_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent='parent_value', + ) + + +def test_list_attack_paths_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token='def', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListAttackPathsResponse.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': 'organizations/sample1/simulations/sample2'} + + pager = client.list_attack_paths(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, attack_path.AttackPath) + for i in results) + + pages = list(client.list_attack_paths(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListBigQueryExportsRequest, + dict, +]) +def test_list_big_query_exports_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) + 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_big_query_exports(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_big_query_exports_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_big_query_exports in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc + + request = {} + client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_big_query_exports(request) + + # Establish 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_big_query_exports_rest_required_fields(request_type=securitycenter_service.ListBigQueryExportsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_big_query_exports._get_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_big_query_exports._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListBigQueryExportsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) + 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_big_query_exports(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_big_query_exports_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_big_query_exports._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_big_query_exports_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_big_query_exports") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_big_query_exports") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListBigQueryExportsRequest.pb(securitycenter_service.ListBigQueryExportsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListBigQueryExportsResponse.to_json(securitycenter_service.ListBigQueryExportsResponse()) + + request = securitycenter_service.ListBigQueryExportsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListBigQueryExportsResponse() + + client.list_big_query_exports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_big_query_exports_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListBigQueryExportsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_big_query_exports(request) + + +def test_list_big_query_exports_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListBigQueryExportsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse.pb(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_big_query_exports(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{parent=organizations/*/locations/*}/bigQueryExports" % client.transport._host, args[1]) + + +def test_list_big_query_exports_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent='parent_value', + ) + + +def test_list_big_query_exports_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token='abc', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token='def', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListBigQueryExportsResponse.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': 'organizations/sample1/locations/sample2'} + + pager = client.list_big_query_exports(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, bigquery_export.BigQueryExport) + for i in results) + + pages = list(client.list_big_query_exports(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListFindingsRequest, + dict, +]) +def test_list_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.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' + assert response.total_size == 1086 + +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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=securitycenter_service.ListFindingsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("field_mask", "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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.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 = securitycenter_service.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 = [ + ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("fieldMask", "filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) + + request = securitycenter_service.ListFindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListFindingsResponse() + + client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_findings(request) + + +def test_list_findings_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.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/v2/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) + + +def test_list_findings_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + + +def test_list_findings_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} + + pager = client.list_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) + 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 + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListMuteConfigsRequest, + dict, +]) +def test_list_mute_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) + 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_mute_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_mute_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_mute_configs] = mock_rpc + + request = {} + client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_mute_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_mute_configs_rest_required_fields(request_type=securitycenter_service.ListMuteConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListMuteConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) + 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_mute_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_mute_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_mute_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_mute_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_mute_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_mute_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListMuteConfigsRequest.pb(securitycenter_service.ListMuteConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListMuteConfigsResponse.to_json(securitycenter_service.ListMuteConfigsResponse()) + + request = securitycenter_service.ListMuteConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListMuteConfigsResponse() + + client.list_mute_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_mute_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListMuteConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_mute_configs(request) + + +def test_list_mute_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListMuteConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse.pb(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_mute_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/v2/{parent=organizations/*}/muteConfigs" % client.transport._host, args[1]) + + +def test_list_mute_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent='parent_value', + ) + + +def test_list_mute_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token='def', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListMuteConfigsResponse.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': 'organizations/sample1'} + + pager = client.list_mute_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, mute_config.MuteConfig) + for i in results) + + pages = list(client.list_mute_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListNotificationConfigsRequest, + dict, +]) +def test_list_notification_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) + 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_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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_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_notification_configs] = mock_rpc + + request = {} + client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_notification_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_notification_configs_rest_required_fields(request_type=securitycenter_service.ListNotificationConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListNotificationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) + 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_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_notification_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_notification_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_notification_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_notification_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_notification_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListNotificationConfigsRequest.pb(securitycenter_service.ListNotificationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListNotificationConfigsResponse.to_json(securitycenter_service.ListNotificationConfigsResponse()) + + request = securitycenter_service.ListNotificationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListNotificationConfigsResponse() + + client.list_notification_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_notification_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_notification_configs(request) + + +def test_list_notification_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListNotificationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse.pb(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_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/v2/{parent=organizations/*/locations/*}/notificationConfigs" % client.transport._host, args[1]) + + +def test_list_notification_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListNotificationConfigsResponse.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': 'organizations/sample1/locations/sample2'} + + pager = client.list_notification_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, notification_config.NotificationConfig) + for i in results) + + pages = list(client.list_notification_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListResourceValueConfigsRequest, + dict, +]) +def test_list_resource_value_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc + + request = {} + client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_value_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_resource_value_configs_rest_required_fields(request_type=securitycenter_service.ListResourceValueConfigsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListResourceValueConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) + 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_resource_value_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_resource_value_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_resource_value_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_resource_value_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_resource_value_configs") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_resource_value_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListResourceValueConfigsRequest.pb(securitycenter_service.ListResourceValueConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListResourceValueConfigsResponse.to_json(securitycenter_service.ListResourceValueConfigsResponse()) + + request = securitycenter_service.ListResourceValueConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListResourceValueConfigsResponse() + + client.list_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListResourceValueConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_resource_value_configs(request) + + +def test_list_resource_value_configs_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListResourceValueConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse.pb(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_resource_value_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/v2/{parent=organizations/*}/resourceValueConfigs" % client.transport._host, args[1]) + + +def test_list_resource_value_configs_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent='parent_value', + ) + + +def test_list_resource_value_configs_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token='def', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListResourceValueConfigsResponse.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': 'organizations/sample1'} + + pager = client.list_resource_value_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resource_value_config.ResourceValueConfig) + for i in results) + + pages = list(client.list_resource_value_configs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListSourcesRequest, + dict, +]) +def test_list_sources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_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_sources] = mock_rpc + + request = {} + client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListSourcesResponse.pb(return_value) + 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_sources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_sources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_sources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) + + request = securitycenter_service.ListSourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListSourcesResponse() + + client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_sources(request) + + +def test_list_sources_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v2/{parent=organizations/*}/sources" % client.transport._host, args[1]) + + +def test_list_sources_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} + + pager = client.list_sources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, source.Source) + for i in results) + + pages = list(client.list_sources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.ListValuedResourcesRequest, + dict, +]) +def test_list_valued_resources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) + 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_valued_resources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + +def test_list_valued_resources_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_valued_resources in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc + + request = {} + client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_valued_resources(request) + + # Establish 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_valued_resources_rest_required_fields(request_type=securitycenter_service.ListValuedResourcesRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_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_valued_resources._get_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_valued_resources._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListValuedResourcesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) + 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_valued_resources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_valued_resources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_valued_resources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_valued_resources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_valued_resources") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_valued_resources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListValuedResourcesRequest.pb(securitycenter_service.ListValuedResourcesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListValuedResourcesResponse.to_json(securitycenter_service.ListValuedResourcesResponse()) + + request = securitycenter_service.ListValuedResourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListValuedResourcesResponse() + + client.list_valued_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_valued_resources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListValuedResourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/simulations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_valued_resources(request) + + +def test_list_valued_resources_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListValuedResourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse.pb(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_valued_resources(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{parent=organizations/*/simulations/*}/valuedResources" % client.transport._host, args[1]) + + +def test_list_valued_resources_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent='parent_value', + ) + + +def test_list_valued_resources_rest_pager(transport: str = 'rest'): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token='abc', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token='def', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(securitycenter_service.ListValuedResourcesResponse.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': 'organizations/sample1/simulations/sample2'} + + pager = client.list_valued_resources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, valued_resource.ValuedResource) + for i in results) + + pages = list(client.list_valued_resources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetFindingStateRequest, + dict, +]) +def test_set_finding_state_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # 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 + response = client.set_finding_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_set_finding_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_finding_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.set_finding_state] = mock_rpc + + request = {} + client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( + 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': "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 = 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.set_finding_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_finding_state_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_finding_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "state", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_finding_state_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetFindingStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_finding_state(request) + + +def test_set_finding_state_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + state=finding.Finding.State.ACTIVE, + ) + mock_args.update(sample_request) + + # 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.set_finding_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/v2/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) + + +def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + ) + + +def test_set_finding_state_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # 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 + response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_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.set_iam_policy] = mock_rpc + + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_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.set_iam_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/v2/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.SetMuteRequest, + dict, +]) +def test_set_mute_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # 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 + response = client.set_mute(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_set_mute_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_mute in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc + + request = {} + client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_mute(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_set_mute_rest_required_fields(request_type=securitycenter_service.SetMuteRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SecurityCenterClient( + 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': "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 = 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.set_mute(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_mute_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_mute._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "mute", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_mute_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_mute") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_mute") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetMuteRequest.pb(securitycenter_service.SetMuteRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetMuteRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_mute(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_mute_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetMuteRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_mute(request) + + +def test_set_mute_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + mock_args.update(sample_request) + + # 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.set_mute(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{name=organizations/*/sources/*/findings/*}:setMute" % client.transport._host, args[1]) + + +def test_set_mute_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_mute( + securitycenter_service.SetMuteRequest(), + name='name_value', + mute=finding.Finding.Mute.MUTED, + ) + + +def test_set_mute_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # 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 + response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.test_iam_permissions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc + + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/sample1/sources/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1/sources/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_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.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateBigQueryExportRequest, + dict, +]) +def test_update_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'big_query_export': {'name': 'organizations/sample1/locations/sample2/bigQueryExports/sample3'}} + request_init["big_query_export"] = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/sample3', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.UpdateBigQueryExportRequest.meta.fields["big_query_export"] + + 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["big_query_export"].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["big_query_export"][field])): + del request_init["big_query_export"][field][i][subfield] + else: + del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( + name='name_value', + description='description_value', + filter='filter_value', + dataset='dataset_value', + most_recent_editor='most_recent_editor_value', + principal='principal_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.dataset == 'dataset_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.principal == 'principal_value' + +def test_update_big_query_export_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_big_query_export in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc + + request = {} + client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_big_query_export(request) + + # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.UpdateBigQueryExportRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_big_query_export._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_big_query_export._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = bigquery_export.BigQueryExport.pb(return_value) + 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_big_query_export(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("bigQueryExport", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_big_query_export") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_big_query_export") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateBigQueryExportRequest.pb(securitycenter_service.UpdateBigQueryExportRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) + + request = securitycenter_service.UpdateBigQueryExportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.update_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateBigQueryExportRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'big_query_export': {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_big_query_export(request) + + +def test_update_big_query_export_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = {'big_query_export': {'name': 'organizations/sample1/locations/sample2/bigQueryExports/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + big_query_export=bigquery_export.BigQueryExport(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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{big_query_export.name=organizations/*/locations/*/bigQueryExports/*}" % client.transport._host, args[1]) + + +def test_update_big_query_export_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateExternalSystemRequest, + dict, +]) +def test_update_external_system_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} + request_init["external_system"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4', 'assignees': ['assignees_value1', 'assignees_value2'], 'external_uid': 'external_uid_value', 'status': 'status_value', 'external_system_update_time': {'seconds': 751, 'nanos': 543}, 'case_uri': 'case_uri_value', 'case_priority': 'case_priority_value', 'case_sla': {}, 'case_create_time': {}, 'case_close_time': {}, 'ticket_info': {'id': 'id_value', 'assignee': 'assignee_value', 'description': 'description_value', 'uri': 'uri_value', 'status': 'status_value', 'update_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 = securitycenter_service.UpdateExternalSystemRequest.meta.fields["external_system"] + + 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["external_system"].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["external_system"][field])): + del request_init["external_system"][field][i][subfield] + else: + del request_init["external_system"][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 = gcs_external_system.ExternalSystem( + name='name_value', + assignees=['assignees_value'], + external_uid='external_uid_value', + status='status_value', + case_uri='case_uri_value', + case_priority='case_priority_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_external_system.ExternalSystem.pb(return_value) + 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_external_system(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == 'name_value' + assert response.assignees == ['assignees_value'] + assert response.external_uid == 'external_uid_value' + assert response.status == 'status_value' + assert response.case_uri == 'case_uri_value' + assert response.case_priority == 'case_priority_value' + +def test_update_external_system_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_external_system in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc + + request = {} + client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_external_system(request) + + # Establish 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_external_system_rest_required_fields(request_type=securitycenter_service.UpdateExternalSystemRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_external_system._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_external_system._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_external_system.ExternalSystem() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_external_system.ExternalSystem.pb(return_value) + 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_external_system(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_external_system_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_external_system._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("externalSystem", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_external_system_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_external_system") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_external_system") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateExternalSystemRequest.pb(securitycenter_service.UpdateExternalSystemRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_external_system.ExternalSystem.to_json(gcs_external_system.ExternalSystem()) + + request = securitycenter_service.UpdateExternalSystemRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_external_system.ExternalSystem() + + client.update_external_system(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_external_system_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateExternalSystemRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_external_system(request) + + +def test_update_external_system_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_external_system.ExternalSystem() + + # get arguments that satisfy an http rule for this method + sample_request = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + external_system=gcs_external_system.ExternalSystem(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 = gcs_external_system.ExternalSystem.pb(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_external_system(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}" % client.transport._host, args[1]) + + +def test_update_external_system_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_external_system_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateFindingRequest, + dict, +]) +def test_update_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'canonical_name': 'canonical_name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'mute': 1, 'mute_info': {'static_mute': {'state': 1, 'apply_time': {}}, 'dynamic_mute_records': [{'mute_config': 'mute_config_value', 'match_time': {}}]}, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True, 'exploit_release_date': {}}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name='name_value', + canonical_name='canonical_name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator='mute_initiator_value', + parent_display_name='parent_display_name_value', + description='description_value', + next_steps='next_steps_value', + module_name='module_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_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.update_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == 'mute_initiator_value' + assert response.parent_display_name == 'parent_display_name_value' + assert response.description == 'description_value' + assert response.next_steps == 'next_steps_value' + assert response.module_name == 'module_name_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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.update_finding] = mock_rpc + + request = {} + client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_finding._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_finding._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_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': "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 = gcs_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.update_finding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.UpdateFindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_finding(request) + + +def test_update_finding_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + finding=gcs_finding.Finding(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 = gcs_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.update_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/v2/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) + + +def test_update_finding_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateMuteConfigRequest, + dict, +]) +def test_update_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} + request_init["mute_config"] = {'name': 'organizations/sample1/muteConfigs/sample2', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'type_': 1, 'expiry_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 = securitycenter_service.UpdateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): + del request_init["mute_config"][field][i][subfield] + else: + del request_init["mute_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 = gcs_mute_config.MuteConfig( + name='name_value', + description='description_value', + filter='filter_value', + most_recent_editor='most_recent_editor_value', + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.filter == 'filter_value' + assert response.most_recent_editor == 'most_recent_editor_value' + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + +def test_update_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_mute_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_mute_config] = mock_rpc + + request = {} + client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.UpdateMuteConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_mute_config.MuteConfig.pb(return_value) + 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_mute_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("muteConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_mute_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_mute_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateMuteConfigRequest.pb(securitycenter_service.UpdateMuteConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) + + request = securitycenter_service.UpdateMuteConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_mute_config.MuteConfig() + + client.update_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateMuteConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_mute_config(request) + + +def test_update_mute_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + mute_config=gcs_mute_config.MuteConfig(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 = gcs_mute_config.MuteConfig.pb(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_mute_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/v2/{mute_config.name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) + + +def test_update_mute_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, +]) +def test_update_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'notification_config': {'name': 'organizations/sample1/locations/sample2/notificationConfigs/sample3'}} + request_init["notification_config"] = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/sample3', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.UpdateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + +def test_update_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_notification_config] = mock_rpc + + request = {} + client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.UpdateNotificationConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_notification_config.NotificationConfig.pb(return_value) + 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_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("notificationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_notification_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_notification_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateNotificationConfigRequest.pb(securitycenter_service.UpdateNotificationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) + + request = securitycenter_service.UpdateNotificationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.update_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'notification_config': {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_notification_config(request) + + +def test_update_notification_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'notification_config': {'name': 'organizations/sample1/locations/sample2/notificationConfigs/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/v2/{notification_config.name=organizations/*/locations/*/notificationConfigs/*}" % client.transport._host, args[1]) + + +def test_update_notification_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateResourceValueConfigRequest, + dict, +]) +def test_update_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} + request_init["resource_value_config"] = {'name': 'organizations/sample1/resourceValueConfigs/sample2', 'resource_value': 1, 'tag_values': ['tag_values_value1', 'tag_values_value2'], 'resource_type': 'resource_type_value', 'scope': 'scope_value', 'resource_labels_selector': {}, 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'cloud_provider': 1, 'sensitive_data_protection_mapping': {'high_sensitivity_mapping': 1, 'medium_sensitivity_mapping': 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 = securitycenter_service.UpdateResourceValueConfigRequest.meta.fields["resource_value_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["resource_value_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["resource_value_config"][field])): + del request_init["resource_value_config"][field][i][subfield] + else: + del request_init["resource_value_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 = gcs_resource_value_config.ResourceValueConfig( + name='name_value', + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=['tag_values_value'], + resource_type='resource_type_value', + scope='scope_value', + description='description_value', + cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == 'name_value' + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ['tag_values_value'] + assert response.resource_type == 'resource_type_value' + assert response.scope == 'scope_value' + assert response.description == 'description_value' + assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM + +def test_update_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_resource_value_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_resource_value_config] = mock_rpc + + request = {} + client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.UpdateResourceValueConfigRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_resource_value_config.ResourceValueConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_resource_value_config.ResourceValueConfig.pb(return_value) + 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_resource_value_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("resourceValueConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_resource_value_config") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_resource_value_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateResourceValueConfigRequest.pb(securitycenter_service.UpdateResourceValueConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_resource_value_config.ResourceValueConfig.to_json(gcs_resource_value_config.ResourceValueConfig()) + + request = securitycenter_service.UpdateResourceValueConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_resource_value_config.ResourceValueConfig() + + client.update_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateResourceValueConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_resource_value_config(request) + + +def test_update_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_resource_value_config.ResourceValueConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + resource_value_config=gcs_resource_value_config.ResourceValueConfig(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 = gcs_resource_value_config.ResourceValueConfig.pb(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_resource_value_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/v2/{resource_value_config.name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) + + +def test_update_resource_value_config_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, +]) +def test_update_security_marks_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks'}} + request_init["security_marks"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks', 'marks': {}, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] + + 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["security_marks"].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["security_marks"][field])): + del request_init["security_marks"][field][i][subfield] + else: + del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + +def test_update_security_marks_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_security_marks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc + + request = {} + client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_security_marks(request) + + # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_security_marks._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_security_marks._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) + 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_security_marks(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_security_marks_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_security_marks._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("securityMarks", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_security_marks_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) + + request = securitycenter_service.UpdateSecurityMarksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_security_marks.SecurityMarks() + + client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'security_marks': {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_security_marks(request) + + +def test_update_security_marks_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + + # get arguments that satisfy an http rule for this method + sample_request = {'security_marks': {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks'}} + + # get truthy value for each flattened field + mock_args = dict( + security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v2/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}" % client.transport._host, args[1]) + + +def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_security_marks_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + securitycenter_service.UpdateSourceRequest, + dict, +]) +def test_update_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_source.Source.pb(return_value) + 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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + +def test_update_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should 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_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_source] = mock_rpc + + request = {} + client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): + transport_class = transports.SecurityCenterRestTransport + + 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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) + 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_source(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ + mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.UpdateSourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_source(request) + + +def test_update_source_rest_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v2/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) + + +def test_update_source_rest_flattened_error(transport: str = 'rest'): + client = SecurityCenterClient( + credentials=ga_credentials.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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SecurityCenterClient( + 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 = SecurityCenterClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecurityCenterClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, +]) +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() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SecurityCenterClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecurityCenterGrpcTransport, + ) + +def test_security_center_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_security_center_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.securitycenter_v2.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'batch_create_resource_value_configs', + 'bulk_mute_findings', + 'create_big_query_export', + 'create_finding', + 'create_mute_config', + 'create_notification_config', + 'create_source', + 'delete_big_query_export', + 'delete_mute_config', + 'delete_notification_config', + 'delete_resource_value_config', + 'get_big_query_export', + 'get_simulation', + 'get_valued_resource', + 'get_iam_policy', + 'get_mute_config', + 'get_notification_config', + 'get_resource_value_config', + 'get_source', + 'group_findings', + 'list_attack_paths', + 'list_big_query_exports', + 'list_findings', + 'list_mute_configs', + 'list_notification_configs', + 'list_resource_value_configs', + 'list_sources', + 'list_valued_resources', + 'set_finding_state', + 'set_iam_policy', + 'set_mute', + 'test_iam_permissions', + 'update_big_query_export', + 'update_external_system', + 'update_finding', + 'update_mute_config', + 'update_notification_config', + 'update_resource_value_config', + 'update_security_marks', + 'update_source', + '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_security_center_base_transport_with_credentials_file(): + # Instantiate the 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.securitycenter_v2.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + 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_security_center_base_transport_with_adc(): + # Test the default 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.securitycenter_v2.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +def test_security_center_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) + SecurityCenterClient() + 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_transport_auth_adc(transport_class): + # If 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, + ], +) +def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_security_center_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host 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( + "securitycenter.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="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_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.SecurityCenterRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_security_center_rest_lro_client(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a 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 + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_no_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_security_center_host_with_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'securitycenter.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://securitycenter.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_security_center_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SecurityCenterClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SecurityCenterClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.batch_create_resource_value_configs._session + session2 = client2.transport.batch_create_resource_value_configs._session + assert session1 != session2 + session1 = client1.transport.bulk_mute_findings._session + session2 = client2.transport.bulk_mute_findings._session + assert session1 != session2 + session1 = client1.transport.create_big_query_export._session + session2 = client2.transport.create_big_query_export._session + assert session1 != session2 + session1 = client1.transport.create_finding._session + session2 = client2.transport.create_finding._session + assert session1 != session2 + session1 = client1.transport.create_mute_config._session + session2 = client2.transport.create_mute_config._session + assert session1 != session2 + session1 = client1.transport.create_notification_config._session + session2 = client2.transport.create_notification_config._session + assert session1 != session2 + session1 = client1.transport.create_source._session + session2 = client2.transport.create_source._session + assert session1 != session2 + session1 = client1.transport.delete_big_query_export._session + session2 = client2.transport.delete_big_query_export._session + assert session1 != session2 + session1 = client1.transport.delete_mute_config._session + session2 = client2.transport.delete_mute_config._session + assert session1 != session2 + session1 = client1.transport.delete_notification_config._session + session2 = client2.transport.delete_notification_config._session + assert session1 != session2 + session1 = client1.transport.delete_resource_value_config._session + session2 = client2.transport.delete_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.get_big_query_export._session + session2 = client2.transport.get_big_query_export._session + assert session1 != session2 + session1 = client1.transport.get_simulation._session + session2 = client2.transport.get_simulation._session + assert session1 != session2 + session1 = client1.transport.get_valued_resource._session + session2 = client2.transport.get_valued_resource._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.get_mute_config._session + session2 = client2.transport.get_mute_config._session + assert session1 != session2 + session1 = client1.transport.get_notification_config._session + session2 = client2.transport.get_notification_config._session + assert session1 != session2 + session1 = client1.transport.get_resource_value_config._session + session2 = client2.transport.get_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.get_source._session + session2 = client2.transport.get_source._session + assert session1 != session2 + session1 = client1.transport.group_findings._session + session2 = client2.transport.group_findings._session + assert session1 != session2 + session1 = client1.transport.list_attack_paths._session + session2 = client2.transport.list_attack_paths._session + assert session1 != session2 + session1 = client1.transport.list_big_query_exports._session + session2 = client2.transport.list_big_query_exports._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_mute_configs._session + session2 = client2.transport.list_mute_configs._session + assert session1 != session2 + session1 = client1.transport.list_notification_configs._session + session2 = client2.transport.list_notification_configs._session + assert session1 != session2 + session1 = client1.transport.list_resource_value_configs._session + session2 = client2.transport.list_resource_value_configs._session + assert session1 != session2 + session1 = client1.transport.list_sources._session + session2 = client2.transport.list_sources._session + assert session1 != session2 + session1 = client1.transport.list_valued_resources._session + session2 = client2.transport.list_valued_resources._session + assert session1 != session2 + session1 = client1.transport.set_finding_state._session + session2 = client2.transport.set_finding_state._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.set_mute._session + session2 = client2.transport.set_mute._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 + session1 = client1.transport.update_big_query_export._session + session2 = client2.transport.update_big_query_export._session + assert session1 != session2 + session1 = client1.transport.update_external_system._session + session2 = client2.transport.update_external_system._session + assert session1 != session2 + session1 = client1.transport.update_finding._session + session2 = client2.transport.update_finding._session + assert session1 != session2 + session1 = client1.transport.update_mute_config._session + session2 = client2.transport.update_mute_config._session + assert session1 != session2 + session1 = client1.transport.update_notification_config._session + session2 = client2.transport.update_notification_config._session + assert session1 != session2 + session1 = client1.transport.update_resource_value_config._session + session2 = client2.transport.update_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.update_security_marks._session + session2 = client2.transport.update_security_marks._session + assert session1 != session2 + session1 = client1.transport.update_source._session + session2 = client2.transport.update_source._session + assert session1 != session2 +def test_security_center_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcTransport( + 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_security_center_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcAsyncIOTransport( + 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(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_security_center_grpc_lro_client(): + client = SecurityCenterClient( + 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_security_center_grpc_lro_async_client(): + client = SecurityCenterAsyncClient( + 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_attack_path_path(): + organization = "squid" + simulation = "clam" + valued_resource = "whelk" + attack_path = "octopus" + expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) + actual = SecurityCenterClient.attack_path_path(organization, simulation, valued_resource, attack_path) + assert expected == actual + + +def test_parse_attack_path_path(): + expected = { + "organization": "oyster", + "simulation": "nudibranch", + "valued_resource": "cuttlefish", + "attack_path": "mussel", + } + path = SecurityCenterClient.attack_path_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_attack_path_path(path) + assert expected == actual + +def test_big_query_export_path(): + organization = "winkle" + location = "nautilus" + export = "scallop" + expected = "organizations/{organization}/locations/{location}/bigQueryExports/{export}".format(organization=organization, location=location, export=export, ) + actual = SecurityCenterClient.big_query_export_path(organization, location, export) + assert expected == actual + + +def test_parse_big_query_export_path(): + expected = { + "organization": "abalone", + "location": "squid", + "export": "clam", + } + path = SecurityCenterClient.big_query_export_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_big_query_export_path(path) + assert expected == actual + +def test_dlp_job_path(): + project = "whelk" + dlp_job = "octopus" + expected = "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) + actual = SecurityCenterClient.dlp_job_path(project, dlp_job) + assert expected == actual + + +def test_parse_dlp_job_path(): + expected = { + "project": "oyster", + "dlp_job": "nudibranch", + } + path = SecurityCenterClient.dlp_job_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_dlp_job_path(path) + assert expected == actual + +def test_external_system_path(): + organization = "cuttlefish" + source = "mussel" + finding = "winkle" + externalsystem = "nautilus" + expected = "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) + actual = SecurityCenterClient.external_system_path(organization, source, finding, externalsystem) + assert expected == actual + + +def test_parse_external_system_path(): + expected = { + "organization": "scallop", + "source": "abalone", + "finding": "squid", + "externalsystem": "clam", + } + path = SecurityCenterClient.external_system_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_external_system_path(path) + assert expected == actual + +def test_finding_path(): + organization = "whelk" + source = "octopus" + finding = "oyster" + expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + actual = SecurityCenterClient.finding_path(organization, source, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "organization": "nudibranch", + "source": "cuttlefish", + "finding": "mussel", + } + path = SecurityCenterClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_finding_path(path) + assert expected == actual + +def test_mute_config_path(): + organization = "winkle" + mute_config = "nautilus" + expected = "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) + actual = SecurityCenterClient.mute_config_path(organization, mute_config) + assert expected == actual + + +def test_parse_mute_config_path(): + expected = { + "organization": "scallop", + "mute_config": "abalone", + } + path = SecurityCenterClient.mute_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_mute_config_path(path) + assert expected == actual + +def test_notification_config_path(): + organization = "squid" + location = "clam" + notification_config = "whelk" + expected = "organizations/{organization}/locations/{location}/notificationConfigs/{notification_config}".format(organization=organization, location=location, notification_config=notification_config, ) + actual = SecurityCenterClient.notification_config_path(organization, location, notification_config) + assert expected == actual + + +def test_parse_notification_config_path(): + expected = { + "organization": "octopus", + "location": "oyster", + "notification_config": "nudibranch", + } + path = SecurityCenterClient.notification_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_notification_config_path(path) + assert expected == actual + +def test_policy_path(): + organization = "cuttlefish" + constraint_name = "mussel" + expected = "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) + actual = SecurityCenterClient.policy_path(organization, constraint_name) + assert expected == actual + + +def test_parse_policy_path(): + expected = { + "organization": "winkle", + "constraint_name": "nautilus", + } + path = SecurityCenterClient.policy_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_policy_path(path) + assert expected == actual + +def test_resource_value_config_path(): + organization = "scallop" + resource_value_config = "abalone" + expected = "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) + actual = SecurityCenterClient.resource_value_config_path(organization, resource_value_config) + assert expected == actual + + +def test_parse_resource_value_config_path(): + expected = { + "organization": "squid", + "resource_value_config": "clam", + } + path = SecurityCenterClient.resource_value_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_resource_value_config_path(path) + assert expected == actual + +def test_security_marks_path(): + organization = "whelk" + asset = "octopus" + expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.security_marks_path(organization, asset) + assert expected == actual + + +def test_parse_security_marks_path(): + expected = { + "organization": "oyster", + "asset": "nudibranch", + } + path = SecurityCenterClient.security_marks_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_marks_path(path) + assert expected == actual + +def test_simulation_path(): + organization = "cuttlefish" + simulation = "mussel" + expected = "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) + actual = SecurityCenterClient.simulation_path(organization, simulation) + assert expected == actual + + +def test_parse_simulation_path(): + expected = { + "organization": "winkle", + "simulation": "nautilus", + } + path = SecurityCenterClient.simulation_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_simulation_path(path) + assert expected == actual + +def test_source_path(): + organization = "scallop" + source = "abalone" + expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + actual = SecurityCenterClient.source_path(organization, source) + assert expected == actual + + +def test_parse_source_path(): + expected = { + "organization": "squid", + "source": "clam", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_path(path) + assert expected == actual + +def test_table_data_profile_path(): + project = "whelk" + table_profile = "octopus" + expected = "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) + actual = SecurityCenterClient.table_data_profile_path(project, table_profile) + assert expected == actual + + +def test_parse_table_data_profile_path(): + expected = { + "project": "oyster", + "table_profile": "nudibranch", + } + path = SecurityCenterClient.table_data_profile_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_table_data_profile_path(path) + assert expected == actual + +def test_topic_path(): + project = "cuttlefish" + topic = "mussel" + expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + actual = SecurityCenterClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "winkle", + "topic": "nautilus", + } + path = SecurityCenterClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_topic_path(path) + assert expected == actual + +def test_valued_resource_path(): + organization = "scallop" + simulation = "abalone" + valued_resource = "squid" + expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) + actual = SecurityCenterClient.valued_resource_path(organization, simulation, valued_resource) + assert expected == actual + + +def test_parse_valued_resource_path(): + expected = { + "organization": "clam", + "simulation": "whelk", + "valued_resource": "octopus", + } + path = SecurityCenterClient.valued_resource_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_valued_resource_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SecurityCenterClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = SecurityCenterClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = SecurityCenterClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = SecurityCenterClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SecurityCenterClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = SecurityCenterClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = SecurityCenterClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = SecurityCenterClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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 = SecurityCenterClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = SecurityCenterClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + transport_class = SecurityCenterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations/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 = 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.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations/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 = 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_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations/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() + + # 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 + + 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(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'organizations/sample1/operations'}, 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() + 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'organizations/sample1/operations'} + request = request_type(**request_init) + # Mock the http request call within the method and 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.ListOperationsResponse() + + # 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterClient( + 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 = SecurityCenterAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), +]) +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 5989c64bbae8b073021e9c468df5a643455988a1 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 8 Aug 2024 20:10:02 +0000 Subject: [PATCH 4/4] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../v1/.coveragerc | 13 - .../google-cloud-securitycenter/v1/.flake8 | 33 - .../v1/MANIFEST.in | 2 - .../google-cloud-securitycenter/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../v1/docs/conf.py | 376 - .../v1/docs/index.rst | 7 - .../securitycenter_v1/security_center.rst | 10 - .../v1/docs/securitycenter_v1/services_.rst | 6 - .../v1/docs/securitycenter_v1/types_.rst | 6 - .../google/cloud/securitycenter/__init__.py | 343 - .../cloud/securitycenter/gapic_version.py | 16 - .../v1/google/cloud/securitycenter/py.typed | 2 - .../cloud/securitycenter_v1/__init__.py | 344 - .../securitycenter_v1/gapic_metadata.json | 973 - .../cloud/securitycenter_v1/gapic_version.py | 16 - .../google/cloud/securitycenter_v1/py.typed | 2 - .../securitycenter_v1/services/__init__.py | 15 - .../services/security_center/__init__.py | 22 - .../services/security_center/async_client.py | 7965 --- .../services/security_center/client.py | 8455 --- .../services/security_center/pagers.py | 2333 - .../security_center/transports/__init__.py | 38 - .../security_center/transports/base.py | 1251 - .../security_center/transports/grpc.py | 2103 - .../transports/grpc_asyncio.py | 2583 - .../security_center/transports/rest.py | 8529 --- .../cloud/securitycenter_v1/types/__init__.py | 440 - .../cloud/securitycenter_v1/types/access.py | 193 - .../securitycenter_v1/types/application.py | 55 - .../cloud/securitycenter_v1/types/asset.py | 227 - .../types/attack_exposure.py | 113 - .../securitycenter_v1/types/attack_path.py | 223 - .../types/backup_disaster_recovery.py | 137 - .../types/bigquery_export.py | 135 - .../securitycenter_v1/types/cloud_armor.py | 217 - .../types/cloud_dlp_data_profile.py | 71 - .../types/cloud_dlp_inspection.py | 70 - .../securitycenter_v1/types/compliance.py | 61 - .../securitycenter_v1/types/connection.py | 97 - .../types/contact_details.py | 61 - .../securitycenter_v1/types/container.py | 80 - .../cloud/securitycenter_v1/types/database.py | 98 - ...ve_event_threat_detection_custom_module.py | 113 - ...security_health_analytics_custom_module.py | 104 - .../event_threat_detection_custom_module.py | 138 - ...tection_custom_module_validation_errors.py | 123 - .../securitycenter_v1/types/exfiltration.py | 96 - .../types/external_system.py | 180 - .../cloud/securitycenter_v1/types/file.py | 113 - .../cloud/securitycenter_v1/types/finding.py | 774 - .../cloud/securitycenter_v1/types/folder.py | 54 - .../types/group_membership.py | 65 - .../securitycenter_v1/types/iam_binding.py | 77 - .../securitycenter_v1/types/indicator.py | 186 - .../securitycenter_v1/types/kernel_rootkit.py | 107 - .../securitycenter_v1/types/kubernetes.py | 398 - .../cloud/securitycenter_v1/types/label.py | 54 - .../securitycenter_v1/types/load_balancer.py | 47 - .../securitycenter_v1/types/log_entry.py | 96 - .../securitycenter_v1/types/mitre_attack.py | 340 - .../securitycenter_v1/types/mute_config.py | 171 - .../cloud/securitycenter_v1/types/notebook.py | 72 - .../types/notification_config.py | 127 - .../types/notification_message.py | 70 - .../securitycenter_v1/types/org_policy.py | 47 - .../types/organization_settings.py | 123 - .../cloud/securitycenter_v1/types/process.py | 136 - .../cloud/securitycenter_v1/types/resource.py | 474 - .../types/resource_value_config.py | 189 - .../types/run_asset_discovery_response.py | 76 - ...security_health_analytics_custom_config.py | 173 - ...security_health_analytics_custom_module.py | 138 - .../securitycenter_v1/types/security_marks.py | 80 - .../types/security_posture.py | 128 - .../types/securitycenter_service.py | 3519 -- .../securitycenter_v1/types/simulation.py | 73 - .../cloud/securitycenter_v1/types/source.py | 88 - .../types/toxic_combination.py | 60 - .../types/valued_resource.py | 126 - .../securitycenter_v1/types/vulnerability.py | 546 - .../google-cloud-securitycenter/v1/mypy.ini | 3 - .../google-cloud-securitycenter/v1/noxfile.py | 280 - ...tch_create_resource_value_configs_async.py | 58 - ...atch_create_resource_value_configs_sync.py | 58 - ...ecurity_center_bulk_mute_findings_async.py | 56 - ...security_center_bulk_mute_findings_sync.py | 56 - ...ty_center_create_big_query_export_async.py | 53 - ...ity_center_create_big_query_export_sync.py | 53 - ...nt_threat_detection_custom_module_async.py | 52 - ...ent_threat_detection_custom_module_sync.py | 52 - ...ed_security_center_create_finding_async.py | 53 - ...ted_security_center_create_finding_sync.py | 53 - ...ecurity_center_create_mute_config_async.py | 57 - ...security_center_create_mute_config_sync.py | 57 - ...center_create_notification_config_async.py | 53 - ..._center_create_notification_config_sync.py | 53 - ...ty_health_analytics_custom_module_async.py | 52 - ...ity_health_analytics_custom_module_sync.py | 52 - ...ted_security_center_create_source_async.py | 52 - ...ated_security_center_create_source_sync.py | 52 - ...ty_center_delete_big_query_export_async.py | 50 - ...ity_center_delete_big_query_export_sync.py | 50 - ...nt_threat_detection_custom_module_async.py | 50 - ...ent_threat_detection_custom_module_sync.py | 50 - ...ecurity_center_delete_mute_config_async.py | 50 - ...security_center_delete_mute_config_sync.py | 50 - ...center_delete_notification_config_async.py | 50 - ..._center_delete_notification_config_sync.py | 50 - ...nter_delete_resource_value_config_async.py | 50 - ...enter_delete_resource_value_config_sync.py | 50 - ...ty_health_analytics_custom_module_async.py | 50 - ...ity_health_analytics_custom_module_sync.py | 50 - ...urity_center_get_big_query_export_async.py | 52 - ...curity_center_get_big_query_export_sync.py | 52 - ...nt_threat_detection_custom_module_async.py | 52 - ...ent_threat_detection_custom_module_sync.py | 52 - ...ty_health_analytics_custom_module_async.py | 52 - ...ity_health_analytics_custom_module_sync.py | 52 - ...nt_threat_detection_custom_module_async.py | 52 - ...ent_threat_detection_custom_module_sync.py | 52 - ...ed_security_center_get_iam_policy_async.py | 53 - ...ted_security_center_get_iam_policy_sync.py | 53 - ...d_security_center_get_mute_config_async.py | 52 - ...ed_security_center_get_mute_config_sync.py | 52 - ...ty_center_get_notification_config_async.py | 52 - ...ity_center_get_notification_config_sync.py | 52 - ..._center_get_organization_settings_async.py | 52 - ...y_center_get_organization_settings_sync.py | 52 - ..._center_get_resource_value_config_async.py | 52 - ...y_center_get_resource_value_config_sync.py | 52 - ...ty_health_analytics_custom_module_async.py | 52 - ...ity_health_analytics_custom_module_sync.py | 52 - ...ed_security_center_get_simulation_async.py | 52 - ...ted_security_center_get_simulation_sync.py | 52 - ...erated_security_center_get_source_async.py | 52 - ...nerated_security_center_get_source_sync.py | 52 - ...curity_center_get_valued_resource_async.py | 52 - ...ecurity_center_get_valued_resource_sync.py | 52 - ...ated_security_center_group_assets_async.py | 54 - ...rated_security_center_group_assets_sync.py | 54 - ...ed_security_center_group_findings_async.py | 54 - ...ted_security_center_group_findings_sync.py | 54 - ...rated_security_center_list_assets_async.py | 53 - ...erated_security_center_list_assets_sync.py | 53 - ...security_center_list_attack_paths_async.py | 53 - ..._security_center_list_attack_paths_sync.py | 53 - ...ity_center_list_big_query_exports_async.py | 53 - ...rity_center_list_big_query_exports_sync.py | 53 - ...t_threat_detection_custom_modules_async.py | 53 - ...nt_threat_detection_custom_modules_sync.py | 53 - ...y_health_analytics_custom_modules_async.py | 53 - ...ty_health_analytics_custom_modules_sync.py | 53 - ...t_threat_detection_custom_modules_async.py | 53 - ...nt_threat_detection_custom_modules_sync.py | 53 - ...y_health_analytics_custom_modules_async.py | 53 - ...ty_health_analytics_custom_modules_sync.py | 53 - ...t_threat_detection_custom_modules_async.py | 53 - ...nt_threat_detection_custom_modules_sync.py | 53 - ...ted_security_center_list_findings_async.py | 53 - ...ated_security_center_list_findings_sync.py | 53 - ...security_center_list_mute_configs_async.py | 53 - ..._security_center_list_mute_configs_sync.py | 53 - ..._center_list_notification_configs_async.py | 53 - ...y_center_list_notification_configs_sync.py | 53 - ...enter_list_resource_value_configs_async.py | 53 - ...center_list_resource_value_configs_sync.py | 53 - ...y_health_analytics_custom_modules_async.py | 53 - ...ty_health_analytics_custom_modules_sync.py | 53 - ...ated_security_center_list_sources_async.py | 53 - ...rated_security_center_list_sources_sync.py | 53 - ...rity_center_list_valued_resources_async.py | 53 - ...urity_center_list_valued_resources_sync.py | 53 - ...curity_center_run_asset_discovery_async.py | 56 - ...ecurity_center_run_asset_discovery_sync.py | 56 - ...security_center_set_finding_state_async.py | 53 - ..._security_center_set_finding_state_sync.py | 53 - ...ed_security_center_set_iam_policy_async.py | 53 - ...ted_security_center_set_iam_policy_sync.py | 53 - ...enerated_security_center_set_mute_async.py | 53 - ...generated_security_center_set_mute_sync.py | 53 - ...ty_health_analytics_custom_module_async.py | 56 - ...ity_health_analytics_custom_module_sync.py | 56 - ...urity_center_test_iam_permissions_async.py | 54 - ...curity_center_test_iam_permissions_sync.py | 54 - ...ty_center_update_big_query_export_async.py | 51 - ...ity_center_update_big_query_export_sync.py | 51 - ...nt_threat_detection_custom_module_async.py | 51 - ...ent_threat_detection_custom_module_sync.py | 51 - ...ity_center_update_external_system_async.py | 51 - ...rity_center_update_external_system_sync.py | 51 - ...ed_security_center_update_finding_async.py | 51 - ...ted_security_center_update_finding_sync.py | 51 - ...ecurity_center_update_mute_config_async.py | 55 - ...security_center_update_mute_config_sync.py | 55 - ...center_update_notification_config_async.py | 51 - ..._center_update_notification_config_sync.py | 51 - ...nter_update_organization_settings_async.py | 51 - ...enter_update_organization_settings_sync.py | 51 - ...nter_update_resource_value_config_async.py | 56 - ...enter_update_resource_value_config_sync.py | 56 - ...ty_health_analytics_custom_module_async.py | 51 - ...ity_health_analytics_custom_module_sync.py | 51 - ...rity_center_update_security_marks_async.py | 51 - ...urity_center_update_security_marks_sync.py | 51 - ...ted_security_center_update_source_async.py | 51 - ...ated_security_center_update_source_sync.py | 51 - ...nt_threat_detection_custom_module_async.py | 54 - ...ent_threat_detection_custom_module_sync.py | 54 - ...tadata_google.cloud.securitycenter.v1.json | 10298 ---- .../fixup_securitycenter_v1_keywords.py | 238 - .../google-cloud-securitycenter/v1/setup.py | 94 - .../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/securitycenter_v1/__init__.py | 16 - .../securitycenter_v1/test_security_center.py | 48271 ---------------- .../v1beta1/.coveragerc | 13 - .../v1beta1/.flake8 | 33 - .../v1beta1/MANIFEST.in | 2 - .../v1beta1/README.rst | 49 - .../v1beta1/docs/_static/custom.css | 3 - .../v1beta1/docs/conf.py | 376 - .../v1beta1/docs/index.rst | 7 - .../security_center.rst | 10 - .../docs/securitycenter_v1beta1/services_.rst | 6 - .../docs/securitycenter_v1beta1/types_.rst | 6 - .../google/cloud/securitycenter/__init__.py | 81 - .../cloud/securitycenter/gapic_version.py | 16 - .../google/cloud/securitycenter/py.typed | 2 - .../cloud/securitycenter_v1beta1/__init__.py | 82 - .../gapic_metadata.json | 298 - .../securitycenter_v1beta1/gapic_version.py | 16 - .../cloud/securitycenter_v1beta1/py.typed | 2 - .../services/__init__.py | 15 - .../services/security_center/__init__.py | 22 - .../services/security_center/async_client.py | 2364 - .../services/security_center/client.py | 2755 - .../services/security_center/pagers.py | 704 - .../security_center/transports/__init__.py | 38 - .../security_center/transports/base.py | 498 - .../security_center/transports/grpc.py | 760 - .../transports/grpc_asyncio.py | 945 - .../security_center/transports/rest.py | 2542 - .../securitycenter_v1beta1/types/__init__.py | 86 - .../securitycenter_v1beta1/types/asset.py | 155 - .../securitycenter_v1beta1/types/finding.py | 165 - .../types/organization_settings.py | 115 - .../types/run_asset_discovery_response.py | 76 - .../types/security_marks.py | 68 - .../types/securitycenter_service.py | 1053 - .../securitycenter_v1beta1/types/source.py | 77 - .../v1beta1/mypy.ini | 3 - .../v1beta1/noxfile.py | 280 - ...ed_security_center_create_finding_async.py | 53 - ...ted_security_center_create_finding_sync.py | 53 - ...ted_security_center_create_source_async.py | 52 - ...ated_security_center_create_source_sync.py | 52 - ...ed_security_center_get_iam_policy_async.py | 53 - ...ted_security_center_get_iam_policy_sync.py | 53 - ..._center_get_organization_settings_async.py | 52 - ...y_center_get_organization_settings_sync.py | 52 - ...erated_security_center_get_source_async.py | 52 - ...nerated_security_center_get_source_sync.py | 52 - ...ated_security_center_group_assets_async.py | 54 - ...rated_security_center_group_assets_sync.py | 54 - ...ed_security_center_group_findings_async.py | 54 - ...ted_security_center_group_findings_sync.py | 54 - ...rated_security_center_list_assets_async.py | 53 - ...erated_security_center_list_assets_sync.py | 53 - ...ted_security_center_list_findings_async.py | 53 - ...ated_security_center_list_findings_sync.py | 53 - ...ated_security_center_list_sources_async.py | 53 - ...rated_security_center_list_sources_sync.py | 53 - ...curity_center_run_asset_discovery_async.py | 56 - ...ecurity_center_run_asset_discovery_sync.py | 56 - ...security_center_set_finding_state_async.py | 53 - ..._security_center_set_finding_state_sync.py | 53 - ...ed_security_center_set_iam_policy_async.py | 53 - ...ted_security_center_set_iam_policy_sync.py | 53 - ...urity_center_test_iam_permissions_async.py | 54 - ...curity_center_test_iam_permissions_sync.py | 54 - ...ed_security_center_update_finding_async.py | 51 - ...ted_security_center_update_finding_sync.py | 51 - ...nter_update_organization_settings_async.py | 51 - ...enter_update_organization_settings_sync.py | 51 - ...rity_center_update_security_marks_async.py | 51 - ...urity_center_update_security_marks_sync.py | 51 - ...ted_security_center_update_source_async.py | 51 - ...ated_security_center_update_source_sync.py | 51 - ...a_google.cloud.securitycenter.v1beta1.json | 2945 - .../fixup_securitycenter_v1beta1_keywords.py | 193 - .../v1beta1/setup.py | 94 - .../v1beta1/testing/constraints-3.10.txt | 7 - .../v1beta1/testing/constraints-3.11.txt | 7 - .../v1beta1/testing/constraints-3.12.txt | 7 - .../v1beta1/testing/constraints-3.7.txt | 11 - .../v1beta1/testing/constraints-3.8.txt | 7 - .../v1beta1/testing/constraints-3.9.txt | 7 - .../v1beta1/tests/__init__.py | 16 - .../v1beta1/tests/unit/__init__.py | 16 - .../v1beta1/tests/unit/gapic/__init__.py | 16 - .../gapic/securitycenter_v1beta1/__init__.py | 16 - .../test_security_center.py | 14372 ----- .../v1p1beta1/.coveragerc | 13 - .../v1p1beta1/.flake8 | 33 - .../v1p1beta1/MANIFEST.in | 2 - .../v1p1beta1/README.rst | 49 - .../v1p1beta1/docs/_static/custom.css | 3 - .../v1p1beta1/docs/conf.py | 376 - .../v1p1beta1/docs/index.rst | 7 - .../security_center.rst | 10 - .../securitycenter_v1p1beta1/services_.rst | 6 - .../docs/securitycenter_v1p1beta1/types_.rst | 6 - .../google/cloud/securitycenter/__init__.py | 101 - .../cloud/securitycenter/gapic_version.py | 16 - .../google/cloud/securitycenter/py.typed | 2 - .../securitycenter_v1p1beta1/__init__.py | 102 - .../gapic_metadata.json | 373 - .../securitycenter_v1p1beta1/gapic_version.py | 16 - .../cloud/securitycenter_v1p1beta1/py.typed | 2 - .../services/__init__.py | 15 - .../services/security_center/__init__.py | 22 - .../services/security_center/async_client.py | 3039 - .../services/security_center/client.py | 3441 -- .../services/security_center/pagers.py | 839 - .../security_center/transports/__init__.py | 38 - .../security_center/transports/base.py | 591 - .../security_center/transports/grpc.py | 895 - .../transports/grpc_asyncio.py | 1125 - .../security_center/transports/rest.py | 3197 - .../types/__init__.py | 114 - .../securitycenter_v1p1beta1/types/asset.py | 227 - .../securitycenter_v1p1beta1/types/finding.py | 209 - .../securitycenter_v1p1beta1/types/folder.py | 54 - .../types/notification_config.py | 143 - .../types/notification_message.py | 69 - .../types/organization_settings.py | 123 - .../types/resource.py | 85 - .../types/run_asset_discovery_response.py | 76 - .../types/security_marks.py | 80 - .../types/securitycenter_service.py | 1641 - .../securitycenter_v1p1beta1/types/source.py | 88 - .../v1p1beta1/mypy.ini | 3 - .../v1p1beta1/noxfile.py | 280 - ...ed_security_center_create_finding_async.py | 53 - ...ted_security_center_create_finding_sync.py | 53 - ...center_create_notification_config_async.py | 53 - ..._center_create_notification_config_sync.py | 53 - ...ted_security_center_create_source_async.py | 52 - ...ated_security_center_create_source_sync.py | 52 - ...center_delete_notification_config_async.py | 50 - ..._center_delete_notification_config_sync.py | 50 - ...ed_security_center_get_iam_policy_async.py | 53 - ...ted_security_center_get_iam_policy_sync.py | 53 - ...ty_center_get_notification_config_async.py | 52 - ...ity_center_get_notification_config_sync.py | 52 - ..._center_get_organization_settings_async.py | 52 - ...y_center_get_organization_settings_sync.py | 52 - ...erated_security_center_get_source_async.py | 52 - ...nerated_security_center_get_source_sync.py | 52 - ...ated_security_center_group_assets_async.py | 54 - ...rated_security_center_group_assets_sync.py | 54 - ...ed_security_center_group_findings_async.py | 54 - ...ted_security_center_group_findings_sync.py | 54 - ...rated_security_center_list_assets_async.py | 53 - ...erated_security_center_list_assets_sync.py | 53 - ...ted_security_center_list_findings_async.py | 53 - ...ated_security_center_list_findings_sync.py | 53 - ..._center_list_notification_configs_async.py | 53 - ...y_center_list_notification_configs_sync.py | 53 - ...ated_security_center_list_sources_async.py | 53 - ...rated_security_center_list_sources_sync.py | 53 - ...curity_center_run_asset_discovery_async.py | 56 - ...ecurity_center_run_asset_discovery_sync.py | 56 - ...security_center_set_finding_state_async.py | 53 - ..._security_center_set_finding_state_sync.py | 53 - ...ed_security_center_set_iam_policy_async.py | 53 - ...ted_security_center_set_iam_policy_sync.py | 53 - ...urity_center_test_iam_permissions_async.py | 54 - ...curity_center_test_iam_permissions_sync.py | 54 - ...ed_security_center_update_finding_async.py | 51 - ...ted_security_center_update_finding_sync.py | 51 - ...center_update_notification_config_async.py | 51 - ..._center_update_notification_config_sync.py | 51 - ...nter_update_organization_settings_async.py | 51 - ...enter_update_organization_settings_sync.py | 51 - ...rity_center_update_security_marks_async.py | 51 - ...urity_center_update_security_marks_sync.py | 51 - ...ted_security_center_update_source_async.py | 51 - ...ated_security_center_update_source_sync.py | 51 - ...google.cloud.securitycenter.v1p1beta1.json | 3808 -- ...fixup_securitycenter_v1p1beta1_keywords.py | 198 - .../v1p1beta1/setup.py | 94 - .../v1p1beta1/testing/constraints-3.10.txt | 7 - .../v1p1beta1/testing/constraints-3.11.txt | 7 - .../v1p1beta1/testing/constraints-3.12.txt | 7 - .../v1p1beta1/testing/constraints-3.7.txt | 11 - .../v1p1beta1/testing/constraints-3.8.txt | 7 - .../v1p1beta1/testing/constraints-3.9.txt | 7 - .../v1p1beta1/tests/__init__.py | 16 - .../v1p1beta1/tests/unit/__init__.py | 16 - .../v1p1beta1/tests/unit/gapic/__init__.py | 16 - .../securitycenter_v1p1beta1/__init__.py | 16 - .../test_security_center.py | 18405 ------ .../v2/.coveragerc | 13 - .../google-cloud-securitycenter/v2/.flake8 | 33 - .../v2/MANIFEST.in | 2 - .../google-cloud-securitycenter/v2/README.rst | 49 - .../v2/docs/_static/custom.css | 3 - .../v2/docs/conf.py | 376 - .../v2/docs/index.rst | 7 - .../securitycenter_v2/security_center.rst | 10 - .../v2/docs/securitycenter_v2/services_.rst | 6 - .../v2/docs/securitycenter_v2/types_.rst | 6 - .../google/cloud/securitycenter/__init__.py | 257 - .../cloud/securitycenter/gapic_version.py | 16 - .../v2/google/cloud/securitycenter/py.typed | 2 - .../cloud/securitycenter_v2/__init__.py | 258 - .../securitycenter_v2/gapic_metadata.json | 628 - .../cloud/securitycenter_v2/gapic_version.py | 16 - .../google/cloud/securitycenter_v2/py.typed | 2 - .../securitycenter_v2/services/__init__.py | 15 - .../services/security_center/__init__.py | 22 - .../services/security_center/async_client.py | 5422 -- .../services/security_center/client.py | 5948 -- .../services/security_center/pagers.py | 1249 - .../security_center/transports/__init__.py | 38 - .../security_center/transports/base.py | 761 - .../security_center/transports/grpc.py | 1452 - .../transports/grpc_asyncio.py | 1657 - .../security_center/transports/rest.py | 5820 -- .../cloud/securitycenter_v2/types/__init__.py | 336 - .../cloud/securitycenter_v2/types/access.py | 193 - .../securitycenter_v2/types/application.py | 55 - .../types/attack_exposure.py | 113 - .../securitycenter_v2/types/attack_path.py | 223 - .../types/backup_disaster_recovery.py | 137 - .../types/bigquery_export.py | 141 - .../securitycenter_v2/types/cloud_armor.py | 217 - .../types/cloud_dlp_data_profile.py | 71 - .../types/cloud_dlp_inspection.py | 70 - .../securitycenter_v2/types/compliance.py | 61 - .../securitycenter_v2/types/connection.py | 97 - .../types/contact_details.py | 61 - .../securitycenter_v2/types/container.py | 80 - .../cloud/securitycenter_v2/types/database.py | 98 - .../securitycenter_v2/types/exfiltration.py | 96 - .../types/external_system.py | 192 - .../cloud/securitycenter_v2/types/file.py | 113 - .../cloud/securitycenter_v2/types/finding.py | 808 - .../cloud/securitycenter_v2/types/folder.py | 54 - .../types/group_membership.py | 65 - .../securitycenter_v2/types/iam_binding.py | 77 - .../securitycenter_v2/types/indicator.py | 186 - .../securitycenter_v2/types/kernel_rootkit.py | 107 - .../securitycenter_v2/types/kubernetes.py | 398 - .../cloud/securitycenter_v2/types/label.py | 54 - .../securitycenter_v2/types/load_balancer.py | 47 - .../securitycenter_v2/types/log_entry.py | 95 - .../securitycenter_v2/types/mitre_attack.py | 340 - .../securitycenter_v2/types/mute_config.py | 166 - .../cloud/securitycenter_v2/types/notebook.py | 72 - .../types/notification_config.py | 129 - .../types/notification_message.py | 70 - .../securitycenter_v2/types/org_policy.py | 47 - .../cloud/securitycenter_v2/types/process.py | 136 - .../cloud/securitycenter_v2/types/resource.py | 493 - .../types/resource_value_config.py | 190 - .../securitycenter_v2/types/security_marks.py | 101 - .../types/security_posture.py | 128 - .../types/securitycenter_service.py | 1932 - .../securitycenter_v2/types/simulation.py | 73 - .../cloud/securitycenter_v2/types/source.py | 88 - .../types/toxic_combination.py | 60 - .../types/valued_resource.py | 126 - .../securitycenter_v2/types/vulnerability.py | 546 - .../google-cloud-securitycenter/v2/mypy.ini | 3 - .../google-cloud-securitycenter/v2/noxfile.py | 280 - ...tch_create_resource_value_configs_async.py | 56 - ...atch_create_resource_value_configs_sync.py | 56 - ...ecurity_center_bulk_mute_findings_async.py | 56 - ...security_center_bulk_mute_findings_sync.py | 56 - ...ty_center_create_big_query_export_async.py | 53 - ...ity_center_create_big_query_export_sync.py | 53 - ...ed_security_center_create_finding_async.py | 53 - ...ted_security_center_create_finding_sync.py | 53 - ...ecurity_center_create_mute_config_async.py | 58 - ...security_center_create_mute_config_sync.py | 58 - ...center_create_notification_config_async.py | 53 - ..._center_create_notification_config_sync.py | 53 - ...ted_security_center_create_source_async.py | 52 - ...ated_security_center_create_source_sync.py | 52 - ...ty_center_delete_big_query_export_async.py | 50 - ...ity_center_delete_big_query_export_sync.py | 50 - ...ecurity_center_delete_mute_config_async.py | 50 - ...security_center_delete_mute_config_sync.py | 50 - ...center_delete_notification_config_async.py | 50 - ..._center_delete_notification_config_sync.py | 50 - ...nter_delete_resource_value_config_async.py | 50 - ...enter_delete_resource_value_config_sync.py | 50 - ...urity_center_get_big_query_export_async.py | 52 - ...curity_center_get_big_query_export_sync.py | 52 - ...ed_security_center_get_iam_policy_async.py | 53 - ...ted_security_center_get_iam_policy_sync.py | 53 - ...d_security_center_get_mute_config_async.py | 52 - ...ed_security_center_get_mute_config_sync.py | 52 - ...ty_center_get_notification_config_async.py | 52 - ...ity_center_get_notification_config_sync.py | 52 - ..._center_get_resource_value_config_async.py | 52 - ...y_center_get_resource_value_config_sync.py | 52 - ...ed_security_center_get_simulation_async.py | 52 - ...ted_security_center_get_simulation_sync.py | 52 - ...erated_security_center_get_source_async.py | 52 - ...nerated_security_center_get_source_sync.py | 52 - ...curity_center_get_valued_resource_async.py | 52 - ...ecurity_center_get_valued_resource_sync.py | 52 - ...ed_security_center_group_findings_async.py | 54 - ...ted_security_center_group_findings_sync.py | 54 - ...security_center_list_attack_paths_async.py | 53 - ..._security_center_list_attack_paths_sync.py | 53 - ...ity_center_list_big_query_exports_async.py | 53 - ...rity_center_list_big_query_exports_sync.py | 53 - ...ted_security_center_list_findings_async.py | 53 - ...ated_security_center_list_findings_sync.py | 53 - ...security_center_list_mute_configs_async.py | 53 - ..._security_center_list_mute_configs_sync.py | 53 - ..._center_list_notification_configs_async.py | 53 - ...y_center_list_notification_configs_sync.py | 53 - ...enter_list_resource_value_configs_async.py | 53 - ...center_list_resource_value_configs_sync.py | 53 - ...ated_security_center_list_sources_async.py | 53 - ...rated_security_center_list_sources_sync.py | 53 - ...rity_center_list_valued_resources_async.py | 53 - ...urity_center_list_valued_resources_sync.py | 53 - ...security_center_set_finding_state_async.py | 53 - ..._security_center_set_finding_state_sync.py | 53 - ...ed_security_center_set_iam_policy_async.py | 53 - ...ted_security_center_set_iam_policy_sync.py | 53 - ...enerated_security_center_set_mute_async.py | 53 - ...generated_security_center_set_mute_sync.py | 53 - ...urity_center_test_iam_permissions_async.py | 54 - ...curity_center_test_iam_permissions_sync.py | 54 - ...ty_center_update_big_query_export_async.py | 51 - ...ity_center_update_big_query_export_sync.py | 51 - ...ity_center_update_external_system_async.py | 51 - ...rity_center_update_external_system_sync.py | 51 - ...ed_security_center_update_finding_async.py | 51 - ...ted_security_center_update_finding_sync.py | 51 - ...ecurity_center_update_mute_config_async.py | 56 - ...security_center_update_mute_config_sync.py | 56 - ...center_update_notification_config_async.py | 51 - ..._center_update_notification_config_sync.py | 51 - ...nter_update_resource_value_config_async.py | 51 - ...enter_update_resource_value_config_sync.py | 51 - ...rity_center_update_security_marks_async.py | 51 - ...urity_center_update_security_marks_sync.py | 51 - ...ted_security_center_update_source_async.py | 51 - ...ated_security_center_update_source_sync.py | 51 - ...tadata_google.cloud.securitycenter.v2.json | 6607 --- .../fixup_securitycenter_v2_keywords.py | 215 - .../google-cloud-securitycenter/v2/setup.py | 94 - .../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 - .../v2/tests/__init__.py | 16 - .../v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/securitycenter_v2/__init__.py | 16 - .../securitycenter_v2/test_security_center.py | 31716 ---------- .../services/security_center/async_client.py | 6 +- .../services/security_center/client.py | 6 +- .../cloud/securitycenter_v1/types/finding.py | 85 + .../securitycenter_v1/types/mitre_attack.py | 8 +- .../securitycenter_v1/types/mute_config.py | 49 + .../types/securitycenter_service.py | 34 +- .../securitycenter_v1/types/vulnerability.py | 8 + .../fixup_securitycenter_v1_keywords.py | 2 +- .../securitycenter_v1/test_security_center.py | 39 + 588 files changed, 225 insertions(+), 265306 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/setup.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/setup.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/.flake8 delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/README.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/setup.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/__init__.py delete mode 100644 owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc deleted file mode 100644 index 45cb273f8f7c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/securitycenter/__init__.py - google/cloud/securitycenter/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-securitycenter/v1/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v1/MANIFEST.in deleted file mode 100644 index a18e3d0b6821..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/securitycenter *.py -recursive-include google/cloud/securitycenter_v1 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/README.rst b/owl-bot-staging/google-cloud-securitycenter/v1/README.rst deleted file mode 100644 index f8c63f4cb48a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v1/docs/conf.py deleted file mode 100644 index 8e92d2319721..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter 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-securitycenter" -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-securitycenter-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-securitycenter.tex", - u"google-cloud-securitycenter 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-securitycenter", - u"Google Cloud Securitycenter 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-securitycenter", - u"google-cloud-securitycenter Documentation", - author, - "google-cloud-securitycenter", - "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v1/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/index.rst deleted file mode 100644 index 47fc2db7cc98..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - securitycenter_v1/services - securitycenter_v1/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst deleted file mode 100644 index bc6175c8b5cc..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/security_center.rst +++ /dev/null @@ -1,10 +0,0 @@ -SecurityCenter --------------------------------- - -.. automodule:: google.cloud.securitycenter_v1.services.security_center - :members: - :inherited-members: - -.. automodule:: google.cloud.securitycenter_v1.services.security_center.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst deleted file mode 100644 index 295acede4385..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Securitycenter v1 API -=============================================== -.. toctree:: - :maxdepth: 2 - - security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst deleted file mode 100644 index f7497757d041..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/docs/securitycenter_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Securitycenter v1 API -============================================ - -.. automodule:: google.cloud.securitycenter_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.py deleted file mode 100644 index 7c15b78219eb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/__init__.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. -# -from google.cloud.securitycenter import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.securitycenter_v1.services.security_center.client import SecurityCenterClient -from google.cloud.securitycenter_v1.services.security_center.async_client import SecurityCenterAsyncClient - -from google.cloud.securitycenter_v1.types.access import Access -from google.cloud.securitycenter_v1.types.access import Geolocation -from google.cloud.securitycenter_v1.types.access import ServiceAccountDelegationInfo -from google.cloud.securitycenter_v1.types.application import Application -from google.cloud.securitycenter_v1.types.asset import Asset -from google.cloud.securitycenter_v1.types.attack_exposure import AttackExposure -from google.cloud.securitycenter_v1.types.attack_path import AttackPath -from google.cloud.securitycenter_v1.types.backup_disaster_recovery import BackupDisasterRecovery -from google.cloud.securitycenter_v1.types.bigquery_export import BigQueryExport -from google.cloud.securitycenter_v1.types.cloud_armor import AdaptiveProtection -from google.cloud.securitycenter_v1.types.cloud_armor import Attack -from google.cloud.securitycenter_v1.types.cloud_armor import CloudArmor -from google.cloud.securitycenter_v1.types.cloud_armor import Requests -from google.cloud.securitycenter_v1.types.cloud_armor import SecurityPolicy -from google.cloud.securitycenter_v1.types.cloud_dlp_data_profile import CloudDlpDataProfile -from google.cloud.securitycenter_v1.types.cloud_dlp_inspection import CloudDlpInspection -from google.cloud.securitycenter_v1.types.compliance import Compliance -from google.cloud.securitycenter_v1.types.connection import Connection -from google.cloud.securitycenter_v1.types.contact_details import Contact -from google.cloud.securitycenter_v1.types.contact_details import ContactDetails -from google.cloud.securitycenter_v1.types.container import Container -from google.cloud.securitycenter_v1.types.database import Database -from google.cloud.securitycenter_v1.types.effective_event_threat_detection_custom_module import EffectiveEventThreatDetectionCustomModule -from google.cloud.securitycenter_v1.types.effective_security_health_analytics_custom_module import EffectiveSecurityHealthAnalyticsCustomModule -from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module import EventThreatDetectionCustomModule -from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationError -from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationErrors -from google.cloud.securitycenter_v1.types.event_threat_detection_custom_module_validation_errors import Position -from google.cloud.securitycenter_v1.types.exfiltration import ExfilResource -from google.cloud.securitycenter_v1.types.exfiltration import Exfiltration -from google.cloud.securitycenter_v1.types.external_system import ExternalSystem -from google.cloud.securitycenter_v1.types.file import File -from google.cloud.securitycenter_v1.types.finding import Finding -from google.cloud.securitycenter_v1.types.folder import Folder -from google.cloud.securitycenter_v1.types.group_membership import GroupMembership -from google.cloud.securitycenter_v1.types.iam_binding import IamBinding -from google.cloud.securitycenter_v1.types.indicator import Indicator -from google.cloud.securitycenter_v1.types.kernel_rootkit import KernelRootkit -from google.cloud.securitycenter_v1.types.kubernetes import Kubernetes -from google.cloud.securitycenter_v1.types.label import Label -from google.cloud.securitycenter_v1.types.load_balancer import LoadBalancer -from google.cloud.securitycenter_v1.types.log_entry import CloudLoggingEntry -from google.cloud.securitycenter_v1.types.log_entry import LogEntry -from google.cloud.securitycenter_v1.types.mitre_attack import MitreAttack -from google.cloud.securitycenter_v1.types.mute_config import MuteConfig -from google.cloud.securitycenter_v1.types.notebook import Notebook -from google.cloud.securitycenter_v1.types.notification_config import NotificationConfig -from google.cloud.securitycenter_v1.types.notification_message import NotificationMessage -from google.cloud.securitycenter_v1.types.org_policy import OrgPolicy -from google.cloud.securitycenter_v1.types.organization_settings import OrganizationSettings -from google.cloud.securitycenter_v1.types.process import EnvironmentVariable -from google.cloud.securitycenter_v1.types.process import Process -from google.cloud.securitycenter_v1.types.resource import AwsMetadata -from google.cloud.securitycenter_v1.types.resource import AzureMetadata -from google.cloud.securitycenter_v1.types.resource import Resource -from google.cloud.securitycenter_v1.types.resource import ResourcePath -from google.cloud.securitycenter_v1.types.resource import CloudProvider -from google.cloud.securitycenter_v1.types.resource_value_config import ResourceValueConfig -from google.cloud.securitycenter_v1.types.resource_value_config import ResourceValue -from google.cloud.securitycenter_v1.types.run_asset_discovery_response import RunAssetDiscoveryResponse -from google.cloud.securitycenter_v1.types.security_health_analytics_custom_config import CustomConfig -from google.cloud.securitycenter_v1.types.security_health_analytics_custom_module import SecurityHealthAnalyticsCustomModule -from google.cloud.securitycenter_v1.types.security_marks import SecurityMarks -from google.cloud.securitycenter_v1.types.security_posture import SecurityPosture -from google.cloud.securitycenter_v1.types.securitycenter_service import BatchCreateResourceValueConfigsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import BatchCreateResourceValueConfigsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import BulkMuteFindingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import BulkMuteFindingsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateBigQueryExportRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateEventThreatDetectionCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateFindingRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateMuteConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateNotificationConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateResourceValueConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateSecurityHealthAnalyticsCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateSourceRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteBigQueryExportRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteEventThreatDetectionCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteMuteConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteNotificationConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteResourceValueConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteSecurityHealthAnalyticsCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetBigQueryExportRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetEffectiveEventThreatDetectionCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetEffectiveSecurityHealthAnalyticsCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetEventThreatDetectionCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetMuteConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetNotificationConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetOrganizationSettingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetResourceValueConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetSecurityHealthAnalyticsCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetSimulationRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetSourceRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetValuedResourceRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupAssetsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupAssetsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupFindingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupFindingsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupResult -from google.cloud.securitycenter_v1.types.securitycenter_service import ListAssetsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListAssetsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListAttackPathsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListAttackPathsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListBigQueryExportsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListBigQueryExportsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListEventThreatDetectionCustomModulesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListEventThreatDetectionCustomModulesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListFindingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListFindingsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListMuteConfigsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListMuteConfigsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListNotificationConfigsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListNotificationConfigsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListResourceValueConfigsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListResourceValueConfigsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListSourcesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListSourcesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListValuedResourcesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListValuedResourcesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import RunAssetDiscoveryRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import SetFindingStateRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import SetMuteRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateBigQueryExportRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateEventThreatDetectionCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateExternalSystemRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateFindingRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateMuteConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateNotificationConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateOrganizationSettingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateResourceValueConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSecurityHealthAnalyticsCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSecurityMarksRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSourceRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ValidateEventThreatDetectionCustomModuleRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ValidateEventThreatDetectionCustomModuleResponse -from google.cloud.securitycenter_v1.types.simulation import Simulation -from google.cloud.securitycenter_v1.types.source import Source -from google.cloud.securitycenter_v1.types.toxic_combination import ToxicCombination -from google.cloud.securitycenter_v1.types.valued_resource import ResourceValueConfigMetadata -from google.cloud.securitycenter_v1.types.valued_resource import ValuedResource -from google.cloud.securitycenter_v1.types.vulnerability import Cve -from google.cloud.securitycenter_v1.types.vulnerability import Cvssv3 -from google.cloud.securitycenter_v1.types.vulnerability import Package -from google.cloud.securitycenter_v1.types.vulnerability import Reference -from google.cloud.securitycenter_v1.types.vulnerability import SecurityBulletin -from google.cloud.securitycenter_v1.types.vulnerability import Vulnerability - -__all__ = ('SecurityCenterClient', - 'SecurityCenterAsyncClient', - 'Access', - 'Geolocation', - 'ServiceAccountDelegationInfo', - 'Application', - 'Asset', - 'AttackExposure', - 'AttackPath', - 'BackupDisasterRecovery', - 'BigQueryExport', - 'AdaptiveProtection', - 'Attack', - 'CloudArmor', - 'Requests', - 'SecurityPolicy', - 'CloudDlpDataProfile', - 'CloudDlpInspection', - 'Compliance', - 'Connection', - 'Contact', - 'ContactDetails', - 'Container', - 'Database', - 'EffectiveEventThreatDetectionCustomModule', - 'EffectiveSecurityHealthAnalyticsCustomModule', - 'EventThreatDetectionCustomModule', - 'CustomModuleValidationError', - 'CustomModuleValidationErrors', - 'Position', - 'ExfilResource', - 'Exfiltration', - 'ExternalSystem', - 'File', - 'Finding', - 'Folder', - 'GroupMembership', - 'IamBinding', - 'Indicator', - 'KernelRootkit', - 'Kubernetes', - 'Label', - 'LoadBalancer', - 'CloudLoggingEntry', - 'LogEntry', - 'MitreAttack', - 'MuteConfig', - 'Notebook', - 'NotificationConfig', - 'NotificationMessage', - 'OrgPolicy', - 'OrganizationSettings', - 'EnvironmentVariable', - 'Process', - 'AwsMetadata', - 'AzureMetadata', - 'Resource', - 'ResourcePath', - 'CloudProvider', - 'ResourceValueConfig', - 'ResourceValue', - 'RunAssetDiscoveryResponse', - 'CustomConfig', - 'SecurityHealthAnalyticsCustomModule', - 'SecurityMarks', - 'SecurityPosture', - 'BatchCreateResourceValueConfigsRequest', - 'BatchCreateResourceValueConfigsResponse', - 'BulkMuteFindingsRequest', - 'BulkMuteFindingsResponse', - 'CreateBigQueryExportRequest', - 'CreateEventThreatDetectionCustomModuleRequest', - 'CreateFindingRequest', - 'CreateMuteConfigRequest', - 'CreateNotificationConfigRequest', - 'CreateResourceValueConfigRequest', - 'CreateSecurityHealthAnalyticsCustomModuleRequest', - 'CreateSourceRequest', - 'DeleteBigQueryExportRequest', - 'DeleteEventThreatDetectionCustomModuleRequest', - 'DeleteMuteConfigRequest', - 'DeleteNotificationConfigRequest', - 'DeleteResourceValueConfigRequest', - 'DeleteSecurityHealthAnalyticsCustomModuleRequest', - 'GetBigQueryExportRequest', - 'GetEffectiveEventThreatDetectionCustomModuleRequest', - 'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', - 'GetEventThreatDetectionCustomModuleRequest', - 'GetMuteConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetResourceValueConfigRequest', - 'GetSecurityHealthAnalyticsCustomModuleRequest', - 'GetSimulationRequest', - 'GetSourceRequest', - 'GetValuedResourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListAttackPathsRequest', - 'ListAttackPathsResponse', - 'ListBigQueryExportsRequest', - 'ListBigQueryExportsResponse', - 'ListDescendantEventThreatDetectionCustomModulesRequest', - 'ListDescendantEventThreatDetectionCustomModulesResponse', - 'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', - 'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', - 'ListEffectiveEventThreatDetectionCustomModulesRequest', - 'ListEffectiveEventThreatDetectionCustomModulesResponse', - 'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', - 'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', - 'ListEventThreatDetectionCustomModulesRequest', - 'ListEventThreatDetectionCustomModulesResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListMuteConfigsRequest', - 'ListMuteConfigsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListResourceValueConfigsRequest', - 'ListResourceValueConfigsResponse', - 'ListSecurityHealthAnalyticsCustomModulesRequest', - 'ListSecurityHealthAnalyticsCustomModulesResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListValuedResourcesRequest', - 'ListValuedResourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'SetMuteRequest', - 'SimulateSecurityHealthAnalyticsCustomModuleRequest', - 'SimulateSecurityHealthAnalyticsCustomModuleResponse', - 'UpdateBigQueryExportRequest', - 'UpdateEventThreatDetectionCustomModuleRequest', - 'UpdateExternalSystemRequest', - 'UpdateFindingRequest', - 'UpdateMuteConfigRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateResourceValueConfigRequest', - 'UpdateSecurityHealthAnalyticsCustomModuleRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'ValidateEventThreatDetectionCustomModuleRequest', - 'ValidateEventThreatDetectionCustomModuleResponse', - 'Simulation', - 'Source', - 'ToxicCombination', - 'ResourceValueConfigMetadata', - 'ValuedResource', - 'Cve', - 'Cvssv3', - 'Package', - 'Reference', - 'SecurityBulletin', - 'Vulnerability', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/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-securitycenter/v1/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.py deleted file mode 100644 index ac4fb60e1479..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/__init__.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. -# -from google.cloud.securitycenter_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.security_center import SecurityCenterClient -from .services.security_center import SecurityCenterAsyncClient - -from .types.access import Access -from .types.access import Geolocation -from .types.access import ServiceAccountDelegationInfo -from .types.application import Application -from .types.asset import Asset -from .types.attack_exposure import AttackExposure -from .types.attack_path import AttackPath -from .types.backup_disaster_recovery import BackupDisasterRecovery -from .types.bigquery_export import BigQueryExport -from .types.cloud_armor import AdaptiveProtection -from .types.cloud_armor import Attack -from .types.cloud_armor import CloudArmor -from .types.cloud_armor import Requests -from .types.cloud_armor import SecurityPolicy -from .types.cloud_dlp_data_profile import CloudDlpDataProfile -from .types.cloud_dlp_inspection import CloudDlpInspection -from .types.compliance import Compliance -from .types.connection import Connection -from .types.contact_details import Contact -from .types.contact_details import ContactDetails -from .types.container import Container -from .types.database import Database -from .types.effective_event_threat_detection_custom_module import EffectiveEventThreatDetectionCustomModule -from .types.effective_security_health_analytics_custom_module import EffectiveSecurityHealthAnalyticsCustomModule -from .types.event_threat_detection_custom_module import EventThreatDetectionCustomModule -from .types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationError -from .types.event_threat_detection_custom_module_validation_errors import CustomModuleValidationErrors -from .types.event_threat_detection_custom_module_validation_errors import Position -from .types.exfiltration import ExfilResource -from .types.exfiltration import Exfiltration -from .types.external_system import ExternalSystem -from .types.file import File -from .types.finding import Finding -from .types.folder import Folder -from .types.group_membership import GroupMembership -from .types.iam_binding import IamBinding -from .types.indicator import Indicator -from .types.kernel_rootkit import KernelRootkit -from .types.kubernetes import Kubernetes -from .types.label import Label -from .types.load_balancer import LoadBalancer -from .types.log_entry import CloudLoggingEntry -from .types.log_entry import LogEntry -from .types.mitre_attack import MitreAttack -from .types.mute_config import MuteConfig -from .types.notebook import Notebook -from .types.notification_config import NotificationConfig -from .types.notification_message import NotificationMessage -from .types.org_policy import OrgPolicy -from .types.organization_settings import OrganizationSettings -from .types.process import EnvironmentVariable -from .types.process import Process -from .types.resource import AwsMetadata -from .types.resource import AzureMetadata -from .types.resource import Resource -from .types.resource import ResourcePath -from .types.resource import CloudProvider -from .types.resource_value_config import ResourceValueConfig -from .types.resource_value_config import ResourceValue -from .types.run_asset_discovery_response import RunAssetDiscoveryResponse -from .types.security_health_analytics_custom_config import CustomConfig -from .types.security_health_analytics_custom_module import SecurityHealthAnalyticsCustomModule -from .types.security_marks import SecurityMarks -from .types.security_posture import SecurityPosture -from .types.securitycenter_service import BatchCreateResourceValueConfigsRequest -from .types.securitycenter_service import BatchCreateResourceValueConfigsResponse -from .types.securitycenter_service import BulkMuteFindingsRequest -from .types.securitycenter_service import BulkMuteFindingsResponse -from .types.securitycenter_service import CreateBigQueryExportRequest -from .types.securitycenter_service import CreateEventThreatDetectionCustomModuleRequest -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateMuteConfigRequest -from .types.securitycenter_service import CreateNotificationConfigRequest -from .types.securitycenter_service import CreateResourceValueConfigRequest -from .types.securitycenter_service import CreateSecurityHealthAnalyticsCustomModuleRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import DeleteBigQueryExportRequest -from .types.securitycenter_service import DeleteEventThreatDetectionCustomModuleRequest -from .types.securitycenter_service import DeleteMuteConfigRequest -from .types.securitycenter_service import DeleteNotificationConfigRequest -from .types.securitycenter_service import DeleteResourceValueConfigRequest -from .types.securitycenter_service import DeleteSecurityHealthAnalyticsCustomModuleRequest -from .types.securitycenter_service import GetBigQueryExportRequest -from .types.securitycenter_service import GetEffectiveEventThreatDetectionCustomModuleRequest -from .types.securitycenter_service import GetEffectiveSecurityHealthAnalyticsCustomModuleRequest -from .types.securitycenter_service import GetEventThreatDetectionCustomModuleRequest -from .types.securitycenter_service import GetMuteConfigRequest -from .types.securitycenter_service import GetNotificationConfigRequest -from .types.securitycenter_service import GetOrganizationSettingsRequest -from .types.securitycenter_service import GetResourceValueConfigRequest -from .types.securitycenter_service import GetSecurityHealthAnalyticsCustomModuleRequest -from .types.securitycenter_service import GetSimulationRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GetValuedResourceRequest -from .types.securitycenter_service import GroupAssetsRequest -from .types.securitycenter_service import GroupAssetsResponse -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAssetsRequest -from .types.securitycenter_service import ListAssetsResponse -from .types.securitycenter_service import ListAttackPathsRequest -from .types.securitycenter_service import ListAttackPathsResponse -from .types.securitycenter_service import ListBigQueryExportsRequest -from .types.securitycenter_service import ListBigQueryExportsResponse -from .types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesRequest -from .types.securitycenter_service import ListDescendantEventThreatDetectionCustomModulesResponse -from .types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesRequest -from .types.securitycenter_service import ListDescendantSecurityHealthAnalyticsCustomModulesResponse -from .types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesRequest -from .types.securitycenter_service import ListEffectiveEventThreatDetectionCustomModulesResponse -from .types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesRequest -from .types.securitycenter_service import ListEffectiveSecurityHealthAnalyticsCustomModulesResponse -from .types.securitycenter_service import ListEventThreatDetectionCustomModulesRequest -from .types.securitycenter_service import ListEventThreatDetectionCustomModulesResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListMuteConfigsRequest -from .types.securitycenter_service import ListMuteConfigsResponse -from .types.securitycenter_service import ListNotificationConfigsRequest -from .types.securitycenter_service import ListNotificationConfigsResponse -from .types.securitycenter_service import ListResourceValueConfigsRequest -from .types.securitycenter_service import ListResourceValueConfigsResponse -from .types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesRequest -from .types.securitycenter_service import ListSecurityHealthAnalyticsCustomModulesResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import ListValuedResourcesRequest -from .types.securitycenter_service import ListValuedResourcesResponse -from .types.securitycenter_service import RunAssetDiscoveryRequest -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import SetMuteRequest -from .types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleRequest -from .types.securitycenter_service import SimulateSecurityHealthAnalyticsCustomModuleResponse -from .types.securitycenter_service import UpdateBigQueryExportRequest -from .types.securitycenter_service import UpdateEventThreatDetectionCustomModuleRequest -from .types.securitycenter_service import UpdateExternalSystemRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateMuteConfigRequest -from .types.securitycenter_service import UpdateNotificationConfigRequest -from .types.securitycenter_service import UpdateOrganizationSettingsRequest -from .types.securitycenter_service import UpdateResourceValueConfigRequest -from .types.securitycenter_service import UpdateSecurityHealthAnalyticsCustomModuleRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.securitycenter_service import ValidateEventThreatDetectionCustomModuleRequest -from .types.securitycenter_service import ValidateEventThreatDetectionCustomModuleResponse -from .types.simulation import Simulation -from .types.source import Source -from .types.toxic_combination import ToxicCombination -from .types.valued_resource import ResourceValueConfigMetadata -from .types.valued_resource import ValuedResource -from .types.vulnerability import Cve -from .types.vulnerability import Cvssv3 -from .types.vulnerability import Package -from .types.vulnerability import Reference -from .types.vulnerability import SecurityBulletin -from .types.vulnerability import Vulnerability - -__all__ = ( - 'SecurityCenterAsyncClient', -'Access', -'AdaptiveProtection', -'Application', -'Asset', -'Attack', -'AttackExposure', -'AttackPath', -'AwsMetadata', -'AzureMetadata', -'BackupDisasterRecovery', -'BatchCreateResourceValueConfigsRequest', -'BatchCreateResourceValueConfigsResponse', -'BigQueryExport', -'BulkMuteFindingsRequest', -'BulkMuteFindingsResponse', -'CloudArmor', -'CloudDlpDataProfile', -'CloudDlpInspection', -'CloudLoggingEntry', -'CloudProvider', -'Compliance', -'Connection', -'Contact', -'ContactDetails', -'Container', -'CreateBigQueryExportRequest', -'CreateEventThreatDetectionCustomModuleRequest', -'CreateFindingRequest', -'CreateMuteConfigRequest', -'CreateNotificationConfigRequest', -'CreateResourceValueConfigRequest', -'CreateSecurityHealthAnalyticsCustomModuleRequest', -'CreateSourceRequest', -'CustomConfig', -'CustomModuleValidationError', -'CustomModuleValidationErrors', -'Cve', -'Cvssv3', -'Database', -'DeleteBigQueryExportRequest', -'DeleteEventThreatDetectionCustomModuleRequest', -'DeleteMuteConfigRequest', -'DeleteNotificationConfigRequest', -'DeleteResourceValueConfigRequest', -'DeleteSecurityHealthAnalyticsCustomModuleRequest', -'EffectiveEventThreatDetectionCustomModule', -'EffectiveSecurityHealthAnalyticsCustomModule', -'EnvironmentVariable', -'EventThreatDetectionCustomModule', -'ExfilResource', -'Exfiltration', -'ExternalSystem', -'File', -'Finding', -'Folder', -'Geolocation', -'GetBigQueryExportRequest', -'GetEffectiveEventThreatDetectionCustomModuleRequest', -'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', -'GetEventThreatDetectionCustomModuleRequest', -'GetMuteConfigRequest', -'GetNotificationConfigRequest', -'GetOrganizationSettingsRequest', -'GetResourceValueConfigRequest', -'GetSecurityHealthAnalyticsCustomModuleRequest', -'GetSimulationRequest', -'GetSourceRequest', -'GetValuedResourceRequest', -'GroupAssetsRequest', -'GroupAssetsResponse', -'GroupFindingsRequest', -'GroupFindingsResponse', -'GroupMembership', -'GroupResult', -'IamBinding', -'Indicator', -'KernelRootkit', -'Kubernetes', -'Label', -'ListAssetsRequest', -'ListAssetsResponse', -'ListAttackPathsRequest', -'ListAttackPathsResponse', -'ListBigQueryExportsRequest', -'ListBigQueryExportsResponse', -'ListDescendantEventThreatDetectionCustomModulesRequest', -'ListDescendantEventThreatDetectionCustomModulesResponse', -'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', -'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', -'ListEffectiveEventThreatDetectionCustomModulesRequest', -'ListEffectiveEventThreatDetectionCustomModulesResponse', -'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', -'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', -'ListEventThreatDetectionCustomModulesRequest', -'ListEventThreatDetectionCustomModulesResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListMuteConfigsRequest', -'ListMuteConfigsResponse', -'ListNotificationConfigsRequest', -'ListNotificationConfigsResponse', -'ListResourceValueConfigsRequest', -'ListResourceValueConfigsResponse', -'ListSecurityHealthAnalyticsCustomModulesRequest', -'ListSecurityHealthAnalyticsCustomModulesResponse', -'ListSourcesRequest', -'ListSourcesResponse', -'ListValuedResourcesRequest', -'ListValuedResourcesResponse', -'LoadBalancer', -'LogEntry', -'MitreAttack', -'MuteConfig', -'Notebook', -'NotificationConfig', -'NotificationMessage', -'OrgPolicy', -'OrganizationSettings', -'Package', -'Position', -'Process', -'Reference', -'Requests', -'Resource', -'ResourcePath', -'ResourceValue', -'ResourceValueConfig', -'ResourceValueConfigMetadata', -'RunAssetDiscoveryRequest', -'RunAssetDiscoveryResponse', -'SecurityBulletin', -'SecurityCenterClient', -'SecurityHealthAnalyticsCustomModule', -'SecurityMarks', -'SecurityPolicy', -'SecurityPosture', -'ServiceAccountDelegationInfo', -'SetFindingStateRequest', -'SetMuteRequest', -'SimulateSecurityHealthAnalyticsCustomModuleRequest', -'SimulateSecurityHealthAnalyticsCustomModuleResponse', -'Simulation', -'Source', -'ToxicCombination', -'UpdateBigQueryExportRequest', -'UpdateEventThreatDetectionCustomModuleRequest', -'UpdateExternalSystemRequest', -'UpdateFindingRequest', -'UpdateMuteConfigRequest', -'UpdateNotificationConfigRequest', -'UpdateOrganizationSettingsRequest', -'UpdateResourceValueConfigRequest', -'UpdateSecurityHealthAnalyticsCustomModuleRequest', -'UpdateSecurityMarksRequest', -'UpdateSourceRequest', -'ValidateEventThreatDetectionCustomModuleRequest', -'ValidateEventThreatDetectionCustomModuleResponse', -'ValuedResource', -'Vulnerability', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json deleted file mode 100644 index 3bca8f8a0f67..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_metadata.json +++ /dev/null @@ -1,973 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.securitycenter_v1", - "protoPackage": "google.cloud.securitycenter.v1", - "schema": "1.0", - "services": { - "SecurityCenter": { - "clients": { - "grpc": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "BatchCreateResourceValueConfigs": { - "methods": [ - "batch_create_resource_value_configs" - ] - }, - "BulkMuteFindings": { - "methods": [ - "bulk_mute_findings" - ] - }, - "CreateBigQueryExport": { - "methods": [ - "create_big_query_export" - ] - }, - "CreateEventThreatDetectionCustomModule": { - "methods": [ - "create_event_threat_detection_custom_module" - ] - }, - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateMuteConfig": { - "methods": [ - "create_mute_config" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "create_security_health_analytics_custom_module" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteBigQueryExport": { - "methods": [ - "delete_big_query_export" - ] - }, - "DeleteEventThreatDetectionCustomModule": { - "methods": [ - "delete_event_threat_detection_custom_module" - ] - }, - "DeleteMuteConfig": { - "methods": [ - "delete_mute_config" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "DeleteResourceValueConfig": { - "methods": [ - "delete_resource_value_config" - ] - }, - "DeleteSecurityHealthAnalyticsCustomModule": { - "methods": [ - "delete_security_health_analytics_custom_module" - ] - }, - "GetBigQueryExport": { - "methods": [ - "get_big_query_export" - ] - }, - "GetEffectiveEventThreatDetectionCustomModule": { - "methods": [ - "get_effective_event_threat_detection_custom_module" - ] - }, - "GetEffectiveSecurityHealthAnalyticsCustomModule": { - "methods": [ - "get_effective_security_health_analytics_custom_module" - ] - }, - "GetEventThreatDetectionCustomModule": { - "methods": [ - "get_event_threat_detection_custom_module" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetMuteConfig": { - "methods": [ - "get_mute_config" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetResourceValueConfig": { - "methods": [ - "get_resource_value_config" - ] - }, - "GetSecurityHealthAnalyticsCustomModule": { - "methods": [ - "get_security_health_analytics_custom_module" - ] - }, - "GetSimulation": { - "methods": [ - "get_simulation" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GetValuedResource": { - "methods": [ - "get_valued_resource" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListAttackPaths": { - "methods": [ - "list_attack_paths" - ] - }, - "ListBigQueryExports": { - "methods": [ - "list_big_query_exports" - ] - }, - "ListDescendantEventThreatDetectionCustomModules": { - "methods": [ - "list_descendant_event_threat_detection_custom_modules" - ] - }, - "ListDescendantSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_descendant_security_health_analytics_custom_modules" - ] - }, - "ListEffectiveEventThreatDetectionCustomModules": { - "methods": [ - "list_effective_event_threat_detection_custom_modules" - ] - }, - "ListEffectiveSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_effective_security_health_analytics_custom_modules" - ] - }, - "ListEventThreatDetectionCustomModules": { - "methods": [ - "list_event_threat_detection_custom_modules" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListMuteConfigs": { - "methods": [ - "list_mute_configs" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListResourceValueConfigs": { - "methods": [ - "list_resource_value_configs" - ] - }, - "ListSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_security_health_analytics_custom_modules" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "ListValuedResources": { - "methods": [ - "list_valued_resources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "SetMute": { - "methods": [ - "set_mute" - ] - }, - "SimulateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "simulate_security_health_analytics_custom_module" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateBigQueryExport": { - "methods": [ - "update_big_query_export" - ] - }, - "UpdateEventThreatDetectionCustomModule": { - "methods": [ - "update_event_threat_detection_custom_module" - ] - }, - "UpdateExternalSystem": { - "methods": [ - "update_external_system" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateMuteConfig": { - "methods": [ - "update_mute_config" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateResourceValueConfig": { - "methods": [ - "update_resource_value_config" - ] - }, - "UpdateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "update_security_health_analytics_custom_module" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - }, - "ValidateEventThreatDetectionCustomModule": { - "methods": [ - "validate_event_threat_detection_custom_module" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SecurityCenterAsyncClient", - "rpcs": { - "BatchCreateResourceValueConfigs": { - "methods": [ - "batch_create_resource_value_configs" - ] - }, - "BulkMuteFindings": { - "methods": [ - "bulk_mute_findings" - ] - }, - "CreateBigQueryExport": { - "methods": [ - "create_big_query_export" - ] - }, - "CreateEventThreatDetectionCustomModule": { - "methods": [ - "create_event_threat_detection_custom_module" - ] - }, - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateMuteConfig": { - "methods": [ - "create_mute_config" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "create_security_health_analytics_custom_module" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteBigQueryExport": { - "methods": [ - "delete_big_query_export" - ] - }, - "DeleteEventThreatDetectionCustomModule": { - "methods": [ - "delete_event_threat_detection_custom_module" - ] - }, - "DeleteMuteConfig": { - "methods": [ - "delete_mute_config" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "DeleteResourceValueConfig": { - "methods": [ - "delete_resource_value_config" - ] - }, - "DeleteSecurityHealthAnalyticsCustomModule": { - "methods": [ - "delete_security_health_analytics_custom_module" - ] - }, - "GetBigQueryExport": { - "methods": [ - "get_big_query_export" - ] - }, - "GetEffectiveEventThreatDetectionCustomModule": { - "methods": [ - "get_effective_event_threat_detection_custom_module" - ] - }, - "GetEffectiveSecurityHealthAnalyticsCustomModule": { - "methods": [ - "get_effective_security_health_analytics_custom_module" - ] - }, - "GetEventThreatDetectionCustomModule": { - "methods": [ - "get_event_threat_detection_custom_module" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetMuteConfig": { - "methods": [ - "get_mute_config" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetResourceValueConfig": { - "methods": [ - "get_resource_value_config" - ] - }, - "GetSecurityHealthAnalyticsCustomModule": { - "methods": [ - "get_security_health_analytics_custom_module" - ] - }, - "GetSimulation": { - "methods": [ - "get_simulation" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GetValuedResource": { - "methods": [ - "get_valued_resource" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListAttackPaths": { - "methods": [ - "list_attack_paths" - ] - }, - "ListBigQueryExports": { - "methods": [ - "list_big_query_exports" - ] - }, - "ListDescendantEventThreatDetectionCustomModules": { - "methods": [ - "list_descendant_event_threat_detection_custom_modules" - ] - }, - "ListDescendantSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_descendant_security_health_analytics_custom_modules" - ] - }, - "ListEffectiveEventThreatDetectionCustomModules": { - "methods": [ - "list_effective_event_threat_detection_custom_modules" - ] - }, - "ListEffectiveSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_effective_security_health_analytics_custom_modules" - ] - }, - "ListEventThreatDetectionCustomModules": { - "methods": [ - "list_event_threat_detection_custom_modules" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListMuteConfigs": { - "methods": [ - "list_mute_configs" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListResourceValueConfigs": { - "methods": [ - "list_resource_value_configs" - ] - }, - "ListSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_security_health_analytics_custom_modules" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "ListValuedResources": { - "methods": [ - "list_valued_resources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "SetMute": { - "methods": [ - "set_mute" - ] - }, - "SimulateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "simulate_security_health_analytics_custom_module" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateBigQueryExport": { - "methods": [ - "update_big_query_export" - ] - }, - "UpdateEventThreatDetectionCustomModule": { - "methods": [ - "update_event_threat_detection_custom_module" - ] - }, - "UpdateExternalSystem": { - "methods": [ - "update_external_system" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateMuteConfig": { - "methods": [ - "update_mute_config" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateResourceValueConfig": { - "methods": [ - "update_resource_value_config" - ] - }, - "UpdateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "update_security_health_analytics_custom_module" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - }, - "ValidateEventThreatDetectionCustomModule": { - "methods": [ - "validate_event_threat_detection_custom_module" - ] - } - } - }, - "rest": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "BatchCreateResourceValueConfigs": { - "methods": [ - "batch_create_resource_value_configs" - ] - }, - "BulkMuteFindings": { - "methods": [ - "bulk_mute_findings" - ] - }, - "CreateBigQueryExport": { - "methods": [ - "create_big_query_export" - ] - }, - "CreateEventThreatDetectionCustomModule": { - "methods": [ - "create_event_threat_detection_custom_module" - ] - }, - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateMuteConfig": { - "methods": [ - "create_mute_config" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "create_security_health_analytics_custom_module" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteBigQueryExport": { - "methods": [ - "delete_big_query_export" - ] - }, - "DeleteEventThreatDetectionCustomModule": { - "methods": [ - "delete_event_threat_detection_custom_module" - ] - }, - "DeleteMuteConfig": { - "methods": [ - "delete_mute_config" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "DeleteResourceValueConfig": { - "methods": [ - "delete_resource_value_config" - ] - }, - "DeleteSecurityHealthAnalyticsCustomModule": { - "methods": [ - "delete_security_health_analytics_custom_module" - ] - }, - "GetBigQueryExport": { - "methods": [ - "get_big_query_export" - ] - }, - "GetEffectiveEventThreatDetectionCustomModule": { - "methods": [ - "get_effective_event_threat_detection_custom_module" - ] - }, - "GetEffectiveSecurityHealthAnalyticsCustomModule": { - "methods": [ - "get_effective_security_health_analytics_custom_module" - ] - }, - "GetEventThreatDetectionCustomModule": { - "methods": [ - "get_event_threat_detection_custom_module" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetMuteConfig": { - "methods": [ - "get_mute_config" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetResourceValueConfig": { - "methods": [ - "get_resource_value_config" - ] - }, - "GetSecurityHealthAnalyticsCustomModule": { - "methods": [ - "get_security_health_analytics_custom_module" - ] - }, - "GetSimulation": { - "methods": [ - "get_simulation" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GetValuedResource": { - "methods": [ - "get_valued_resource" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListAttackPaths": { - "methods": [ - "list_attack_paths" - ] - }, - "ListBigQueryExports": { - "methods": [ - "list_big_query_exports" - ] - }, - "ListDescendantEventThreatDetectionCustomModules": { - "methods": [ - "list_descendant_event_threat_detection_custom_modules" - ] - }, - "ListDescendantSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_descendant_security_health_analytics_custom_modules" - ] - }, - "ListEffectiveEventThreatDetectionCustomModules": { - "methods": [ - "list_effective_event_threat_detection_custom_modules" - ] - }, - "ListEffectiveSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_effective_security_health_analytics_custom_modules" - ] - }, - "ListEventThreatDetectionCustomModules": { - "methods": [ - "list_event_threat_detection_custom_modules" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListMuteConfigs": { - "methods": [ - "list_mute_configs" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListResourceValueConfigs": { - "methods": [ - "list_resource_value_configs" - ] - }, - "ListSecurityHealthAnalyticsCustomModules": { - "methods": [ - "list_security_health_analytics_custom_modules" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "ListValuedResources": { - "methods": [ - "list_valued_resources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "SetMute": { - "methods": [ - "set_mute" - ] - }, - "SimulateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "simulate_security_health_analytics_custom_module" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateBigQueryExport": { - "methods": [ - "update_big_query_export" - ] - }, - "UpdateEventThreatDetectionCustomModule": { - "methods": [ - "update_event_threat_detection_custom_module" - ] - }, - "UpdateExternalSystem": { - "methods": [ - "update_external_system" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateMuteConfig": { - "methods": [ - "update_mute_config" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateResourceValueConfig": { - "methods": [ - "update_resource_value_config" - ] - }, - "UpdateSecurityHealthAnalyticsCustomModule": { - "methods": [ - "update_security_health_analytics_custom_module" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - }, - "ValidateEventThreatDetectionCustomModule": { - "methods": [ - "validate_event_threat_detection_custom_module" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_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-securitycenter/v1/google/cloud/securitycenter_v1/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_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-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py deleted file mode 100644 index bffcff5da306..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/__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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - 'SecurityCenterClient', - 'SecurityCenterAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py deleted file mode 100644 index 913bf9fee02a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ /dev/null @@ -1,7965 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union -import warnings - -from google.cloud.securitycenter_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.securitycenter_v1.services.security_center import pagers -from google.cloud.securitycenter_v1.types import access -from google.cloud.securitycenter_v1.types import application -from google.cloud.securitycenter_v1.types import attack_exposure -from google.cloud.securitycenter_v1.types import attack_path -from google.cloud.securitycenter_v1.types import backup_disaster_recovery -from google.cloud.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import cloud_armor -from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile -from google.cloud.securitycenter_v1.types import cloud_dlp_inspection -from google.cloud.securitycenter_v1.types import compliance -from google.cloud.securitycenter_v1.types import connection -from google.cloud.securitycenter_v1.types import container -from google.cloud.securitycenter_v1.types import database -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors -from google.cloud.securitycenter_v1.types import exfiltration -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import file -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import group_membership -from google.cloud.securitycenter_v1.types import iam_binding -from google.cloud.securitycenter_v1.types import indicator -from google.cloud.securitycenter_v1.types import kernel_rootkit -from google.cloud.securitycenter_v1.types import kubernetes -from google.cloud.securitycenter_v1.types import load_balancer -from google.cloud.securitycenter_v1.types import log_entry -from google.cloud.securitycenter_v1.types import mitre_attack -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notebook -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import org_policy -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import process -from google.cloud.securitycenter_v1.types import resource -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import security_posture -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import toxic_combination -from google.cloud.securitycenter_v1.types import valued_resource -from google.cloud.securitycenter_v1.types import vulnerability -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 empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V1 APIs for Security Center service.""" - - _client: SecurityCenterClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE - - asset_path = staticmethod(SecurityCenterClient.asset_path) - parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) - attack_path_path = staticmethod(SecurityCenterClient.attack_path_path) - parse_attack_path_path = staticmethod(SecurityCenterClient.parse_attack_path_path) - big_query_export_path = staticmethod(SecurityCenterClient.big_query_export_path) - parse_big_query_export_path = staticmethod(SecurityCenterClient.parse_big_query_export_path) - dlp_job_path = staticmethod(SecurityCenterClient.dlp_job_path) - parse_dlp_job_path = staticmethod(SecurityCenterClient.parse_dlp_job_path) - effective_event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.effective_event_threat_detection_custom_module_path) - parse_effective_event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.parse_effective_event_threat_detection_custom_module_path) - effective_security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.effective_security_health_analytics_custom_module_path) - parse_effective_security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.parse_effective_security_health_analytics_custom_module_path) - event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.event_threat_detection_custom_module_path) - parse_event_threat_detection_custom_module_path = staticmethod(SecurityCenterClient.parse_event_threat_detection_custom_module_path) - external_system_path = staticmethod(SecurityCenterClient.external_system_path) - parse_external_system_path = staticmethod(SecurityCenterClient.parse_external_system_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) - parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) - mute_config_path = staticmethod(SecurityCenterClient.mute_config_path) - parse_mute_config_path = staticmethod(SecurityCenterClient.parse_mute_config_path) - notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) - parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) - organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) - parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) - policy_path = staticmethod(SecurityCenterClient.policy_path) - parse_policy_path = staticmethod(SecurityCenterClient.parse_policy_path) - resource_value_config_path = staticmethod(SecurityCenterClient.resource_value_config_path) - parse_resource_value_config_path = staticmethod(SecurityCenterClient.parse_resource_value_config_path) - security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.security_health_analytics_custom_module_path) - parse_security_health_analytics_custom_module_path = staticmethod(SecurityCenterClient.parse_security_health_analytics_custom_module_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) - simulation_path = staticmethod(SecurityCenterClient.simulation_path) - parse_simulation_path = staticmethod(SecurityCenterClient.parse_simulation_path) - source_path = staticmethod(SecurityCenterClient.source_path) - parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) - table_data_profile_path = staticmethod(SecurityCenterClient.table_data_profile_path) - parse_table_data_profile_path = staticmethod(SecurityCenterClient.parse_table_data_profile_path) - topic_path = staticmethod(SecurityCenterClient.topic_path) - parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) - valued_resource_path = staticmethod(SecurityCenterClient.valued_resource_path) - parse_valued_resource_path = staticmethod(SecurityCenterClient.parse_valued_resource_path) - common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) - parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) - common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) - parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) - parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) - parse_common_location_path = staticmethod(SecurityCenterClient.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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def bulk_mute_findings(self, - request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), - ) -> operation_async.AsyncOperation: - r"""Kicks off an LRO to bulk mute findings for a parent - based on a filter. The parent can be either an - organization, folder or project. The findings matched by - the filter will be muted after the LRO is done. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest, dict]]): - The request object. Request message for bulk findings - update. - Note: - - 1. If multiple bulk update requests - match the same resource, the order - in which they get executed is not - defined. - 2. Once a bulk operation is started, - there is no way to stop it. - parent (:class:`str`): - Required. The parent, at which bulk action needs to be - applied. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1.types.BulkMuteFindingsResponse` - The response to a BulkMute request. Contains the LRO - 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]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): - request = securitycenter_service.BulkMuteFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.bulk_mute_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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - securitycenter_service.BulkMuteFindingsResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - async def create_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - parent: Optional[str] = None, - security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Creates a resident - SecurityHealthAnalyticsCustomModule at the scope of the - given CRM parent, and also creates inherited - SecurityHealthAnalyticsCustomModules for all CRM - descendants of the given parent. These modules are - enabled by default. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_create_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Request message for creating Security - Health Analytics custom modules. - parent (:class:`str`): - Required. Resource name of the new custom module's - parent. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - security_health_analytics_custom_module (:class:`google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule`): - Required. SecurityHealthAnalytics - custom module to create. The provided - name is ignored and reset with provided - parent information and server-generated - ID. - - This corresponds to the ``security_health_analytics_custom_module`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, security_health_analytics_custom_module]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if security_health_analytics_custom_module is not None: - request.security_health_analytics_custom_module = security_health_analytics_custom_module - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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 create_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v1 - - async def sample_create_source(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateSourceRequest, dict]]): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be ``organizations/[organization_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`google.cloud.securitycenter_v1.types.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = 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_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding_id: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_create_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateFindingRequest, dict]]): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - ``organizations/[organization_id]/sources/[source_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`google.cloud.securitycenter_v1.types.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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 create_mute_config(self, - request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - mute_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Creates a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_create_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = await client.create_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateMuteConfigRequest, dict]]): - The request object. Request message for creating a mute - config. - parent (:class:`str`): - Required. Resource name of the new mute configs's - parent. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config (:class:`google.cloud.securitycenter_v1.types.MuteConfig`): - Required. The mute config being - created. - - This corresponds to the ``mute_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``mute_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.cloud.securitycenter_v1.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): - request = securitycenter_service.CreateMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if mute_config is not None: - request.mute_config = mute_config - if mute_config_id is not None: - request.mute_config_id = mute_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_mute_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 create_notification_config(self, - request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - config_id: Optional[str] = None, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_create_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.create_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest, dict]]): - The request object. Request message for creating a - notification config. - parent (:class:`str`): - Required. Resource name of the new notification config's - parent. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (:class:`str`): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters and contain - alphanumeric characters, underscores, or - hyphens only. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_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.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_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_notification_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_mute_config(self, - request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_delete_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_mute_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest, dict]]): - The request object. Request message for deleting a mute - config. - name (:class:`str`): - Required. Name of the mute config to delete. Its format - is - ``organizations/{organization}/muteConfigs/{config_id}``, - ``folders/{folder}/muteConfigs/{config_id}``, - ``projects/{project}/muteConfigs/{config_id}``, - ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, - ``folders/{folder}/locations/global/muteConfigs/{config_id}``, - or - ``projects/{project}/locations/global/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): - request = securitycenter_service.DeleteMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_mute_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 delete_notification_config(self, - request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest, dict]]): - The request object. Request message for deleting a - notification config. - name (:class:`str`): - Required. Name of the notification config to delete. Its - format is - ``organizations/[organization_id]/notificationConfigs/[config_id]``, - ``folders/[folder_id]/notificationConfigs/[config_id]``, - or - ``projects/[project_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 delete_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]] = 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 - SecurityHealthAnalyticsCustomModule and all of its - descendants in the CRM hierarchy. This method is only - supported for resident custom modules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_delete_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - await client.delete_security_health_analytics_custom_module(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Request message for deleting Security - Health Analytics custom modules. - name (:class:`str`): - Required. Name of the custom module to delete. Its - format is - ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be 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, securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_simulation(self, - request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> simulation.Simulation: - r"""Get the simulation by name or the latest simulation - for the given organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_simulation(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_simulation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetSimulationRequest, dict]]): - The request object. Request message for getting - simulation. Simulation name can include - "latest" to retrieve the latest - simulation For example, - "organizations/123/simulations/latest". - name (:class:`str`): - Required. The organization name or simulation name of - this simulation - - Valid format: - ``organizations/{organization}/simulations/latest`` - ``organizations/{organization}/simulations/{simulation}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Simulation: - Attack path simulation - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSimulationRequest): - request = securitycenter_service.GetSimulationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_simulation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_valued_resource(self, - request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> valued_resource.ValuedResource: - r"""Get the valued resource by 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 import securitycenter_v1 - - async def sample_get_valued_resource(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_valued_resource(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetValuedResourceRequest, dict]]): - The request object. Request message for getting a valued - resource. - name (:class:`str`): - Required. The name of this valued resource - - Valid format: - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v1.types.ValuedResource: - A resource that is determined to have - value to a user's system - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetValuedResourceRequest): - request = securitycenter_service.GetValuedResourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_valued_resource] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_big_query_export(self, - request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Gets a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = await client.get_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetBigQueryExportRequest, dict]]): - The request object. Request message for retrieving a - BigQuery export. - name (:class:`str`): - Required. Name of the BigQuery export to retrieve. Its - format is - ``organizations/{organization}/bigQueryExports/{export_id}``, - ``folders/{folder}/bigQueryExports/{export_id}``, or - ``projects/{project}/bigQueryExports/{export_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.cloud.securitycenter_v1.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): - request = securitycenter_service.GetBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 get_mute_config(self, - request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> mute_config.MuteConfig: - r"""Gets a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetMuteConfigRequest, dict]]): - The request object. Request message for retrieving a mute - config. - name (:class:`str`): - Required. Name of the mute config to retrieve. Its - format is - ``organizations/{organization}/muteConfigs/{config_id}``, - ``folders/{folder}/muteConfigs/{config_id}``, - ``projects/{project}/muteConfigs/{config_id}``, - ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, - ``folders/{folder}/locations/global/muteConfigs/{config_id}``, - or - ``projects/{project}/locations/global/muteConfigs/{config_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.cloud.securitycenter_v1.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetMuteConfigRequest): - request = securitycenter_service.GetMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_mute_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 get_notification_config(self, - request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetNotificationConfigRequest, dict]]): - The request object. Request message for getting a - notification config. - name (:class:`str`): - Required. Name of the notification config to get. Its - format is - ``organizations/[organization_id]/notificationConfigs/[config_id]``, - ``folders/[folder_id]/notificationConfigs/[config_id]``, - or - ``projects/[project_id]/notificationConfigs/[config_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.cloud.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 get_organization_settings(self, - request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest, dict]]): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - ``organizations/[organization_id]/organizationSettings``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_organization_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 get_effective_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: - r"""Retrieves an - EffectiveSecurityHealthAnalyticsCustomModule. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_effective_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_effective_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Request message for getting effective - Security Health Analytics custom - modules. - name (:class:`str`): - Required. Name of the effective custom module to get. - Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule: - An EffectiveSecurityHealthAnalyticsCustomModule is the representation of - a Security Health Analytics custom module at a - specified level of the resource hierarchy: - organization, folder, or project. If a custom module - is inherited from a parent organization or folder, - the value of the enablementState property in - EffectiveSecurityHealthAnalyticsCustomModule is set - to the value that is effective in the parent, instead - of INHERITED. For example, if the module is enabled - in a parent organization or folder, the effective - enablement_state for the module in all child folders - or projects is also enabled. - EffectiveSecurityHealthAnalyticsCustomModule is - read-only. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_effective_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Retrieves a SecurityHealthAnalyticsCustomModule. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Request message for getting Security - Health Analytics custom modules. - name (:class:`str`): - Required. Name of the custom module to get. Its format - is - ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v1 - - async def sample_get_source(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetSourceRequest, dict]]): - The request object. Request message for getting a source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 group_assets(self, - request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsAsyncPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_group_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GroupAssetsRequest, dict]]): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsAsyncPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - warnings.warn("SecurityCenterAsyncClient.group_assets is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.GroupAssetsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_group_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GroupFindingsRequest, dict]]): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - ``organizations/[organization_id]/sources/[source_id]``, - ``folders/[folder_id]/sources/[source_id]``, or - ``projects/[project_id]/sources/[source_id]``. To - groupBy across all sources provide a source_id of ``-``. - For example: - ``organizations/{organization_id}/sources/-, folders/{folder_id}/sources/-``, - or ``projects/{project_id}/sources/-`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported when compare_duration - is set: - - - state_change - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_assets(self, - request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsAsyncPager: - r"""Lists an organization's assets. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListAssetsRequest, dict]]): - The request object. Request message for listing assets. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsAsyncPager: - Response message for listing assets. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - warnings.warn("SecurityCenterAsyncClient.list_assets is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(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_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListAssetsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_descendant_security_health_analytics_custom_modules(self, - request: Optional[Union[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, 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.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: - r"""Returns a list of all resident - SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent’s CRM descendants. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_descendant_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, dict]]): - The request object. Request message for listing - descendant Security Health Analytics - custom modules. - parent (:class:`str`): - Required. Name of parent to list descendant custom - modules. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - 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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: - Response message for listing - descendant Security Health Analytics - custom modules. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_descendant_security_health_analytics_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings(self, - request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListFindingsRequest( - parent="parent_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.securitycenter_v1.types.ListFindingsRequest, dict]]): - The request object. Request message for listing findings. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.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_mute_configs(self, - request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsAsyncPager: - r"""Lists mute configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_mute_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListMuteConfigsRequest, dict]]): - The request object. Request message for listing mute - configs at a given scope e.g. - organization, folder or project. - parent (:class:`str`): - Required. The parent, which owns the collection of mute - configs. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - - 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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsAsyncPager: - Response message for listing mute - configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): - request = securitycenter_service.ListMuteConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_mute_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.ListMuteConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_notification_configs(self, - request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsAsyncPager: - r"""Lists notification configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest, dict]]): - The request object. Request message for listing - notification configs. - parent (:class:`str`): - Required. The name of the parent in which to list the - notification configurations. Its format is - "organizations/[organization_id]", - "folders/[folder_id]", or "projects/[project_id]". - - 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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsAsyncPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListNotificationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_effective_security_health_analytics_custom_modules(self, - request: Optional[Union[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, 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.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: - r"""Returns a list of all - EffectiveSecurityHealthAnalyticsCustomModules for the - given parent. This includes resident modules defined at - the scope of the parent, and inherited modules, - inherited from CRM ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_effective_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_security_health_analytics_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, dict]]): - The request object. Request message for listing effective - Security Health Analytics custom - modules. - parent (:class:`str`): - Required. Name of parent to list effective custom - modules. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - 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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: - Response message for listing - effective Security Health Analytics - custom modules. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_effective_security_health_analytics_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_security_health_analytics_custom_modules(self, - request: Optional[Union[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, 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.ListSecurityHealthAnalyticsCustomModulesAsyncPager: - r"""Returns a list of all - SecurityHealthAnalyticsCustomModules for the given - parent. This includes resident modules defined at the - scope of the parent, and inherited modules, inherited - from CRM ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_security_health_analytics_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest, dict]]): - The request object. Request message for listing Security - Health Analytics custom modules. - parent (:class:`str`): - Required. Name of parent to list custom modules. Its - format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - 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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager: - Response message for listing Security - Health Analytics custom modules. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_security_health_analytics_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListSecurityHealthAnalyticsCustomModulesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_sources(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListSourcesRequest, dict]]): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - 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.securitycenter_v1.services.security_center.pagers.ListSourcesAsyncPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_asset_discovery(self, - request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), - ) -> operation_async.AsyncOperation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS 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 securitycenter_v1 - - async def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest, dict]]): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - ``organizations/[organization_id]``. - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` - Response of asset discovery run - - """ - warnings.warn("SecurityCenterAsyncClient.run_asset_discovery is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - async def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - start_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of 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 securitycenter_v1 - - async def sample_set_finding_state(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.SetFindingStateRequest, dict]]): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The `relative resource - name `__ - of the finding. Example: - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`google.cloud.securitycenter_v1.types.Finding.State`): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_mute(self, - request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, - *, - name: Optional[str] = None, - mute: Optional[finding.Finding.Mute] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the mute state of 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 securitycenter_v1 - - async def sample_set_mute(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = await client.set_mute(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.SetMuteRequest, dict]]): - The request object. Request message for updating a - finding's mute status. - name (:class:`str`): - Required. The `relative resource - name `__ - of the finding. Example: - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute (:class:`google.cloud.securitycenter_v1.types.Finding.Mute`): - Required. The desired state of the - Mute. - - This corresponds to the ``mute`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, mute]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetMuteRequest): - request = securitycenter_service.SetMuteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if mute is not None: - request.mute = mute - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.set_mute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 simulate_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - parent: Optional[str] = None, - custom_config: Optional[security_health_analytics_custom_config.CustomConfig] = None, - resource: Optional[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: - r"""Simulates a given SecurityHealthAnalyticsCustomModule - and Resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_simulate_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - resource = securitycenter_v1.SimulatedResource() - resource.resource_type = "resource_type_value" - - request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - resource=resource, - ) - - # Make the request - response = await client.simulate_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Request message to simulate a - CustomConfig against a given test - resource. Maximum size of the request is - 4 MB by default. - parent (:class:`str`): - Required. The relative resource name of the - organization, project, or folder. For more information - about relative resource names, see `Relative Resource - Name `__ - Example: ``organizations/{organization_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - custom_config (:class:`google.cloud.securitycenter_v1.types.CustomConfig`): - Required. The custom configuration - that you need to test. - - This corresponds to the ``custom_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (:class:`google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource`): - Required. Resource data to simulate - custom module against. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse: - Response message for simulating a SecurityHealthAnalyticsCustomModule - against a given 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, custom_config, resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if custom_config is not None: - request.custom_config = custom_config - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.simulate_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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_external_system(self, - request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, - *, - external_system: Optional[gcs_external_system.ExternalSystem] = None, - update_mask: 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]] = (), - ) -> gcs_external_system.ExternalSystem: - r"""Updates external system. This is for a given 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 securitycenter_v1 - - async def sample_update_external_system(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateExternalSystemRequest( - ) - - # Make the request - response = await client.update_external_system(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest, dict]]): - The request object. Request message for updating a - ExternalSystem resource. - external_system (:class:`google.cloud.securitycenter_v1.types.ExternalSystem`): - Required. The external system - resource to update. - - This corresponds to the ``external_system`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the external system resource. - If empty all mutable fields 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.cloud.securitycenter_v1.types.ExternalSystem: - Representation of third party - SIEM/SOAR fields within SCC. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): - request = securitycenter_service.UpdateExternalSystemRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if external_system is not None: - request.external_system = external_system - 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_external_system] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("external_system.name", request.external_system.name), - )), - ) - - # Validate the universe domain. - self._client._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_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateFindingRequest, dict]]): - The request object. Request message for updating or - creating a finding. - finding (:class:`google.cloud.securitycenter_v1.types.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe domain. - self._client._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_mute_config(self, - request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, - *, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - update_mask: 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]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Updates a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = await client.update_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest, dict]]): - The request object. Request message for updating a mute - config. - mute_config (:class:`google.cloud.securitycenter_v1.types.MuteConfig`): - Required. The mute config being - updated. - - This corresponds to the ``mute_config`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): - request = securitycenter_service.UpdateMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if mute_config is not None: - request.mute_config = mute_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_mute_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("mute_config.name", request.mute_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 update_notification_config(self, - request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, - *, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - update_mask: 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]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = await client.update_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest, dict]]): - The request object. Request message for updating a - notification config. - notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the notification config. - If empty all mutable fields 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.cloud.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_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 update_organization_settings(self, - request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, - *, - organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = await client.update_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest, dict]]): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`google.cloud.securitycenter_v1.types.OrganizationSettings`): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_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 update_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, - update_mask: 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]] = (), - ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Updates the SecurityHealthAnalyticsCustomModule under - the given name based on the given update mask. Updating - the enablement state is supported on both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name and custom config of a module is supported - on resident modules only. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( - ) - - # Make the request - response = await client.update_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Request message for updating Security - Health Analytics custom modules. - security_health_analytics_custom_module (:class:`google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule`): - Required. The SecurityHealthAnalytics - custom module to update. - - This corresponds to the ``security_health_analytics_custom_module`` 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 only fields that - can be updated are ``enablement_state`` and - ``custom_config``. If empty or set to the wildcard value - ``*``, both ``enablement_state`` and ``custom_config`` - are 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.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_health_analytics_custom_module, 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, securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_health_analytics_custom_module is not None: - request.security_health_analytics_custom_module = security_health_analytics_custom_module - 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_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_health_analytics_custom_module.name", request.security_health_analytics_custom_module.name), - )), - ) - - # Validate the universe domain. - self._client._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_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v1 - - async def sample_update_source(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateSourceRequest, dict]]): - The request object. Request message for updating a - source. - source (:class:`google.cloud.securitycenter_v1.types.Source`): - Required. The source resource to - update. - - This corresponds to the ``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.cloud.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_security_marks(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest, dict]]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`google.cloud.securitycenter_v1.types.SecurityMarks`): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe domain. - self._client._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_big_query_export(self, - request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, - *, - parent: Optional[str] = None, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - big_query_export_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Creates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_create_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = await client.create_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest, dict]]): - The request object. Request message for creating a - BigQuery export. - parent (:class:`str`): - Required. The name of the parent resource of the new - BigQuery export. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export (:class:`google.cloud.securitycenter_v1.types.BigQueryExport`): - Required. The BigQuery export being - created. - - This corresponds to the ``big_query_export`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``big_query_export_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.cloud.securitycenter_v1.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): - request = securitycenter_service.CreateBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if big_query_export is not None: - request.big_query_export = big_query_export - if big_query_export_id is not None: - request.big_query_export_id = big_query_export_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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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_big_query_export(self, - request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - await client.delete_big_query_export(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest, dict]]): - The request object. Request message for deleting a - BigQuery export. - name (:class:`str`): - Required. The name of the BigQuery export to delete. Its - format is - ``organizations/{organization}/bigQueryExports/{export_id}``, - ``folders/{folder}/bigQueryExports/{export_id}``, or - ``projects/{project}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): - request = securitycenter_service.DeleteBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_big_query_export(self, - request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, - *, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - update_mask: 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]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Updates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateBigQueryExportRequest( - ) - - # Make the request - response = await client.update_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest, dict]]): - The request object. Request message for updating a - BigQuery export. - big_query_export (:class:`google.cloud.securitycenter_v1.types.BigQueryExport`): - Required. The BigQuery export being - updated. - - This corresponds to the ``big_query_export`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): - request = securitycenter_service.UpdateBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if big_query_export is not None: - request.big_query_export = big_query_export - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("big_query_export.name", request.big_query_export.name), - )), - ) - - # Validate the universe domain. - self._client._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_big_query_exports(self, - request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsAsyncPager: - r"""Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are 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 securitycenter_v1 - - async def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest, dict]]): - The request object. Request message for listing BigQuery - exports at a given scope e.g. - organization, folder or project. - parent (:class:`str`): - Required. The parent, which owns the collection of - BigQuery exports. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - - 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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsAsyncPager: - Response message for listing BigQuery - exports. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): - request = securitycenter_service.ListBigQueryExportsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_big_query_exports] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListBigQueryExportsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - parent: Optional[str] = None, - event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Creates a resident Event Threat Detection custom - module at the scope of the given Resource Manager - parent, and also creates inherited custom modules for - all descendants of the given parent. These modules are - enabled by default. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_create_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Request to create an Event Threat - Detection custom module. - parent (:class:`str`): - Required. The new custom module's parent. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - event_threat_detection_custom_module (:class:`google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule`): - Required. The module to create. The - event_threat_detection_custom_module.name will be - ignored and server generated. - - This corresponds to the ``event_threat_detection_custom_module`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, event_threat_detection_custom_module]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if event_threat_detection_custom_module is not None: - request.event_threat_detection_custom_module = event_threat_detection_custom_module - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, dict]] = 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 Event Threat Detection custom - module and all of its descendants in the Resource - Manager hierarchy. This method is only supported for - resident custom modules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_delete_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - await client.delete_event_threat_detection_custom_module(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Request to delete an Event Threat - Detection custom module. - name (:class:`str`): - Required. Name of the custom module to delete. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be 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, securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.GetEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Gets an Event Threat Detection custom module. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Request to get an Event Threat - Detection custom module. - name (:class:`str`): - Required. Name of the custom module to get. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_descendant_event_threat_detection_custom_modules(self, - request: Optional[Union[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, 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.ListDescendantEventThreatDetectionCustomModulesAsyncPager: - r"""Lists all resident Event Threat Detection custom - modules under the given Resource Manager parent and its - descendants. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_descendant_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest, dict]]): - The request object. Request to list current and - descendant resident Event Threat - Detection custom modules. - parent (:class:`str`): - Required. Name of the parent to list custom modules - under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - 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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager: - Response for listing current and - descendant resident Event Threat - Detection custom modules. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_descendant_event_threat_detection_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListDescendantEventThreatDetectionCustomModulesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_event_threat_detection_custom_modules(self, - request: Optional[Union[securitycenter_service.ListEventThreatDetectionCustomModulesRequest, 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.ListEventThreatDetectionCustomModulesAsyncPager: - r"""Lists all Event Threat Detection custom modules for - the given Resource Manager parent. This includes - resident modules defined at the scope of the parent - along with modules inherited from ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_event_threat_detection_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest, dict]]): - The request object. Request to list Event Threat - Detection custom modules. - parent (:class:`str`): - Required. Name of the parent to list custom modules - under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - 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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesAsyncPager: - Response for listing Event Threat - Detection custom modules. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListEventThreatDetectionCustomModulesRequest): - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_event_threat_detection_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListEventThreatDetectionCustomModulesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, - update_mask: 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]] = (), - ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Updates the Event Threat Detection custom module with - the given name based on the given update mask. Updating - the enablement state is supported for both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name or configuration of a module is supported - for resident modules only. The type of a module cannot - be changed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( - ) - - # Make the request - response = await client.update_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Request to update an Event Threat - Detection custom module. - event_threat_detection_custom_module (:class:`google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule`): - Required. The module being updated. - This corresponds to the ``event_threat_detection_custom_module`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([event_threat_detection_custom_module, 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, securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if event_threat_detection_custom_module is not None: - request.event_threat_detection_custom_module = event_threat_detection_custom_module - 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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("event_threat_detection_custom_module.name", request.event_threat_detection_custom_module.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def validate_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: - r"""Validates the given Event Threat Detection custom - module. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_validate_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - raw_text="raw_text_value", - type_="type__value", - ) - - # Make the request - response = await client.validate_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Request to validate an Event Threat - Detection custom module. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse: - Response to validating an Event - Threat Detection custom module. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest(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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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_effective_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: - r"""Gets an effective Event Threat Detection custom - module at the given level. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_effective_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_effective_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Request to get an - EffectiveEventThreatDetectionCustomModule. - name (:class:`str`): - Required. The resource name of the effective Event - Threat Detection custom module. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule: - An EffectiveEventThreatDetectionCustomModule is the representation of - an Event Threat Detection custom module at a - specified level of the resource hierarchy: - organization, folder, or project. If a custom module - is inherited from a parent organization or folder, - the value of the enablement_state property in - EffectiveEventThreatDetectionCustomModule is set to - the value that is effective in the parent, instead of - INHERITED. For example, if the module is enabled in a - parent organization or folder, the effective - enablement_state for the module in all child folders - or projects is also enabled. - EffectiveEventThreatDetectionCustomModule is - read-only. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_effective_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_effective_event_threat_detection_custom_modules(self, - request: Optional[Union[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, 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.ListEffectiveEventThreatDetectionCustomModulesAsyncPager: - r"""Lists all effective Event Threat Detection custom - modules for the given parent. This includes resident - modules defined at the scope of the parent along with - modules inherited from its ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_effective_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_event_threat_detection_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest, dict]]): - The request object. Request to list effective Event - Threat Detection custom modules. - parent (:class:`str`): - Required. Name of the parent to list custom modules for. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - 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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesAsyncPager: - Response for listing - EffectiveEventThreatDetectionCustomModules. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_effective_event_threat_detection_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListEffectiveEventThreatDetectionCustomModulesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_create_resource_value_configs(self, - request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - r"""Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - requests = securitycenter_v1.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - requests.resource_value_config.resource_value = "NONE" - requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest, dict]]): - The request object. Request message to create multiple - resource value configs - parent (:class:`str`): - Required. Resource name of the new - ResourceValueConfig's parent. The parent - field in the - CreateResourceValueConfigRequest - messages must either be empty or match - this field. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - requests (:class:`MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]`): - Required. The resource value configs - to be created. - - This corresponds to the ``requests`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse: - Response message for - BatchCreateResourceValueConfigs - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, requests]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): - request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if requests: - request.requests.extend(requests) - - # 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_resource_value_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, - ) - - # Done; return the response. - return response - - async def delete_resource_value_config(self, - request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_resource_value_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest, dict]]): - The request object. Request message to delete resource - value config - name (:class:`str`): - Required. Name of the - ResourceValueConfig 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. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): - request = securitycenter_service.DeleteResourceValueConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_resource_value_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_resource_value_config(self, - request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resource_value_config.ResourceValueConfig: - r"""Gets a ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest, dict]]): - The request object. Request message to get resource value - config - name (:class:`str`): - Required. Name of the resource value config to retrieve. - Its format is - ``organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v1.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): - request = securitycenter_service.GetResourceValueConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_resource_value_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_resource_value_configs(self, - request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsAsyncPager: - r"""Lists all ResourceValueConfigs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest, dict]]): - The request object. Request message to list resource - value configs of a parent - parent (:class:`str`): - Required. The parent, which owns the collection of - resource value configs. Its format is - ``organizations/[organization_id]`` - - 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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsAsyncPager: - Response message to list resource - value configs - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): - request = securitycenter_service.ListResourceValueConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_resource_value_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.ListResourceValueConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_resource_value_config(self, - request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, - *, - resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, - update_mask: 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]] = (), - ) -> gcs_resource_value_config.ResourceValueConfig: - r"""Updates an existing ResourceValueConfigs with new - rules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - resource_value_config = securitycenter_v1.ResourceValueConfig() - resource_value_config.resource_value = "NONE" - resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.UpdateResourceValueConfigRequest( - resource_value_config=resource_value_config, - ) - - # Make the request - response = await client.update_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest, dict]]): - The request object. Request message to update resource - value config - resource_value_config (:class:`google.cloud.securitycenter_v1.types.ResourceValueConfig`): - Required. The resource value config - being updated. - - This corresponds to the ``resource_value_config`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): - request = securitycenter_service.UpdateResourceValueConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if resource_value_config is not None: - request.resource_value_config = resource_value_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_resource_value_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource_value_config.name", request.resource_value_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 list_valued_resources(self, - request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesAsyncPager: - r"""Lists the valued resources for a set of simulation - results and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_valued_resources(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListValuedResourcesRequest, dict]]): - The request object. Request message for listing the - valued resources for a given simulation. - parent (:class:`str`): - Required. Name of parent to list valued resources. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - - 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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesAsyncPager: - Response message for listing the - valued resources for a given simulation. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): - request = securitycenter_service.ListValuedResourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_valued_resources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListValuedResourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_attack_paths(self, - request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsAsyncPager: - r"""Lists the attack paths for a set of simulation - results or valued resources and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - async def sample_list_attack_paths(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1.types.ListAttackPathsRequest, dict]]): - The request object. Request message for listing the - attack paths for a given simulation or - valued resource. - parent (:class:`str`): - Required. Name of parent to list attack paths. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - - 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.securitycenter_v1.services.security_center.pagers.ListAttackPathsAsyncPager: - Response message for listing the - attack paths for a given simulation or - valued resource. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): - request = securitycenter_service.ListAttackPathsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_attack_paths] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListAttackPathsAsyncPager( - method=rpc, - request=request, - response=response, - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self) -> "SecurityCenterAsyncClient": - 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__ = ( - "SecurityCenterAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py deleted file mode 100644 index 2224817c3303..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/client.py +++ /dev/null @@ -1,8455 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_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.securitycenter_v1.services.security_center import pagers -from google.cloud.securitycenter_v1.types import access -from google.cloud.securitycenter_v1.types import application -from google.cloud.securitycenter_v1.types import attack_exposure -from google.cloud.securitycenter_v1.types import attack_path -from google.cloud.securitycenter_v1.types import backup_disaster_recovery -from google.cloud.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import cloud_armor -from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile -from google.cloud.securitycenter_v1.types import cloud_dlp_inspection -from google.cloud.securitycenter_v1.types import compliance -from google.cloud.securitycenter_v1.types import connection -from google.cloud.securitycenter_v1.types import container -from google.cloud.securitycenter_v1.types import database -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors -from google.cloud.securitycenter_v1.types import exfiltration -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import file -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import group_membership -from google.cloud.securitycenter_v1.types import iam_binding -from google.cloud.securitycenter_v1.types import indicator -from google.cloud.securitycenter_v1.types import kernel_rootkit -from google.cloud.securitycenter_v1.types import kubernetes -from google.cloud.securitycenter_v1.types import load_balancer -from google.cloud.securitycenter_v1.types import log_entry -from google.cloud.securitycenter_v1.types import mitre_attack -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notebook -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import org_policy -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import process -from google.cloud.securitycenter_v1.types import resource -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import security_posture -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import toxic_combination -from google.cloud.securitycenter_v1.types import valued_resource -from google.cloud.securitycenter_v1.types import vulnerability -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 empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .transports.rest import SecurityCenterRestTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - _transport_registry["rest"] = SecurityCenterRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SecurityCenterTransport]: - """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V1 APIs for Security Center 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 = "securitycenter.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: - SecurityCenterClient: 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: - SecurityCenterClient: 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) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def asset_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified asset string.""" - return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_asset_path(path: str) -> Dict[str,str]: - """Parses a asset path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def attack_path_path(organization: str,simulation: str,valued_resource: str,attack_path: str,) -> str: - """Returns a fully-qualified attack_path string.""" - return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) - - @staticmethod - def parse_attack_path_path(path: str) -> Dict[str,str]: - """Parses a attack_path path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?P.+?)/attackPaths/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def big_query_export_path(organization: str,export: str,) -> str: - """Returns a fully-qualified big_query_export string.""" - return "organizations/{organization}/bigQueryExports/{export}".format(organization=organization, export=export, ) - - @staticmethod - def parse_big_query_export_path(path: str) -> Dict[str,str]: - """Parses a big_query_export path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/bigQueryExports/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def dlp_job_path(project: str,dlp_job: str,) -> str: - """Returns a fully-qualified dlp_job string.""" - return "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) - - @staticmethod - def parse_dlp_job_path(path: str) -> Dict[str,str]: - """Parses a dlp_job path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/dlpJobs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def effective_event_threat_detection_custom_module_path(organization: str,module: str,) -> str: - """Returns a fully-qualified effective_event_threat_detection_custom_module string.""" - return "organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}".format(organization=organization, module=module, ) - - @staticmethod - def parse_effective_event_threat_detection_custom_module_path(path: str) -> Dict[str,str]: - """Parses a effective_event_threat_detection_custom_module path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/eventThreatDetectionSettings/effectiveCustomModules/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def effective_security_health_analytics_custom_module_path(organization: str,effective_custom_module: str,) -> str: - """Returns a fully-qualified effective_security_health_analytics_custom_module string.""" - return "organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{effective_custom_module}".format(organization=organization, effective_custom_module=effective_custom_module, ) - - @staticmethod - def parse_effective_security_health_analytics_custom_module_path(path: str) -> Dict[str,str]: - """Parses a effective_security_health_analytics_custom_module path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/securityHealthAnalyticsSettings/effectiveCustomModules/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def event_threat_detection_custom_module_path(organization: str,module: str,) -> str: - """Returns a fully-qualified event_threat_detection_custom_module string.""" - return "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}".format(organization=organization, module=module, ) - - @staticmethod - def parse_event_threat_detection_custom_module_path(path: str) -> Dict[str,str]: - """Parses a event_threat_detection_custom_module path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/eventThreatDetectionSettings/customModules/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def external_system_path(organization: str,source: str,finding: str,externalsystem: str,) -> str: - """Returns a fully-qualified external_system string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) - - @staticmethod - def parse_external_system_path(path: str) -> Dict[str,str]: - """Parses a external_system path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)/externalSystems/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def finding_path(organization: str,source: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def mute_config_path(organization: str,mute_config: str,) -> str: - """Returns a fully-qualified mute_config string.""" - return "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) - - @staticmethod - def parse_mute_config_path(path: str) -> Dict[str,str]: - """Parses a mute_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/muteConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def notification_config_path(organization: str,notification_config: str,) -> str: - """Returns a fully-qualified notification_config string.""" - return "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) - - @staticmethod - def parse_notification_config_path(path: str) -> Dict[str,str]: - """Parses a notification_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def organization_settings_path(organization: str,) -> str: - """Returns a fully-qualified organization_settings string.""" - return "organizations/{organization}/organizationSettings".format(organization=organization, ) - - @staticmethod - def parse_organization_settings_path(path: str) -> Dict[str,str]: - """Parses a organization_settings path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) - return m.groupdict() if m else {} - - @staticmethod - def policy_path(organization: str,constraint_name: str,) -> str: - """Returns a fully-qualified policy string.""" - return "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) - - @staticmethod - def parse_policy_path(path: str) -> Dict[str,str]: - """Parses a policy path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/policies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def resource_value_config_path(organization: str,resource_value_config: str,) -> str: - """Returns a fully-qualified resource_value_config string.""" - return "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) - - @staticmethod - def parse_resource_value_config_path(path: str) -> Dict[str,str]: - """Parses a resource_value_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/resourceValueConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_health_analytics_custom_module_path(organization: str,custom_module: str,) -> str: - """Returns a fully-qualified security_health_analytics_custom_module string.""" - return "organizations/{organization}/securityHealthAnalyticsSettings/customModules/{custom_module}".format(organization=organization, custom_module=custom_module, ) - - @staticmethod - def parse_security_health_analytics_custom_module_path(path: str) -> Dict[str,str]: - """Parses a security_health_analytics_custom_module path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/securityHealthAnalyticsSettings/customModules/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str,str]: - """Parses a security_marks path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) - return m.groupdict() if m else {} - - @staticmethod - def simulation_path(organization: str,simulation: str,) -> str: - """Returns a fully-qualified simulation string.""" - return "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) - - @staticmethod - def parse_simulation_path(path: str) -> Dict[str,str]: - """Parses a simulation path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str,source: str,) -> str: - """Returns a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str,str]: - """Parses a source path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def table_data_profile_path(project: str,table_profile: str,) -> str: - """Returns a fully-qualified table_data_profile string.""" - return "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) - - @staticmethod - def parse_table_data_profile_path(path: str) -> Dict[str,str]: - """Parses a table_data_profile path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/tableProfiles/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def topic_path(project: str,topic: str,) -> str: - """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - - @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: - """Parses a topic path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def valued_resource_path(organization: str,simulation: str,valued_resource: str,) -> str: - """Returns a fully-qualified valued_resource string.""" - return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) - - @staticmethod - def parse_valued_resource_path(path: str) -> Dict[str,str]: - """Parses a valued_resource path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 - SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient._read_environment_variables() - self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) - if transport_provided: - # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( - type(self).get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., SecurityCenterTransport], 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 bulk_mute_findings(self, - request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), - ) -> operation.Operation: - r"""Kicks off an LRO to bulk mute findings for a parent - based on a filter. The parent can be either an - organization, folder or project. The findings matched by - the filter will be muted after the LRO is done. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest, dict]): - The request object. Request message for bulk findings - update. - Note: - - 1. If multiple bulk update requests - match the same resource, the order - in which they get executed is not - defined. - 2. Once a bulk operation is started, - there is no way to stop it. - parent (str): - Required. The parent, at which bulk action needs to be - applied. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1.types.BulkMuteFindingsResponse` - The response to a BulkMute request. Contains the LRO - 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): - request = securitycenter_service.BulkMuteFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.bulk_mute_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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - securitycenter_service.BulkMuteFindingsResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - def create_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - parent: Optional[str] = None, - security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Creates a resident - SecurityHealthAnalyticsCustomModule at the scope of the - given CRM parent, and also creates inherited - SecurityHealthAnalyticsCustomModules for all CRM - descendants of the given parent. These modules are - enabled by default. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_create_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Request message for creating Security - Health Analytics custom modules. - parent (str): - Required. Resource name of the new custom module's - parent. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): - Required. SecurityHealthAnalytics - custom module to create. The provided - name is ignored and reset with provided - parent information and server-generated - ID. - - This corresponds to the ``security_health_analytics_custom_module`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, security_health_analytics_custom_module]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if security_health_analytics_custom_module is not None: - request.security_health_analytics_custom_module = security_health_analytics_custom_module - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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 create_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v1 - - def sample_create_source(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateSourceRequest, dict]): - The request object. Request message for creating a - source. - parent (str): - Required. Resource name of the new source's parent. Its - format should be ``organizations/[organization_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (google.cloud.securitycenter_v1.types.Source): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding_id: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_create_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateFindingRequest, dict]): - The request object. Request message for creating a - finding. - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - ``organizations/[organization_id]/sources/[source_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (google.cloud.securitycenter_v1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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 create_mute_config(self, - request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - mute_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Creates a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_create_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = client.create_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateMuteConfigRequest, dict]): - The request object. Request message for creating a mute - config. - parent (str): - Required. Resource name of the new mute configs's - parent. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config (google.cloud.securitycenter_v1.types.MuteConfig): - Required. The mute config being - created. - - This corresponds to the ``mute_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``mute_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.cloud.securitycenter_v1.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): - request = securitycenter_service.CreateMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if mute_config is not None: - request.mute_config = mute_config - if mute_config_id is not None: - request.mute_config_id = mute_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_mute_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 create_notification_config(self, - request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - config_id: Optional[str] = None, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_create_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = client.create_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest, dict]): - The request object. Request message for creating a - notification config. - parent (str): - Required. Resource name of the new notification config's - parent. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (str): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters and contain - alphanumeric characters, underscores, or - hyphens only. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_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.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_notification_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_mute_config(self, - request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_delete_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_mute_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest, dict]): - The request object. Request message for deleting a mute - config. - name (str): - Required. Name of the mute config to delete. Its format - is - ``organizations/{organization}/muteConfigs/{config_id}``, - ``folders/{folder}/muteConfigs/{config_id}``, - ``projects/{project}/muteConfigs/{config_id}``, - ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, - ``folders/{folder}/locations/global/muteConfigs/{config_id}``, - or - ``projects/{project}/locations/global/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): - request = securitycenter_service.DeleteMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_mute_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 delete_notification_config(self, - request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest, dict]): - The request object. Request message for deleting a - notification config. - name (str): - Required. Name of the notification config to delete. Its - format is - ``organizations/[organization_id]/notificationConfigs/[config_id]``, - ``folders/[folder_id]/notificationConfigs/[config_id]``, - or - ``projects/[project_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 delete_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]] = 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 - SecurityHealthAnalyticsCustomModule and all of its - descendants in the CRM hierarchy. This method is only - supported for resident custom modules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_delete_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - client.delete_security_health_analytics_custom_module(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Request message for deleting Security - Health Analytics custom modules. - name (str): - Required. Name of the custom module to delete. Its - format is - ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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, securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - 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_simulation(self, - request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> simulation.Simulation: - r"""Get the simulation by name or the latest simulation - for the given organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_simulation(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = client.get_simulation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetSimulationRequest, dict]): - The request object. Request message for getting - simulation. Simulation name can include - "latest" to retrieve the latest - simulation For example, - "organizations/123/simulations/latest". - name (str): - Required. The organization name or simulation name of - this simulation - - Valid format: - ``organizations/{organization}/simulations/latest`` - ``organizations/{organization}/simulations/{simulation}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Simulation: - Attack path simulation - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSimulationRequest): - request = securitycenter_service.GetSimulationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_simulation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_valued_resource(self, - request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> valued_resource.ValuedResource: - r"""Get the valued resource by 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 import securitycenter_v1 - - def sample_get_valued_resource(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_valued_resource(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetValuedResourceRequest, dict]): - The request object. Request message for getting a valued - resource. - name (str): - Required. The name of this valued resource - - Valid format: - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v1.types.ValuedResource: - A resource that is determined to have - value to a user's system - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetValuedResourceRequest): - request = securitycenter_service.GetValuedResourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_valued_resource] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_big_query_export(self, - request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Gets a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = client.get_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetBigQueryExportRequest, dict]): - The request object. Request message for retrieving a - BigQuery export. - name (str): - Required. Name of the BigQuery export to retrieve. Its - format is - ``organizations/{organization}/bigQueryExports/{export_id}``, - ``folders/{folder}/bigQueryExports/{export_id}``, or - ``projects/{project}/bigQueryExports/{export_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.cloud.securitycenter_v1.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): - request = securitycenter_service.GetBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 get_mute_config(self, - request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> mute_config.MuteConfig: - r"""Gets a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetMuteConfigRequest, dict]): - The request object. Request message for retrieving a mute - config. - name (str): - Required. Name of the mute config to retrieve. Its - format is - ``organizations/{organization}/muteConfigs/{config_id}``, - ``folders/{folder}/muteConfigs/{config_id}``, - ``projects/{project}/muteConfigs/{config_id}``, - ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, - ``folders/{folder}/locations/global/muteConfigs/{config_id}``, - or - ``projects/{project}/locations/global/muteConfigs/{config_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.cloud.securitycenter_v1.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetMuteConfigRequest): - request = securitycenter_service.GetMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_mute_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 get_notification_config(self, - request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetNotificationConfigRequest, dict]): - The request object. Request message for getting a - notification config. - name (str): - Required. Name of the notification config to get. Its - format is - ``organizations/[organization_id]/notificationConfigs/[config_id]``, - ``folders/[folder_id]/notificationConfigs/[config_id]``, - or - ``projects/[project_id]/notificationConfigs/[config_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.cloud.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 get_organization_settings(self, - request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest, dict]): - The request object. Request message for getting - organization settings. - name (str): - Required. Name of the organization to get organization - settings for. Its format is - ``organizations/[organization_id]/organizationSettings``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_organization_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 get_effective_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: - r"""Retrieves an - EffectiveSecurityHealthAnalyticsCustomModule. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_effective_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_effective_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Request message for getting effective - Security Health Analytics custom - modules. - name (str): - Required. Name of the effective custom module to get. - Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule: - An EffectiveSecurityHealthAnalyticsCustomModule is the representation of - a Security Health Analytics custom module at a - specified level of the resource hierarchy: - organization, folder, or project. If a custom module - is inherited from a parent organization or folder, - the value of the enablementState property in - EffectiveSecurityHealthAnalyticsCustomModule is set - to the value that is effective in the parent, instead - of INHERITED. For example, if the module is enabled - in a parent organization or folder, the effective - enablement_state for the module in all child folders - or projects is also enabled. - EffectiveSecurityHealthAnalyticsCustomModule is - read-only. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_effective_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Retrieves a SecurityHealthAnalyticsCustomModule. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Request message for getting Security - Health Analytics custom modules. - name (str): - Required. Name of the custom module to get. Its format - is - ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v1 - - def sample_get_source(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetSourceRequest, dict]): - The request object. Request message for getting a source. - name (str): - Required. Relative resource name of the source. Its - format is - ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 group_assets(self, - request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_group_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GroupAssetsRequest, dict]): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - warnings.warn("SecurityCenterClient.group_assets is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.GroupAssetsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_group_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GroupFindingsRequest, dict]): - The request object. Request message for grouping by - findings. - parent (str): - Required. Name of the source to groupBy. Its format is - ``organizations/[organization_id]/sources/[source_id]``, - ``folders/[folder_id]/sources/[source_id]``, or - ``projects/[project_id]/sources/[source_id]``. To - groupBy across all sources provide a source_id of ``-``. - For example: - ``organizations/{organization_id}/sources/-, folders/{folder_id}/sources/-``, - or ``projects/{project_id}/sources/-`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (str): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported when compare_duration - is set: - - - state_change - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_assets(self, - request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsPager: - r"""Lists an organization's assets. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListAssetsRequest, dict]): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsPager: - Response message for listing assets. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - warnings.warn("SecurityCenterClient.list_assets is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListAssetsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_descendant_security_health_analytics_custom_modules(self, - request: Optional[Union[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, 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.ListDescendantSecurityHealthAnalyticsCustomModulesPager: - r"""Returns a list of all resident - SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent’s CRM descendants. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_descendant_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, dict]): - The request object. Request message for listing - descendant Security Health Analytics - custom modules. - parent (str): - Required. Name of parent to list descendant custom - modules. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - 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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager: - Response message for listing - descendant Security Health Analytics - custom modules. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_descendant_security_health_analytics_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListDescendantSecurityHealthAnalyticsCustomModulesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings(self, - request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListFindingsRequest( - parent="parent_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.securitycenter_v1.types.ListFindingsRequest, dict]): - The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.services.security_center.pagers.ListFindingsPager: - Response message for listing - findings. - 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.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_mute_configs(self, - request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsPager: - r"""Lists mute configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_mute_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListMuteConfigsRequest, dict]): - The request object. Request message for listing mute - configs at a given scope e.g. - organization, folder or project. - parent (str): - Required. The parent, which owns the collection of mute - configs. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - - 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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsPager: - Response message for listing mute - configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): - request = securitycenter_service.ListMuteConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_mute_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.ListMuteConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_notification_configs(self, - request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsPager: - r"""Lists notification configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest, dict]): - The request object. Request message for listing - notification configs. - parent (str): - Required. The name of the parent in which to list the - notification configurations. Its format is - "organizations/[organization_id]", - "folders/[folder_id]", or "projects/[project_id]". - - 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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListNotificationConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_effective_security_health_analytics_custom_modules(self, - request: Optional[Union[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, 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.ListEffectiveSecurityHealthAnalyticsCustomModulesPager: - r"""Returns a list of all - EffectiveSecurityHealthAnalyticsCustomModules for the - given parent. This includes resident modules defined at - the scope of the parent, and inherited modules, - inherited from CRM ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_effective_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_security_health_analytics_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, dict]): - The request object. Request message for listing effective - Security Health Analytics custom - modules. - parent (str): - Required. Name of parent to list effective custom - modules. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - 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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager: - Response message for listing - effective Security Health Analytics - custom modules. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_effective_security_health_analytics_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListEffectiveSecurityHealthAnalyticsCustomModulesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_security_health_analytics_custom_modules(self, - request: Optional[Union[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, 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.ListSecurityHealthAnalyticsCustomModulesPager: - r"""Returns a list of all - SecurityHealthAnalyticsCustomModules for the given - parent. This includes resident modules defined at the - scope of the parent, and inherited modules, inherited - from CRM ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_security_health_analytics_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest, dict]): - The request object. Request message for listing Security - Health Analytics custom modules. - parent (str): - Required. Name of parent to list custom modules. Its - format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - - 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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesPager: - Response message for listing Security - Health Analytics custom modules. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_security_health_analytics_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListSecurityHealthAnalyticsCustomModulesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_sources(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListSourcesRequest, dict]): - The request object. Request message for listing sources. - parent (str): - Required. Resource name of the parent of sources to - list. Its format should be - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - 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.securitycenter_v1.services.security_center.pagers.ListSourcesPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_asset_discovery(self, - request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), - ) -> operation.Operation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS 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 securitycenter_v1 - - def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest, dict]): - The request object. Request message for running asset - discovery for an organization. - parent (str): - Required. Name of the organization to run asset - discovery for. Its format is - ``organizations/[organization_id]``. - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` - Response of asset discovery run - - """ - warnings.warn("SecurityCenterClient.run_asset_discovery is deprecated", - DeprecationWarning) - - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - start_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of 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 securitycenter_v1 - - def sample_set_finding_state(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.SetFindingStateRequest, dict]): - The request object. Request message for updating a - finding's state. - name (str): - Required. The `relative resource - name `__ - of the finding. Example: - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (google.cloud.securitycenter_v1.types.Finding.State): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_mute(self, - request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, - *, - name: Optional[str] = None, - mute: Optional[finding.Finding.Mute] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the mute state of 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 securitycenter_v1 - - def sample_set_mute(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = client.set_mute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.SetMuteRequest, dict]): - The request object. Request message for updating a - finding's mute status. - name (str): - Required. The `relative resource - name `__ - of the finding. Example: - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute (google.cloud.securitycenter_v1.types.Finding.Mute): - Required. The desired state of the - Mute. - - This corresponds to the ``mute`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, mute]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetMuteRequest): - request = securitycenter_service.SetMuteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if mute is not None: - request.mute = mute - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_mute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # 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 - - def simulate_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - parent: Optional[str] = None, - custom_config: Optional[security_health_analytics_custom_config.CustomConfig] = None, - resource: Optional[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: - r"""Simulates a given SecurityHealthAnalyticsCustomModule - and Resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_simulate_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - resource = securitycenter_v1.SimulatedResource() - resource.resource_type = "resource_type_value" - - request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - resource=resource, - ) - - # Make the request - response = client.simulate_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Request message to simulate a - CustomConfig against a given test - resource. Maximum size of the request is - 4 MB by default. - parent (str): - Required. The relative resource name of the - organization, project, or folder. For more information - about relative resource names, see `Relative Resource - Name `__ - Example: ``organizations/{organization_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - custom_config (google.cloud.securitycenter_v1.types.CustomConfig): - Required. The custom configuration - that you need to test. - - This corresponds to the ``custom_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource): - Required. Resource data to simulate - custom module against. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse: - Response message for simulating a SecurityHealthAnalyticsCustomModule - against a given 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, custom_config, resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if custom_config is not None: - request.custom_config = custom_config - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.simulate_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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_external_system(self, - request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, - *, - external_system: Optional[gcs_external_system.ExternalSystem] = None, - update_mask: 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]] = (), - ) -> gcs_external_system.ExternalSystem: - r"""Updates external system. This is for a given 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 securitycenter_v1 - - def sample_update_external_system(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateExternalSystemRequest( - ) - - # Make the request - response = client.update_external_system(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest, dict]): - The request object. Request message for updating a - ExternalSystem resource. - external_system (google.cloud.securitycenter_v1.types.ExternalSystem): - Required. The external system - resource to update. - - This corresponds to the ``external_system`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the external system resource. - If empty all mutable fields 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.cloud.securitycenter_v1.types.ExternalSystem: - Representation of third party - SIEM/SOAR fields within SCC. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): - request = securitycenter_service.UpdateExternalSystemRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if external_system is not None: - request.external_system = external_system - 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_external_system] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("external_system.name", request.external_system.name), - )), - ) - - # Validate the universe 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_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateFindingRequest, dict]): - The request object. Request message for updating or - creating a finding. - finding (google.cloud.securitycenter_v1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe 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_mute_config(self, - request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, - *, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - update_mask: 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]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Updates a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = client.update_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest, dict]): - The request object. Request message for updating a mute - config. - mute_config (google.cloud.securitycenter_v1.types.MuteConfig): - Required. The mute config being - updated. - - This corresponds to the ``mute_config`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): - request = securitycenter_service.UpdateMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if mute_config is not None: - request.mute_config = mute_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_mute_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("mute_config.name", request.mute_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 update_notification_config(self, - request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, - *, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - update_mask: 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]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = client.update_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest, dict]): - The request object. Request message for updating a - notification config. - notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the notification config. - If empty all mutable fields 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.cloud.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_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 update_organization_settings(self, - request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, - *, - organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = client.update_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest, dict]): - The request object. Request message for updating an - organization's settings. - organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_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 update_security_health_analytics_custom_module(self, - request: Optional[Union[securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]] = None, - *, - security_health_analytics_custom_module: Optional[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = None, - update_mask: 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]] = (), - ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Updates the SecurityHealthAnalyticsCustomModule under - the given name based on the given update mask. Updating - the enablement state is supported on both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name and custom config of a module is supported - on resident modules only. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( - ) - - # Make the request - response = client.update_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Request message for updating Security - Health Analytics custom modules. - security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): - Required. The SecurityHealthAnalytics - custom module to update. - - This corresponds to the ``security_health_analytics_custom_module`` 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 only fields that - can be updated are ``enablement_state`` and - ``custom_config``. If empty or set to the wildcard value - ``*``, both ``enablement_state`` and ``custom_config`` - are 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.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_health_analytics_custom_module, 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, securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_health_analytics_custom_module is not None: - request.security_health_analytics_custom_module = security_health_analytics_custom_module - 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_security_health_analytics_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_health_analytics_custom_module.name", request.security_health_analytics_custom_module.name), - )), - ) - - # Validate the universe 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_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v1 - - def sample_update_source(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateSourceRequest, dict]): - The request object. Request message for updating a - source. - source (google.cloud.securitycenter_v1.types.Source): - Required. The source resource to - update. - - This corresponds to the ``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.cloud.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_security_marks(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest, dict]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe 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_big_query_export(self, - request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, - *, - parent: Optional[str] = None, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - big_query_export_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Creates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_create_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = client.create_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest, dict]): - The request object. Request message for creating a - BigQuery export. - parent (str): - Required. The name of the parent resource of the new - BigQuery export. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): - Required. The BigQuery export being - created. - - This corresponds to the ``big_query_export`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``big_query_export_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.cloud.securitycenter_v1.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): - request = securitycenter_service.CreateBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if big_query_export is not None: - request.big_query_export = big_query_export - if big_query_export_id is not None: - request.big_query_export_id = big_query_export_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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_big_query_export(self, - request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - client.delete_big_query_export(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest, dict]): - The request object. Request message for deleting a - BigQuery export. - name (str): - Required. The name of the BigQuery export to delete. Its - format is - ``organizations/{organization}/bigQueryExports/{export_id}``, - ``folders/{folder}/bigQueryExports/{export_id}``, or - ``projects/{project}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): - request = securitycenter_service.DeleteBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - 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_big_query_export(self, - request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, - *, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - update_mask: 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]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Updates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateBigQueryExportRequest( - ) - - # Make the request - response = client.update_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest, dict]): - The request object. Request message for updating a - BigQuery export. - big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): - Required. The BigQuery export being - updated. - - This corresponds to the ``big_query_export`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): - request = securitycenter_service.UpdateBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if big_query_export is not None: - request.big_query_export = big_query_export - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("big_query_export.name", request.big_query_export.name), - )), - ) - - # Validate the universe 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_big_query_exports(self, - request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsPager: - r"""Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are 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 securitycenter_v1 - - def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest, dict]): - The request object. Request message for listing BigQuery - exports at a given scope e.g. - organization, folder or project. - parent (str): - Required. The parent, which owns the collection of - BigQuery exports. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - - 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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsPager: - Response message for listing BigQuery - exports. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): - request = securitycenter_service.ListBigQueryExportsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_big_query_exports] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListBigQueryExportsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - parent: Optional[str] = None, - event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Creates a resident Event Threat Detection custom - module at the scope of the given Resource Manager - parent, and also creates inherited custom modules for - all descendants of the given parent. These modules are - enabled by default. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_create_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest, dict]): - The request object. Request to create an Event Threat - Detection custom module. - parent (str): - Required. The new custom module's parent. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): - Required. The module to create. The - event_threat_detection_custom_module.name will be - ignored and server generated. - - This corresponds to the ``event_threat_detection_custom_module`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, event_threat_detection_custom_module]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if event_threat_detection_custom_module is not None: - request.event_threat_detection_custom_module = event_threat_detection_custom_module - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, dict]] = 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 Event Threat Detection custom - module and all of its descendants in the Resource - Manager hierarchy. This method is only supported for - resident custom modules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_delete_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - client.delete_event_threat_detection_custom_module(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest, dict]): - The request object. Request to delete an Event Threat - Detection custom module. - name (str): - Required. Name of the custom module to delete. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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, securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - 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_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.GetEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Gets an Event Threat Detection custom module. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest, dict]): - The request object. Request to get an Event Threat - Detection custom module. - name (str): - Required. Name of the custom module to get. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_descendant_event_threat_detection_custom_modules(self, - request: Optional[Union[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, 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.ListDescendantEventThreatDetectionCustomModulesPager: - r"""Lists all resident Event Threat Detection custom - modules under the given Resource Manager parent and its - descendants. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_descendant_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest, dict]): - The request object. Request to list current and - descendant resident Event Threat - Detection custom modules. - parent (str): - Required. Name of the parent to list custom modules - under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - 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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesPager: - Response for listing current and - descendant resident Event Threat - Detection custom modules. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_descendant_event_threat_detection_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListDescendantEventThreatDetectionCustomModulesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_event_threat_detection_custom_modules(self, - request: Optional[Union[securitycenter_service.ListEventThreatDetectionCustomModulesRequest, 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.ListEventThreatDetectionCustomModulesPager: - r"""Lists all Event Threat Detection custom modules for - the given Resource Manager parent. This includes - resident modules defined at the scope of the parent - along with modules inherited from ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_event_threat_detection_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest, dict]): - The request object. Request to list Event Threat - Detection custom modules. - parent (str): - Required. Name of the parent to list custom modules - under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - 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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesPager: - Response for listing Event Threat - Detection custom modules. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListEventThreatDetectionCustomModulesRequest): - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_event_threat_detection_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListEventThreatDetectionCustomModulesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - event_threat_detection_custom_module: Optional[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = None, - update_mask: 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]] = (), - ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Updates the Event Threat Detection custom module with - the given name based on the given update mask. Updating - the enablement state is supported for both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name or configuration of a module is supported - for resident modules only. The type of a module cannot - be changed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( - ) - - # Make the request - response = client.update_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest, dict]): - The request object. Request to update an Event Threat - Detection custom module. - event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): - Required. The module being updated. - This corresponds to the ``event_threat_detection_custom_module`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([event_threat_detection_custom_module, 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, securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if event_threat_detection_custom_module is not None: - request.event_threat_detection_custom_module = event_threat_detection_custom_module - 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_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("event_threat_detection_custom_module.name", request.event_threat_detection_custom_module.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def validate_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: - r"""Validates the given Event Threat Detection custom - module. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_validate_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - raw_text="raw_text_value", - type_="type__value", - ) - - # Make the request - response = client.validate_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest, dict]): - The request object. Request to validate an Event Threat - Detection custom module. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse: - Response to validating an Event - Threat Detection custom module. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.validate_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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_effective_event_threat_detection_custom_module(self, - request: Optional[Union[securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: - r"""Gets an effective Event Threat Detection custom - module at the given level. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_effective_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_effective_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]): - The request object. Request to get an - EffectiveEventThreatDetectionCustomModule. - name (str): - Required. The resource name of the effective Event - Threat Detection custom module. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule: - An EffectiveEventThreatDetectionCustomModule is the representation of - an Event Threat Detection custom module at a - specified level of the resource hierarchy: - organization, folder, or project. If a custom module - is inherited from a parent organization or folder, - the value of the enablement_state property in - EffectiveEventThreatDetectionCustomModule is set to - the value that is effective in the parent, instead of - INHERITED. For example, if the module is enabled in a - parent organization or folder, the effective - enablement_state for the module in all child folders - or projects is also enabled. - EffectiveEventThreatDetectionCustomModule is - read-only. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_effective_event_threat_detection_custom_module] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_effective_event_threat_detection_custom_modules(self, - request: Optional[Union[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, 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.ListEffectiveEventThreatDetectionCustomModulesPager: - r"""Lists all effective Event Threat Detection custom - modules for the given parent. This includes resident - modules defined at the scope of the parent along with - modules inherited from its ancestors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_effective_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_event_threat_detection_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest, dict]): - The request object. Request to list effective Event - Threat Detection custom modules. - parent (str): - Required. Name of the parent to list custom modules for. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - - 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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesPager: - Response for listing - EffectiveEventThreatDetectionCustomModules. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_effective_event_threat_detection_custom_modules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListEffectiveEventThreatDetectionCustomModulesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_create_resource_value_configs(self, - request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - r"""Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - requests = securitycenter_v1.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - requests.resource_value_config.resource_value = "NONE" - requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest, dict]): - The request object. Request message to create multiple - resource value configs - parent (str): - Required. Resource name of the new - ResourceValueConfig's parent. The parent - field in the - CreateResourceValueConfigRequest - messages must either be empty or match - this field. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - requests (MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]): - Required. The resource value configs - to be created. - - This corresponds to the ``requests`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse: - Response message for - BatchCreateResourceValueConfigs - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, requests]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): - request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if requests is not None: - request.requests = requests - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_resource_value_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, - ) - - # Done; return the response. - return response - - def delete_resource_value_config(self, - request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_resource_value_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest, dict]): - The request object. Request message to delete resource - value config - name (str): - Required. Name of the - ResourceValueConfig 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. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): - request = securitycenter_service.DeleteResourceValueConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_resource_value_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_resource_value_config(self, - request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resource_value_config.ResourceValueConfig: - r"""Gets a ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest, dict]): - The request object. Request message to get resource value - config - name (str): - Required. Name of the resource value config to retrieve. - Its format is - ``organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v1.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): - request = securitycenter_service.GetResourceValueConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_resource_value_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_resource_value_configs(self, - request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsPager: - r"""Lists all ResourceValueConfigs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest, dict]): - The request object. Request message to list resource - value configs of a parent - parent (str): - Required. The parent, which owns the collection of - resource value configs. Its format is - ``organizations/[organization_id]`` - - 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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsPager: - Response message to list resource - value configs - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): - request = securitycenter_service.ListResourceValueConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_resource_value_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.ListResourceValueConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_resource_value_config(self, - request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, - *, - resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, - update_mask: 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]] = (), - ) -> gcs_resource_value_config.ResourceValueConfig: - r"""Updates an existing ResourceValueConfigs with new - rules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - resource_value_config = securitycenter_v1.ResourceValueConfig() - resource_value_config.resource_value = "NONE" - resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.UpdateResourceValueConfigRequest( - resource_value_config=resource_value_config, - ) - - # Make the request - response = client.update_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest, dict]): - The request object. Request message to update resource - value config - resource_value_config (google.cloud.securitycenter_v1.types.ResourceValueConfig): - Required. The resource value config - being updated. - - This corresponds to the ``resource_value_config`` 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. - If empty all mutable fields 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.cloud.securitycenter_v1.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): - request = securitycenter_service.UpdateResourceValueConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if resource_value_config is not None: - request.resource_value_config = resource_value_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_resource_value_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource_value_config.name", request.resource_value_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 list_valued_resources(self, - request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesPager: - r"""Lists the valued resources for a set of simulation - results and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_valued_resources(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListValuedResourcesRequest, dict]): - The request object. Request message for listing the - valued resources for a given simulation. - parent (str): - Required. Name of parent to list valued resources. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - - 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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesPager: - Response message for listing the - valued resources for a given simulation. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): - request = securitycenter_service.ListValuedResourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_valued_resources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListValuedResourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_attack_paths(self, - request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsPager: - r"""Lists the attack paths for a set of simulation - results or valued resources and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1 - - def sample_list_attack_paths(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1.types.ListAttackPathsRequest, dict]): - The request object. Request message for listing the - attack paths for a given simulation or - valued resource. - parent (str): - Required. Name of parent to list attack paths. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - - 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.securitycenter_v1.services.security_center.pagers.ListAttackPathsPager: - Response message for listing the - attack paths for a given simulation or - valued resource. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): - request = securitycenter_service.ListAttackPathsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_attack_paths] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListAttackPathsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "SecurityCenterClient": - 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 = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - 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 = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SecurityCenterClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py deleted file mode 100644 index 6fb1704f990d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py +++ /dev/null @@ -1,2333 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.securitycenter_v1.types import attack_path -from google.cloud.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import valued_resource - - -class GroupAssetsPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupAssetsResponse], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - 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[securitycenter_service.GroupAssetsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupAssetsAsyncPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` - attributes are available on the 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[securitycenter_service.GroupAssetsResponse]], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - 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[securitycenter_service.GroupAssetsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` - attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListAssetsResponse], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - 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[securitycenter_service.ListAssetsResponse]: - 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - for page in self.pages: - yield from page.list_assets_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` - attributes are available on the 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[securitycenter_service.ListAssetsResponse]], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - 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[securitycenter_service.ListAssetsResponse]: - 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_assets_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDescendantSecurityHealthAnalyticsCustomModulesPager: - """A pager for iterating through ``list_descendant_security_health_analytics_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``security_health_analytics_custom_modules`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDescendantSecurityHealthAnalyticsCustomModules`` requests and continue to iterate - through the ``security_health_analytics_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse], - request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, - response: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse): - 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 = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) - 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[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: - 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - for page in self.pages: - yield from page.security_health_analytics_custom_modules - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: - """A pager for iterating through ``list_descendant_security_health_analytics_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``security_health_analytics_custom_modules`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDescendantSecurityHealthAnalyticsCustomModules`` requests and continue to iterate - through the ``security_health_analytics_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse` - attributes are available on the 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[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]], - request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, - response: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesResponse): - 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 = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(request) - 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[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: - 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - async def async_generator(): - async for page in self.pages: - for response in page.security_health_analytics_custom_modules: - 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.securitycenter_v1.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_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[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - for page in self.pages: - yield from page.list_findings_results - - 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.securitycenter_v1.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_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[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_findings_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMuteConfigsPager: - """A pager for iterating through ``list_mute_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``mute_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListMuteConfigs`` requests and continue to iterate - through the ``mute_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListMuteConfigsResponse], - request: securitycenter_service.ListMuteConfigsRequest, - response: securitycenter_service.ListMuteConfigsResponse, - *, - 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.securitycenter_v1.types.ListMuteConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListMuteConfigsResponse): - 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 = securitycenter_service.ListMuteConfigsRequest(request) - 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[securitycenter_service.ListMuteConfigsResponse]: - 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[mute_config.MuteConfig]: - for page in self.pages: - yield from page.mute_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMuteConfigsAsyncPager: - """A pager for iterating through ``list_mute_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``mute_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListMuteConfigs`` requests and continue to iterate - through the ``mute_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListMuteConfigsResponse` - attributes are available on the 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[securitycenter_service.ListMuteConfigsResponse]], - request: securitycenter_service.ListMuteConfigsRequest, - response: securitycenter_service.ListMuteConfigsResponse, - *, - 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.securitycenter_v1.types.ListMuteConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListMuteConfigsResponse): - 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 = securitycenter_service.ListMuteConfigsRequest(request) - 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[securitycenter_service.ListMuteConfigsResponse]: - 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[mute_config.MuteConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.mute_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v1.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - 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[securitycenter_service.ListNotificationConfigsResponse]: - 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[notification_config.NotificationConfig]: - for page in self.pages: - yield from page.notification_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsAsyncPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` - attributes are available on the 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[securitycenter_service.ListNotificationConfigsResponse]], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v1.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - 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[securitycenter_service.ListNotificationConfigsResponse]: - 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[notification_config.NotificationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.notification_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEffectiveSecurityHealthAnalyticsCustomModulesPager: - """A pager for iterating through ``list_effective_security_health_analytics_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``effective_security_health_analytics_custom_modules`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEffectiveSecurityHealthAnalyticsCustomModules`` requests and continue to iterate - through the ``effective_security_health_analytics_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse], - request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, - response: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse): - 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 = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) - 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[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: - 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[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: - for page in self.pages: - yield from page.effective_security_health_analytics_custom_modules - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: - """A pager for iterating through ``list_effective_security_health_analytics_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``effective_security_health_analytics_custom_modules`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEffectiveSecurityHealthAnalyticsCustomModules`` requests and continue to iterate - through the ``effective_security_health_analytics_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse` - attributes are available on the 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[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]], - request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, - response: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse): - 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 = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(request) - 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[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: - 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[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: - async def async_generator(): - async for page in self.pages: - for response in page.effective_security_health_analytics_custom_modules: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSecurityHealthAnalyticsCustomModulesPager: - """A pager for iterating through ``list_security_health_analytics_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``security_health_analytics_custom_modules`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSecurityHealthAnalyticsCustomModules`` requests and continue to iterate - through the ``security_health_analytics_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse], - request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, - response: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse): - 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 = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) - 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[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: - 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - for page in self.pages: - yield from page.security_health_analytics_custom_modules - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSecurityHealthAnalyticsCustomModulesAsyncPager: - """A pager for iterating through ``list_security_health_analytics_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``security_health_analytics_custom_modules`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSecurityHealthAnalyticsCustomModules`` requests and continue to iterate - through the ``security_health_analytics_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse` - attributes are available on the 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[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]], - request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, - response: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesResponse): - 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 = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(request) - 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[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: - 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[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - async def async_generator(): - async for page in self.pages: - for response in page.security_health_analytics_custom_modules: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` - attributes are available on the 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[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.sources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBigQueryExportsPager: - """A pager for iterating through ``list_big_query_exports`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``big_query_exports`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListBigQueryExports`` requests and continue to iterate - through the ``big_query_exports`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListBigQueryExportsResponse], - request: securitycenter_service.ListBigQueryExportsRequest, - response: securitycenter_service.ListBigQueryExportsResponse, - *, - 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.securitycenter_v1.types.ListBigQueryExportsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse): - 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 = securitycenter_service.ListBigQueryExportsRequest(request) - 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[securitycenter_service.ListBigQueryExportsResponse]: - 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[bigquery_export.BigQueryExport]: - for page in self.pages: - yield from page.big_query_exports - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBigQueryExportsAsyncPager: - """A pager for iterating through ``list_big_query_exports`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``big_query_exports`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListBigQueryExports`` requests and continue to iterate - through the ``big_query_exports`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse` - attributes are available on the 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[securitycenter_service.ListBigQueryExportsResponse]], - request: securitycenter_service.ListBigQueryExportsRequest, - response: securitycenter_service.ListBigQueryExportsResponse, - *, - 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.securitycenter_v1.types.ListBigQueryExportsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListBigQueryExportsResponse): - 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 = securitycenter_service.ListBigQueryExportsRequest(request) - 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[securitycenter_service.ListBigQueryExportsResponse]: - 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[bigquery_export.BigQueryExport]: - async def async_generator(): - async for page in self.pages: - for response in page.big_query_exports: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDescendantEventThreatDetectionCustomModulesPager: - """A pager for iterating through ``list_descendant_event_threat_detection_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``event_threat_detection_custom_modules`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDescendantEventThreatDetectionCustomModules`` requests and continue to iterate - through the ``event_threat_detection_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse], - request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, - response: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse): - 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 = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) - 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[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: - 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - for page in self.pages: - yield from page.event_threat_detection_custom_modules - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDescendantEventThreatDetectionCustomModulesAsyncPager: - """A pager for iterating through ``list_descendant_event_threat_detection_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``event_threat_detection_custom_modules`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDescendantEventThreatDetectionCustomModules`` requests and continue to iterate - through the ``event_threat_detection_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse` - attributes are available on the 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[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]], - request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, - response: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesResponse): - 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 = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(request) - 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[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: - 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - async def async_generator(): - async for page in self.pages: - for response in page.event_threat_detection_custom_modules: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEventThreatDetectionCustomModulesPager: - """A pager for iterating through ``list_event_threat_detection_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``event_threat_detection_custom_modules`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEventThreatDetectionCustomModules`` requests and continue to iterate - through the ``event_threat_detection_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListEventThreatDetectionCustomModulesResponse], - request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, - response: securitycenter_service.ListEventThreatDetectionCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse): - 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 = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) - 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[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: - 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - for page in self.pages: - yield from page.event_threat_detection_custom_modules - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEventThreatDetectionCustomModulesAsyncPager: - """A pager for iterating through ``list_event_threat_detection_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``event_threat_detection_custom_modules`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEventThreatDetectionCustomModules`` requests and continue to iterate - through the ``event_threat_detection_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse` - attributes are available on the 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[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]], - request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, - response: securitycenter_service.ListEventThreatDetectionCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesResponse): - 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 = securitycenter_service.ListEventThreatDetectionCustomModulesRequest(request) - 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[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: - 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[event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - async def async_generator(): - async for page in self.pages: - for response in page.event_threat_detection_custom_modules: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEffectiveEventThreatDetectionCustomModulesPager: - """A pager for iterating through ``list_effective_event_threat_detection_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``effective_event_threat_detection_custom_modules`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEffectiveEventThreatDetectionCustomModules`` requests and continue to iterate - through the ``effective_event_threat_detection_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse], - request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, - response: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse): - 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 = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) - 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[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: - 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[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: - for page in self.pages: - yield from page.effective_event_threat_detection_custom_modules - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEffectiveEventThreatDetectionCustomModulesAsyncPager: - """A pager for iterating through ``list_effective_event_threat_detection_custom_modules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``effective_event_threat_detection_custom_modules`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEffectiveEventThreatDetectionCustomModules`` requests and continue to iterate - through the ``effective_event_threat_detection_custom_modules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse` - attributes are available on the 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[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]], - request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, - response: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse, - *, - 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.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesResponse): - 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 = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(request) - 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[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: - 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[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: - async def async_generator(): - async for page in self.pages: - for response in page.effective_event_threat_detection_custom_modules: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourceValueConfigsPager: - """A pager for iterating through ``list_resource_value_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``resource_value_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListResourceValueConfigs`` requests and continue to iterate - through the ``resource_value_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListResourceValueConfigsResponse], - request: securitycenter_service.ListResourceValueConfigsRequest, - response: securitycenter_service.ListResourceValueConfigsResponse, - *, - 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.securitycenter_v1.types.ListResourceValueConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse): - 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 = securitycenter_service.ListResourceValueConfigsRequest(request) - 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[securitycenter_service.ListResourceValueConfigsResponse]: - 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[resource_value_config.ResourceValueConfig]: - for page in self.pages: - yield from page.resource_value_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourceValueConfigsAsyncPager: - """A pager for iterating through ``list_resource_value_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``resource_value_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListResourceValueConfigs`` requests and continue to iterate - through the ``resource_value_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse` - attributes are available on the 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[securitycenter_service.ListResourceValueConfigsResponse]], - request: securitycenter_service.ListResourceValueConfigsRequest, - response: securitycenter_service.ListResourceValueConfigsResponse, - *, - 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.securitycenter_v1.types.ListResourceValueConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListResourceValueConfigsResponse): - 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 = securitycenter_service.ListResourceValueConfigsRequest(request) - 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[securitycenter_service.ListResourceValueConfigsResponse]: - 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[resource_value_config.ResourceValueConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.resource_value_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListValuedResourcesPager: - """A pager for iterating through ``list_valued_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``valued_resources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListValuedResources`` requests and continue to iterate - through the ``valued_resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListValuedResourcesResponse], - request: securitycenter_service.ListValuedResourcesRequest, - response: securitycenter_service.ListValuedResourcesResponse, - *, - 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.securitycenter_v1.types.ListValuedResourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListValuedResourcesResponse): - 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 = securitycenter_service.ListValuedResourcesRequest(request) - 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[securitycenter_service.ListValuedResourcesResponse]: - 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[valued_resource.ValuedResource]: - for page in self.pages: - yield from page.valued_resources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListValuedResourcesAsyncPager: - """A pager for iterating through ``list_valued_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``valued_resources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListValuedResources`` requests and continue to iterate - through the ``valued_resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListValuedResourcesResponse` - attributes are available on the 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[securitycenter_service.ListValuedResourcesResponse]], - request: securitycenter_service.ListValuedResourcesRequest, - response: securitycenter_service.ListValuedResourcesResponse, - *, - 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.securitycenter_v1.types.ListValuedResourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListValuedResourcesResponse): - 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 = securitycenter_service.ListValuedResourcesRequest(request) - 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[securitycenter_service.ListValuedResourcesResponse]: - 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[valued_resource.ValuedResource]: - async def async_generator(): - async for page in self.pages: - for response in page.valued_resources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAttackPathsPager: - """A pager for iterating through ``list_attack_paths`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``attack_paths`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAttackPaths`` requests and continue to iterate - through the ``attack_paths`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListAttackPathsResponse], - request: securitycenter_service.ListAttackPathsRequest, - response: securitycenter_service.ListAttackPathsResponse, - *, - 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.securitycenter_v1.types.ListAttackPathsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListAttackPathsResponse): - 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 = securitycenter_service.ListAttackPathsRequest(request) - 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[securitycenter_service.ListAttackPathsResponse]: - 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[attack_path.AttackPath]: - for page in self.pages: - yield from page.attack_paths - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAttackPathsAsyncPager: - """A pager for iterating through ``list_attack_paths`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``attack_paths`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAttackPaths`` requests and continue to iterate - through the ``attack_paths`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListAttackPathsResponse` - attributes are available on the 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[securitycenter_service.ListAttackPathsResponse]], - request: securitycenter_service.ListAttackPathsRequest, - response: securitycenter_service.ListAttackPathsResponse, - *, - 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.securitycenter_v1.types.ListAttackPathsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListAttackPathsResponse): - 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 = securitycenter_service.ListAttackPathsRequest(request) - 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[securitycenter_service.ListAttackPathsResponse]: - 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[attack_path.AttackPath]: - async def async_generator(): - async for page in self.pages: - for response in page.attack_paths: - 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-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py deleted file mode 100644 index 9d36139c1a9b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/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 SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .rest import SecurityCenterRestTransport -from .rest import SecurityCenterRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry['grpc'] = SecurityCenterGrpcTransport -_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport -_transport_registry['rest'] = SecurityCenterRestTransport - -__all__ = ( - 'SecurityCenterTransport', - 'SecurityCenterGrpcTransport', - 'SecurityCenterGrpcAsyncIOTransport', - 'SecurityCenterRestTransport', - 'SecurityCenterRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py deleted file mode 100644 index 0e98676ba56d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py +++ /dev/null @@ -1,1251 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.securitycenter_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.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import valued_resource -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 empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'securitycenter.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.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: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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.bulk_mute_findings: gapic_v1.method.wrap_method( - self.bulk_mute_findings, - default_timeout=None, - client_info=client_info, - ), - self.create_security_health_analytics_custom_module: gapic_v1.method.wrap_method( - self.create_security_health_analytics_custom_module, - default_timeout=60.0, - client_info=client_info, - ), - self.create_source: gapic_v1.method.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.create_mute_config: gapic_v1.method.wrap_method( - self.create_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method.wrap_method( - self.create_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_mute_config: gapic_v1.method.wrap_method( - self.delete_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method.wrap_method( - self.delete_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_security_health_analytics_custom_module: gapic_v1.method.wrap_method( - self.delete_security_health_analytics_custom_module, - default_timeout=60.0, - client_info=client_info, - ), - self.get_simulation: gapic_v1.method.wrap_method( - self.get_simulation, - default_timeout=None, - client_info=client_info, - ), - self.get_valued_resource: gapic_v1.method.wrap_method( - self.get_valued_resource, - default_timeout=None, - client_info=client_info, - ), - self.get_big_query_export: gapic_v1.method.wrap_method( - self.get_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_mute_config: gapic_v1.method.wrap_method( - self.get_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.get_notification_config: gapic_v1.method.wrap_method( - self.get_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_organization_settings: gapic_v1.method.wrap_method( - self.get_organization_settings, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_effective_security_health_analytics_custom_module: gapic_v1.method.wrap_method( - self.get_effective_security_health_analytics_custom_module, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_security_health_analytics_custom_module: gapic_v1.method.wrap_method( - self.get_security_health_analytics_custom_module, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_source: gapic_v1.method.wrap_method( - self.get_source, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.group_assets: gapic_v1.method.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_descendant_security_health_analytics_custom_modules: gapic_v1.method.wrap_method( - self.list_descendant_security_health_analytics_custom_modules, - 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=60.0, - ), - default_timeout=60.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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_mute_configs: gapic_v1.method.wrap_method( - self.list_mute_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method.wrap_method( - self.list_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_effective_security_health_analytics_custom_modules: gapic_v1.method.wrap_method( - self.list_effective_security_health_analytics_custom_modules, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_security_health_analytics_custom_modules: gapic_v1.method.wrap_method( - self.list_security_health_analytics_custom_modules, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_sources: gapic_v1.method.wrap_method( - self.list_sources, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.run_asset_discovery: gapic_v1.method.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_mute: gapic_v1.method.wrap_method( - self.set_mute, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.simulate_security_health_analytics_custom_module: gapic_v1.method.wrap_method( - self.simulate_security_health_analytics_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.update_external_system: gapic_v1.method.wrap_method( - self.update_external_system, - default_timeout=None, - client_info=client_info, - ), - self.update_finding: gapic_v1.method.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_mute_config: gapic_v1.method.wrap_method( - self.update_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method.wrap_method( - self.update_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_health_analytics_custom_module: gapic_v1.method.wrap_method( - self.update_security_health_analytics_custom_module, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=client_info, - ), - self.create_big_query_export: gapic_v1.method.wrap_method( - self.create_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.delete_big_query_export: gapic_v1.method.wrap_method( - self.delete_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.update_big_query_export: gapic_v1.method.wrap_method( - self.update_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.list_big_query_exports: gapic_v1.method.wrap_method( - self.list_big_query_exports, - default_timeout=None, - client_info=client_info, - ), - self.create_event_threat_detection_custom_module: gapic_v1.method.wrap_method( - self.create_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.delete_event_threat_detection_custom_module: gapic_v1.method.wrap_method( - self.delete_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.get_event_threat_detection_custom_module: gapic_v1.method.wrap_method( - self.get_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.list_descendant_event_threat_detection_custom_modules: gapic_v1.method.wrap_method( - self.list_descendant_event_threat_detection_custom_modules, - default_timeout=None, - client_info=client_info, - ), - self.list_event_threat_detection_custom_modules: gapic_v1.method.wrap_method( - self.list_event_threat_detection_custom_modules, - default_timeout=None, - client_info=client_info, - ), - self.update_event_threat_detection_custom_module: gapic_v1.method.wrap_method( - self.update_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.validate_event_threat_detection_custom_module: gapic_v1.method.wrap_method( - self.validate_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.get_effective_event_threat_detection_custom_module: gapic_v1.method.wrap_method( - self.get_effective_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.list_effective_event_threat_detection_custom_modules: gapic_v1.method.wrap_method( - self.list_effective_event_threat_detection_custom_modules, - default_timeout=None, - client_info=client_info, - ), - self.batch_create_resource_value_configs: gapic_v1.method.wrap_method( - self.batch_create_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.delete_resource_value_config: gapic_v1.method.wrap_method( - self.delete_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.get_resource_value_config: gapic_v1.method.wrap_method( - self.get_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.list_resource_value_configs: gapic_v1.method.wrap_method( - self.list_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.update_resource_value_config: gapic_v1.method.wrap_method( - self.update_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.list_valued_resources: gapic_v1.method.wrap_method( - self.list_valued_resources, - default_timeout=None, - client_info=client_info, - ), - self.list_attack_paths: gapic_v1.method.wrap_method( - self.list_attack_paths, - 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 bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def create_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], - Union[ - gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] - ]]: - raise NotImplementedError() - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - Union[ - gcs_mute_config.MuteConfig, - Awaitable[gcs_mute_config.MuteConfig] - ]]: - raise NotImplementedError() - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def delete_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - Union[ - simulation.Simulation, - Awaitable[simulation.Simulation] - ]]: - raise NotImplementedError() - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - Union[ - valued_resource.ValuedResource, - Awaitable[valued_resource.ValuedResource] - ]]: - raise NotImplementedError() - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - Union[ - bigquery_export.BigQueryExport, - Awaitable[bigquery_export.BigQueryExport] - ]]: - 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 get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - Union[ - mute_config.MuteConfig, - Awaitable[mute_config.MuteConfig] - ]]: - raise NotImplementedError() - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Union[ - notification_config.NotificationConfig, - Awaitable[notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Union[ - organization_settings.OrganizationSettings, - Awaitable[organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def get_effective_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], - Union[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule, - Awaitable[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule] - ]]: - raise NotImplementedError() - - @property - def get_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], - Union[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - Awaitable[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] - ]]: - raise NotImplementedError() - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Union[ - source.Source, - Awaitable[source.Source] - ]]: - raise NotImplementedError() - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Union[ - securitycenter_service.GroupAssetsResponse, - Awaitable[securitycenter_service.GroupAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Union[ - securitycenter_service.GroupFindingsResponse, - Awaitable[securitycenter_service.GroupFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Union[ - securitycenter_service.ListAssetsResponse, - Awaitable[securitycenter_service.ListAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], - Union[ - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse, - Awaitable[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Union[ - securitycenter_service.ListFindingsResponse, - Awaitable[securitycenter_service.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - Union[ - securitycenter_service.ListMuteConfigsResponse, - Awaitable[securitycenter_service.ListMuteConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Union[ - securitycenter_service.ListNotificationConfigsResponse, - Awaitable[securitycenter_service.ListNotificationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_effective_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], - Union[ - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, - Awaitable[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse] - ]]: - raise NotImplementedError() - - @property - def list_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], - Union[ - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse, - Awaitable[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse] - ]]: - raise NotImplementedError() - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Union[ - securitycenter_service.ListSourcesResponse, - Awaitable[securitycenter_service.ListSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - raise NotImplementedError() - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - 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 test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - @property - def simulate_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], - Union[ - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse, - Awaitable[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse] - ]]: - raise NotImplementedError() - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - Union[ - gcs_external_system.ExternalSystem, - Awaitable[gcs_external_system.ExternalSystem] - ]]: - raise NotImplementedError() - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - Union[ - gcs_mute_config.MuteConfig, - Awaitable[gcs_mute_config.MuteConfig] - ]]: - raise NotImplementedError() - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Union[ - gcs_organization_settings.OrganizationSettings, - Awaitable[gcs_organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def update_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], - Union[ - gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] - ]]: - raise NotImplementedError() - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Union[ - gcs_security_marks.SecurityMarks, - Awaitable[gcs_security_marks.SecurityMarks] - ]]: - raise NotImplementedError() - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - Union[ - bigquery_export.BigQueryExport, - Awaitable[bigquery_export.BigQueryExport] - ]]: - raise NotImplementedError() - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - Union[ - bigquery_export.BigQueryExport, - Awaitable[bigquery_export.BigQueryExport] - ]]: - raise NotImplementedError() - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - Union[ - securitycenter_service.ListBigQueryExportsResponse, - Awaitable[securitycenter_service.ListBigQueryExportsResponse] - ]]: - raise NotImplementedError() - - @property - def create_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], - Union[ - gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, - Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] - ]]: - raise NotImplementedError() - - @property - def delete_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], - Union[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule, - Awaitable[event_threat_detection_custom_module.EventThreatDetectionCustomModule] - ]]: - raise NotImplementedError() - - @property - def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], - Union[ - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse, - Awaitable[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse] - ]]: - raise NotImplementedError() - - @property - def list_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], - Union[ - securitycenter_service.ListEventThreatDetectionCustomModulesResponse, - Awaitable[securitycenter_service.ListEventThreatDetectionCustomModulesResponse] - ]]: - raise NotImplementedError() - - @property - def update_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], - Union[ - gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, - Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] - ]]: - raise NotImplementedError() - - @property - def validate_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], - Union[ - securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse, - Awaitable[securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse] - ]]: - raise NotImplementedError() - - @property - def get_effective_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], - Union[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule, - Awaitable[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule] - ]]: - raise NotImplementedError() - - @property - def list_effective_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], - Union[ - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse, - Awaitable[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse] - ]]: - raise NotImplementedError() - - @property - def batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - Union[ - securitycenter_service.BatchCreateResourceValueConfigsResponse, - Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - Union[ - resource_value_config.ResourceValueConfig, - Awaitable[resource_value_config.ResourceValueConfig] - ]]: - raise NotImplementedError() - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - Union[ - securitycenter_service.ListResourceValueConfigsResponse, - Awaitable[securitycenter_service.ListResourceValueConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - Union[ - gcs_resource_value_config.ResourceValueConfig, - Awaitable[gcs_resource_value_config.ResourceValueConfig] - ]]: - raise NotImplementedError() - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - Union[ - securitycenter_service.ListValuedResourcesResponse, - Awaitable[securitycenter_service.ListValuedResourcesResponse] - ]]: - raise NotImplementedError() - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - Union[ - securitycenter_service.ListAttackPathsResponse, - Awaitable[securitycenter_service.ListAttackPathsResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SecurityCenterTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py deleted file mode 100644 index a8d1ee71ce17..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py +++ /dev/null @@ -1,2103 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import valued_resource -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 empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V1 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: 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 bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - operations_pb2.Operation]: - r"""Return a callable for the bulk mute findings method over gRPC. - - Kicks off an LRO to bulk mute findings for a parent - based on a filter. The parent can be either an - organization, folder or project. The findings matched by - the filter will be muted after the LRO is done. - - Returns: - Callable[[~.BulkMuteFindingsRequest], - ~.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 'bulk_mute_findings' not in self._stubs: - self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/BulkMuteFindings', - request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['bulk_mute_findings'] - - @property - def create_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], - gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - r"""Return a callable for the create security health - analytics custom module method over gRPC. - - Creates a resident - SecurityHealthAnalyticsCustomModule at the scope of the - given CRM parent, and also creates inherited - SecurityHealthAnalyticsCustomModules for all CRM - descendants of the given parent. These modules are - enabled by default. - - Returns: - Callable[[~.CreateSecurityHealthAnalyticsCustomModuleRequest], - ~.SecurityHealthAnalyticsCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: - self._stubs['create_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['create_security_health_analytics_custom_module'] - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - r"""Return a callable for the create mute config method over gRPC. - - Creates a mute config. - - Returns: - Callable[[~.CreateMuteConfigRequest], - ~.MuteConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateMuteConfig', - request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['create_mute_config'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete mute config method over gRPC. - - Deletes an existing mute config. - - Returns: - Callable[[~.DeleteMuteConfigRequest], - ~.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_mute_config' not in self._stubs: - self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteMuteConfig', - request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_mute_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - ~.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_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @property - def delete_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete security health - analytics custom module method over gRPC. - - Deletes the specified - SecurityHealthAnalyticsCustomModule and all of its - descendants in the CRM hierarchy. This method is only - supported for resident custom modules. - - Returns: - Callable[[~.DeleteSecurityHealthAnalyticsCustomModuleRequest], - ~.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_security_health_analytics_custom_module' not in self._stubs: - self._stubs['delete_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_security_health_analytics_custom_module'] - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - simulation.Simulation]: - r"""Return a callable for the get simulation method over gRPC. - - Get the simulation by name or the latest simulation - for the given organization. - - Returns: - Callable[[~.GetSimulationRequest], - ~.Simulation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_simulation' not in self._stubs: - self._stubs['get_simulation'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSimulation', - request_serializer=securitycenter_service.GetSimulationRequest.serialize, - response_deserializer=simulation.Simulation.deserialize, - ) - return self._stubs['get_simulation'] - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - valued_resource.ValuedResource]: - r"""Return a callable for the get valued resource method over gRPC. - - Get the valued resource by name - - Returns: - Callable[[~.GetValuedResourceRequest], - ~.ValuedResource]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_valued_resource' not in self._stubs: - self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetValuedResource', - request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, - response_deserializer=valued_resource.ValuedResource.deserialize, - ) - return self._stubs['get_valued_resource'] - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - bigquery_export.BigQueryExport]: - r"""Return a callable for the get big query export method over gRPC. - - Gets a BigQuery export. - - Returns: - Callable[[~.GetBigQueryExportRequest], - ~.BigQueryExport]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_big_query_export' not in self._stubs: - self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetBigQueryExport', - request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['get_big_query_export'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - mute_config.MuteConfig]: - r"""Return a callable for the get mute config method over gRPC. - - Gets a mute config. - - Returns: - Callable[[~.GetMuteConfigRequest], - ~.MuteConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_mute_config' not in self._stubs: - self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetMuteConfig', - request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, - response_deserializer=mute_config.MuteConfig.deserialize, - ) - return self._stubs['get_mute_config'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_effective_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: - r"""Return a callable for the get effective security health - analytics custom module method over gRPC. - - Retrieves an - EffectiveSecurityHealthAnalyticsCustomModule. - - Returns: - Callable[[~.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], - ~.EffectiveSecurityHealthAnalyticsCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_effective_security_health_analytics_custom_module' not in self._stubs: - self._stubs['get_effective_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['get_effective_security_health_analytics_custom_module'] - - @property - def get_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - r"""Return a callable for the get security health analytics - custom module method over gRPC. - - Retrieves a SecurityHealthAnalyticsCustomModule. - - Returns: - Callable[[~.GetSecurityHealthAnalyticsCustomModuleRequest], - ~.SecurityHealthAnalyticsCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_security_health_analytics_custom_module' not in self._stubs: - self._stubs['get_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['get_security_health_analytics_custom_module'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - ~.GroupAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: - r"""Return a callable for the list descendant security - health analytics custom modules method over gRPC. - - Returns a list of all resident - SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent’s CRM descendants. - - Returns: - Callable[[~.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], - ~.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_descendant_security_health_analytics_custom_modules' not in self._stubs: - self._stubs['list_descendant_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantSecurityHealthAnalyticsCustomModules', - request_serializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.deserialize, - ) - return self._stubs['list_descendant_security_health_analytics_custom_modules'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - 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.securitycenter.v1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - securitycenter_service.ListMuteConfigsResponse]: - r"""Return a callable for the list mute configs method over gRPC. - - Lists mute configs. - - Returns: - Callable[[~.ListMuteConfigsRequest], - ~.ListMuteConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_mute_configs' not in self._stubs: - self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListMuteConfigs', - request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, - ) - return self._stubs['list_mute_configs'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - ~.ListNotificationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_effective_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: - r"""Return a callable for the list effective security health - analytics custom modules method over gRPC. - - Returns a list of all - EffectiveSecurityHealthAnalyticsCustomModules for the - given parent. This includes resident modules defined at - the scope of the parent, and inherited modules, - inherited from CRM ancestors. - - Returns: - Callable[[~.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], - ~.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_effective_security_health_analytics_custom_modules' not in self._stubs: - self._stubs['list_effective_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveSecurityHealthAnalyticsCustomModules', - request_serializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.deserialize, - ) - return self._stubs['list_effective_security_health_analytics_custom_modules'] - - @property - def list_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: - r"""Return a callable for the list security health analytics - custom modules method over gRPC. - - Returns a list of all - SecurityHealthAnalyticsCustomModules for the given - parent. This includes resident modules defined at the - scope of the parent, and inherited modules, inherited - from CRM ancestors. - - Returns: - Callable[[~.ListSecurityHealthAnalyticsCustomModulesRequest], - ~.ListSecurityHealthAnalyticsCustomModulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_security_health_analytics_custom_modules' not in self._stubs: - self._stubs['list_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListSecurityHealthAnalyticsCustomModules', - request_serializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.deserialize, - ) - return self._stubs['list_security_health_analytics_custom_modules'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - operations_pb2.Operation]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - ~.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 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - ~.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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - finding.Finding]: - r"""Return a callable for the set mute method over gRPC. - - Updates the mute state of a finding. - - Returns: - Callable[[~.SetMuteRequest], - ~.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 'set_mute' not in self._stubs: - self._stubs['set_mute'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SetMute', - request_serializer=securitycenter_service.SetMuteRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_mute'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def simulate_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse]: - r"""Return a callable for the simulate security health - analytics custom module method over gRPC. - - Simulates a given SecurityHealthAnalyticsCustomModule - and Resource. - - Returns: - Callable[[~.SimulateSecurityHealthAnalyticsCustomModuleRequest], - ~.SimulateSecurityHealthAnalyticsCustomModuleResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'simulate_security_health_analytics_custom_module' not in self._stubs: - self._stubs['simulate_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SimulateSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.deserialize, - ) - return self._stubs['simulate_security_health_analytics_custom_module'] - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - gcs_external_system.ExternalSystem]: - r"""Return a callable for the update external system method over gRPC. - - Updates external system. This is for a given finding. - - Returns: - Callable[[~.UpdateExternalSystemRequest], - ~.ExternalSystem]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_external_system' not in self._stubs: - self._stubs['update_external_system'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateExternalSystem', - request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, - response_deserializer=gcs_external_system.ExternalSystem.deserialize, - ) - return self._stubs['update_external_system'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - r"""Return a callable for the update mute config method over gRPC. - - Updates a mute config. - - Returns: - Callable[[~.UpdateMuteConfigRequest], - ~.MuteConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateMuteConfig', - request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['update_mute_config'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], - gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - r"""Return a callable for the update security health - analytics custom module method over gRPC. - - Updates the SecurityHealthAnalyticsCustomModule under - the given name based on the given update mask. Updating - the enablement state is supported on both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name and custom config of a module is supported - on resident modules only. - - Returns: - Callable[[~.UpdateSecurityHealthAnalyticsCustomModuleRequest], - ~.SecurityHealthAnalyticsCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: - self._stubs['update_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['update_security_health_analytics_custom_module'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - r"""Return a callable for the create big query export method over gRPC. - - Creates a BigQuery export. - - Returns: - Callable[[~.CreateBigQueryExportRequest], - ~.BigQueryExport]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateBigQueryExport', - request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['create_big_query_export'] - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete big query export method over gRPC. - - Deletes an existing BigQuery export. - - Returns: - Callable[[~.DeleteBigQueryExportRequest], - ~.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_big_query_export' not in self._stubs: - self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteBigQueryExport', - request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_big_query_export'] - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - r"""Return a callable for the update big query export method over gRPC. - - Updates a BigQuery export. - - Returns: - Callable[[~.UpdateBigQueryExportRequest], - ~.BigQueryExport]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateBigQueryExport', - request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['update_big_query_export'] - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - securitycenter_service.ListBigQueryExportsResponse]: - r"""Return a callable for the list big query exports method over gRPC. - - Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are returned. - - Returns: - Callable[[~.ListBigQueryExportsRequest], - ~.ListBigQueryExportsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_big_query_exports' not in self._stubs: - self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListBigQueryExports', - request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, - response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, - ) - return self._stubs['list_big_query_exports'] - - @property - def create_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], - gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - r"""Return a callable for the create event threat detection - custom module method over gRPC. - - Creates a resident Event Threat Detection custom - module at the scope of the given Resource Manager - parent, and also creates inherited custom modules for - all descendants of the given parent. These modules are - enabled by default. - - Returns: - Callable[[~.CreateEventThreatDetectionCustomModuleRequest], - ~.EventThreatDetectionCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['create_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['create_event_threat_detection_custom_module'] - - @property - def delete_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete event threat detection - custom module method over gRPC. - - Deletes the specified Event Threat Detection custom - module and all of its descendants in the Resource - Manager hierarchy. This method is only supported for - resident custom modules. - - Returns: - Callable[[~.DeleteEventThreatDetectionCustomModuleRequest], - ~.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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['delete_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_event_threat_detection_custom_module'] - - @property - def get_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], - event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - r"""Return a callable for the get event threat detection - custom module method over gRPC. - - Gets an Event Threat Detection custom module. - - Returns: - Callable[[~.GetEventThreatDetectionCustomModuleRequest], - ~.EventThreatDetectionCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_event_threat_detection_custom_module' not in self._stubs: - self._stubs['get_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.GetEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['get_event_threat_detection_custom_module'] - - @property - def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: - r"""Return a callable for the list descendant event threat - detection custom modules method over gRPC. - - Lists all resident Event Threat Detection custom - modules under the given Resource Manager parent and its - descendants. - - Returns: - Callable[[~.ListDescendantEventThreatDetectionCustomModulesRequest], - ~.ListDescendantEventThreatDetectionCustomModulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_descendant_event_threat_detection_custom_modules' not in self._stubs: - self._stubs['list_descendant_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantEventThreatDetectionCustomModules', - request_serializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.deserialize, - ) - return self._stubs['list_descendant_event_threat_detection_custom_modules'] - - @property - def list_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], - securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: - r"""Return a callable for the list event threat detection - custom modules method over gRPC. - - Lists all Event Threat Detection custom modules for - the given Resource Manager parent. This includes - resident modules defined at the scope of the parent - along with modules inherited from ancestors. - - Returns: - Callable[[~.ListEventThreatDetectionCustomModulesRequest], - ~.ListEventThreatDetectionCustomModulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_event_threat_detection_custom_modules' not in self._stubs: - self._stubs['list_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListEventThreatDetectionCustomModules', - request_serializer=securitycenter_service.ListEventThreatDetectionCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListEventThreatDetectionCustomModulesResponse.deserialize, - ) - return self._stubs['list_event_threat_detection_custom_modules'] - - @property - def update_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], - gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - r"""Return a callable for the update event threat detection - custom module method over gRPC. - - Updates the Event Threat Detection custom module with - the given name based on the given update mask. Updating - the enablement state is supported for both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name or configuration of a module is supported - for resident modules only. The type of a module cannot - be changed. - - Returns: - Callable[[~.UpdateEventThreatDetectionCustomModuleRequest], - ~.EventThreatDetectionCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['update_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['update_event_threat_detection_custom_module'] - - @property - def validate_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], - securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse]: - r"""Return a callable for the validate event threat - detection custom module method over gRPC. - - Validates the given Event Threat Detection custom - module. - - Returns: - Callable[[~.ValidateEventThreatDetectionCustomModuleRequest], - ~.ValidateEventThreatDetectionCustomModuleResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['validate_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ValidateEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.deserialize, - ) - return self._stubs['validate_event_threat_detection_custom_module'] - - @property - def get_effective_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: - r"""Return a callable for the get effective event threat - detection custom module method over gRPC. - - Gets an effective Event Threat Detection custom - module at the given level. - - Returns: - Callable[[~.GetEffectiveEventThreatDetectionCustomModuleRequest], - ~.EffectiveEventThreatDetectionCustomModule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_effective_event_threat_detection_custom_module' not in self._stubs: - self._stubs['get_effective_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['get_effective_event_threat_detection_custom_module'] - - @property - def list_effective_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: - r"""Return a callable for the list effective event threat - detection custom modules method over gRPC. - - Lists all effective Event Threat Detection custom - modules for the given parent. This includes resident - modules defined at the scope of the parent along with - modules inherited from its ancestors. - - Returns: - Callable[[~.ListEffectiveEventThreatDetectionCustomModulesRequest], - ~.ListEffectiveEventThreatDetectionCustomModulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_effective_event_threat_detection_custom_modules' not in self._stubs: - self._stubs['list_effective_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveEventThreatDetectionCustomModules', - request_serializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.deserialize, - ) - return self._stubs['list_effective_event_threat_detection_custom_modules'] - - @property - def batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - securitycenter_service.BatchCreateResourceValueConfigsResponse]: - r"""Return a callable for the batch create resource value - configs method over gRPC. - - Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - Returns: - Callable[[~.BatchCreateResourceValueConfigsRequest], - ~.BatchCreateResourceValueConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: - self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/BatchCreateResourceValueConfigs', - request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, - ) - return self._stubs['batch_create_resource_value_configs'] - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete resource value config method over gRPC. - - Deletes a ResourceValueConfig. - - Returns: - Callable[[~.DeleteResourceValueConfigRequest], - ~.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_resource_value_config' not in self._stubs: - self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteResourceValueConfig', - request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_resource_value_config'] - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - resource_value_config.ResourceValueConfig]: - r"""Return a callable for the get resource value config method over gRPC. - - Gets a ResourceValueConfig. - - Returns: - Callable[[~.GetResourceValueConfigRequest], - ~.ResourceValueConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_resource_value_config' not in self._stubs: - self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetResourceValueConfig', - request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, - response_deserializer=resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['get_resource_value_config'] - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - securitycenter_service.ListResourceValueConfigsResponse]: - r"""Return a callable for the list resource value configs method over gRPC. - - Lists all ResourceValueConfigs. - - Returns: - Callable[[~.ListResourceValueConfigsRequest], - ~.ListResourceValueConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_resource_value_configs' not in self._stubs: - self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListResourceValueConfigs', - request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, - ) - return self._stubs['list_resource_value_configs'] - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - gcs_resource_value_config.ResourceValueConfig]: - r"""Return a callable for the update resource value config method over gRPC. - - Updates an existing ResourceValueConfigs with new - rules. - - Returns: - Callable[[~.UpdateResourceValueConfigRequest], - ~.ResourceValueConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: - self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateResourceValueConfig', - request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, - response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['update_resource_value_config'] - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - securitycenter_service.ListValuedResourcesResponse]: - r"""Return a callable for the list valued resources method over gRPC. - - Lists the valued resources for a set of simulation - results and filter. - - Returns: - Callable[[~.ListValuedResourcesRequest], - ~.ListValuedResourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_valued_resources' not in self._stubs: - self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListValuedResources', - request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, - response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, - ) - return self._stubs['list_valued_resources'] - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - securitycenter_service.ListAttackPathsResponse]: - r"""Return a callable for the list attack paths method over gRPC. - - Lists the attack paths for a set of simulation - results or valued resources and filter. - - Returns: - Callable[[~.ListAttackPathsRequest], - ~.ListAttackPathsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_attack_paths' not in self._stubs: - self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListAttackPaths', - request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, - response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, - ) - return self._stubs['list_attack_paths'] - - 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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SecurityCenterGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index 9e0a84336159..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,2583 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import valued_resource -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 empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V1 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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._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 bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the bulk mute findings method over gRPC. - - Kicks off an LRO to bulk mute findings for a parent - based on a filter. The parent can be either an - organization, folder or project. The findings matched by - the filter will be muted after the LRO is done. - - Returns: - Callable[[~.BulkMuteFindingsRequest], - 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 'bulk_mute_findings' not in self._stubs: - self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/BulkMuteFindings', - request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['bulk_mute_findings'] - - @property - def create_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]]: - r"""Return a callable for the create security health - analytics custom module method over gRPC. - - Creates a resident - SecurityHealthAnalyticsCustomModule at the scope of the - given CRM parent, and also creates inherited - SecurityHealthAnalyticsCustomModules for all CRM - descendants of the given parent. These modules are - enabled by default. - - Returns: - Callable[[~.CreateSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[~.SecurityHealthAnalyticsCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: - self._stubs['create_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['create_security_health_analytics_custom_module'] - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - 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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - Awaitable[gcs_mute_config.MuteConfig]]: - r"""Return a callable for the create mute config method over gRPC. - - Creates a mute config. - - Returns: - Callable[[~.CreateMuteConfigRequest], - Awaitable[~.MuteConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateMuteConfig', - request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['create_mute_config'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete mute config method over gRPC. - - Deletes an existing mute config. - - Returns: - Callable[[~.DeleteMuteConfigRequest], - 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_mute_config' not in self._stubs: - self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteMuteConfig', - request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_mute_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - 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_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @property - def delete_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete security health - analytics custom module method over gRPC. - - Deletes the specified - SecurityHealthAnalyticsCustomModule and all of its - descendants in the CRM hierarchy. This method is only - supported for resident custom modules. - - Returns: - Callable[[~.DeleteSecurityHealthAnalyticsCustomModuleRequest], - 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_security_health_analytics_custom_module' not in self._stubs: - self._stubs['delete_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_security_health_analytics_custom_module'] - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - Awaitable[simulation.Simulation]]: - r"""Return a callable for the get simulation method over gRPC. - - Get the simulation by name or the latest simulation - for the given organization. - - Returns: - Callable[[~.GetSimulationRequest], - Awaitable[~.Simulation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_simulation' not in self._stubs: - self._stubs['get_simulation'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSimulation', - request_serializer=securitycenter_service.GetSimulationRequest.serialize, - response_deserializer=simulation.Simulation.deserialize, - ) - return self._stubs['get_simulation'] - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - Awaitable[valued_resource.ValuedResource]]: - r"""Return a callable for the get valued resource method over gRPC. - - Get the valued resource by name - - Returns: - Callable[[~.GetValuedResourceRequest], - Awaitable[~.ValuedResource]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_valued_resource' not in self._stubs: - self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetValuedResource', - request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, - response_deserializer=valued_resource.ValuedResource.deserialize, - ) - return self._stubs['get_valued_resource'] - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - Awaitable[bigquery_export.BigQueryExport]]: - r"""Return a callable for the get big query export method over gRPC. - - Gets a BigQuery export. - - Returns: - Callable[[~.GetBigQueryExportRequest], - Awaitable[~.BigQueryExport]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_big_query_export' not in self._stubs: - self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetBigQueryExport', - request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['get_big_query_export'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - Awaitable[mute_config.MuteConfig]]: - r"""Return a callable for the get mute config method over gRPC. - - Gets a mute config. - - Returns: - Callable[[~.GetMuteConfigRequest], - Awaitable[~.MuteConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_mute_config' not in self._stubs: - self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetMuteConfig', - request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, - response_deserializer=mute_config.MuteConfig.deserialize, - ) - return self._stubs['get_mute_config'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Awaitable[notification_config.NotificationConfig]]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Awaitable[organization_settings.OrganizationSettings]]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_effective_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]]: - r"""Return a callable for the get effective security health - analytics custom module method over gRPC. - - Retrieves an - EffectiveSecurityHealthAnalyticsCustomModule. - - Returns: - Callable[[~.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[~.EffectiveSecurityHealthAnalyticsCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_effective_security_health_analytics_custom_module' not in self._stubs: - self._stubs['get_effective_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['get_effective_security_health_analytics_custom_module'] - - @property - def get_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]]: - r"""Return a callable for the get security health analytics - custom module method over gRPC. - - Retrieves a SecurityHealthAnalyticsCustomModule. - - Returns: - Callable[[~.GetSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[~.SecurityHealthAnalyticsCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_security_health_analytics_custom_module' not in self._stubs: - self._stubs['get_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['get_security_health_analytics_custom_module'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Awaitable[securitycenter_service.GroupAssetsResponse]]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - Awaitable[~.GroupAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse]]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Awaitable[securitycenter_service.ListAssetsResponse]]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], - Awaitable[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]]: - r"""Return a callable for the list descendant security - health analytics custom modules method over gRPC. - - Returns a list of all resident - SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent’s CRM descendants. - - Returns: - Callable[[~.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], - Awaitable[~.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_descendant_security_health_analytics_custom_modules' not in self._stubs: - self._stubs['list_descendant_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantSecurityHealthAnalyticsCustomModules', - request_serializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.deserialize, - ) - return self._stubs['list_descendant_security_health_analytics_custom_modules'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - 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.securitycenter.v1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - Awaitable[securitycenter_service.ListMuteConfigsResponse]]: - r"""Return a callable for the list mute configs method over gRPC. - - Lists mute configs. - - Returns: - Callable[[~.ListMuteConfigsRequest], - Awaitable[~.ListMuteConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_mute_configs' not in self._stubs: - self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListMuteConfigs', - request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, - ) - return self._stubs['list_mute_configs'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - Awaitable[~.ListNotificationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_effective_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], - Awaitable[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]]: - r"""Return a callable for the list effective security health - analytics custom modules method over gRPC. - - Returns a list of all - EffectiveSecurityHealthAnalyticsCustomModules for the - given parent. This includes resident modules defined at - the scope of the parent, and inherited modules, - inherited from CRM ancestors. - - Returns: - Callable[[~.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], - Awaitable[~.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_effective_security_health_analytics_custom_modules' not in self._stubs: - self._stubs['list_effective_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveSecurityHealthAnalyticsCustomModules', - request_serializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.deserialize, - ) - return self._stubs['list_effective_security_health_analytics_custom_modules'] - - @property - def list_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], - Awaitable[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]]: - r"""Return a callable for the list security health analytics - custom modules method over gRPC. - - Returns a list of all - SecurityHealthAnalyticsCustomModules for the given - parent. This includes resident modules defined at the - scope of the parent, and inherited modules, inherited - from CRM ancestors. - - Returns: - Callable[[~.ListSecurityHealthAnalyticsCustomModulesRequest], - Awaitable[~.ListSecurityHealthAnalyticsCustomModulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_security_health_analytics_custom_modules' not in self._stubs: - self._stubs['list_security_health_analytics_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListSecurityHealthAnalyticsCustomModules', - request_serializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.deserialize, - ) - return self._stubs['list_security_health_analytics_custom_modules'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse]]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - 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 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - 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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set mute method over gRPC. - - Updates the mute state of a finding. - - Returns: - Callable[[~.SetMuteRequest], - 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 'set_mute' not in self._stubs: - self._stubs['set_mute'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SetMute', - request_serializer=securitycenter_service.SetMuteRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_mute'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.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.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def simulate_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse]]: - r"""Return a callable for the simulate security health - analytics custom module method over gRPC. - - Simulates a given SecurityHealthAnalyticsCustomModule - and Resource. - - Returns: - Callable[[~.SimulateSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[~.SimulateSecurityHealthAnalyticsCustomModuleResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'simulate_security_health_analytics_custom_module' not in self._stubs: - self._stubs['simulate_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SimulateSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.deserialize, - ) - return self._stubs['simulate_security_health_analytics_custom_module'] - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - Awaitable[gcs_external_system.ExternalSystem]]: - r"""Return a callable for the update external system method over gRPC. - - Updates external system. This is for a given finding. - - Returns: - Callable[[~.UpdateExternalSystemRequest], - Awaitable[~.ExternalSystem]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_external_system' not in self._stubs: - self._stubs['update_external_system'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateExternalSystem', - request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, - response_deserializer=gcs_external_system.ExternalSystem.deserialize, - ) - return self._stubs['update_external_system'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - 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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - Awaitable[gcs_mute_config.MuteConfig]]: - r"""Return a callable for the update mute config method over gRPC. - - Updates a mute config. - - Returns: - Callable[[~.UpdateMuteConfigRequest], - Awaitable[~.MuteConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateMuteConfig', - request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['update_mute_config'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Awaitable[gcs_organization_settings.OrganizationSettings]]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]]: - r"""Return a callable for the update security health - analytics custom module method over gRPC. - - Updates the SecurityHealthAnalyticsCustomModule under - the given name based on the given update mask. Updating - the enablement state is supported on both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name and custom config of a module is supported - on resident modules only. - - Returns: - Callable[[~.UpdateSecurityHealthAnalyticsCustomModuleRequest], - Awaitable[~.SecurityHealthAnalyticsCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_health_analytics_custom_module' not in self._stubs: - self._stubs['update_security_health_analytics_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityHealthAnalyticsCustomModule', - request_serializer=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.serialize, - response_deserializer=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.deserialize, - ) - return self._stubs['update_security_health_analytics_custom_module'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks]]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - Awaitable[bigquery_export.BigQueryExport]]: - r"""Return a callable for the create big query export method over gRPC. - - Creates a BigQuery export. - - Returns: - Callable[[~.CreateBigQueryExportRequest], - Awaitable[~.BigQueryExport]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateBigQueryExport', - request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['create_big_query_export'] - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete big query export method over gRPC. - - Deletes an existing BigQuery export. - - Returns: - Callable[[~.DeleteBigQueryExportRequest], - 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_big_query_export' not in self._stubs: - self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteBigQueryExport', - request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_big_query_export'] - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - Awaitable[bigquery_export.BigQueryExport]]: - r"""Return a callable for the update big query export method over gRPC. - - Updates a BigQuery export. - - Returns: - Callable[[~.UpdateBigQueryExportRequest], - Awaitable[~.BigQueryExport]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateBigQueryExport', - request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['update_big_query_export'] - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - Awaitable[securitycenter_service.ListBigQueryExportsResponse]]: - r"""Return a callable for the list big query exports method over gRPC. - - Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are returned. - - Returns: - Callable[[~.ListBigQueryExportsRequest], - Awaitable[~.ListBigQueryExportsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_big_query_exports' not in self._stubs: - self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListBigQueryExports', - request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, - response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, - ) - return self._stubs['list_big_query_exports'] - - @property - def create_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], - Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]]: - r"""Return a callable for the create event threat detection - custom module method over gRPC. - - Creates a resident Event Threat Detection custom - module at the scope of the given Resource Manager - parent, and also creates inherited custom modules for - all descendants of the given parent. These modules are - enabled by default. - - Returns: - Callable[[~.CreateEventThreatDetectionCustomModuleRequest], - Awaitable[~.EventThreatDetectionCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['create_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['create_event_threat_detection_custom_module'] - - @property - def delete_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete event threat detection - custom module method over gRPC. - - Deletes the specified Event Threat Detection custom - module and all of its descendants in the Resource - Manager hierarchy. This method is only supported for - resident custom modules. - - Returns: - Callable[[~.DeleteEventThreatDetectionCustomModuleRequest], - 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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['delete_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_event_threat_detection_custom_module'] - - @property - def get_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], - Awaitable[event_threat_detection_custom_module.EventThreatDetectionCustomModule]]: - r"""Return a callable for the get event threat detection - custom module method over gRPC. - - Gets an Event Threat Detection custom module. - - Returns: - Callable[[~.GetEventThreatDetectionCustomModuleRequest], - Awaitable[~.EventThreatDetectionCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_event_threat_detection_custom_module' not in self._stubs: - self._stubs['get_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.GetEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['get_event_threat_detection_custom_module'] - - @property - def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], - Awaitable[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]]: - r"""Return a callable for the list descendant event threat - detection custom modules method over gRPC. - - Lists all resident Event Threat Detection custom - modules under the given Resource Manager parent and its - descendants. - - Returns: - Callable[[~.ListDescendantEventThreatDetectionCustomModulesRequest], - Awaitable[~.ListDescendantEventThreatDetectionCustomModulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_descendant_event_threat_detection_custom_modules' not in self._stubs: - self._stubs['list_descendant_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListDescendantEventThreatDetectionCustomModules', - request_serializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.deserialize, - ) - return self._stubs['list_descendant_event_threat_detection_custom_modules'] - - @property - def list_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], - Awaitable[securitycenter_service.ListEventThreatDetectionCustomModulesResponse]]: - r"""Return a callable for the list event threat detection - custom modules method over gRPC. - - Lists all Event Threat Detection custom modules for - the given Resource Manager parent. This includes - resident modules defined at the scope of the parent - along with modules inherited from ancestors. - - Returns: - Callable[[~.ListEventThreatDetectionCustomModulesRequest], - Awaitable[~.ListEventThreatDetectionCustomModulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_event_threat_detection_custom_modules' not in self._stubs: - self._stubs['list_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListEventThreatDetectionCustomModules', - request_serializer=securitycenter_service.ListEventThreatDetectionCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListEventThreatDetectionCustomModulesResponse.deserialize, - ) - return self._stubs['list_event_threat_detection_custom_modules'] - - @property - def update_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], - Awaitable[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]]: - r"""Return a callable for the update event threat detection - custom module method over gRPC. - - Updates the Event Threat Detection custom module with - the given name based on the given update mask. Updating - the enablement state is supported for both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name or configuration of a module is supported - for resident modules only. The type of a module cannot - be changed. - - Returns: - Callable[[~.UpdateEventThreatDetectionCustomModuleRequest], - Awaitable[~.EventThreatDetectionCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['update_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['update_event_threat_detection_custom_module'] - - @property - def validate_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], - Awaitable[securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse]]: - r"""Return a callable for the validate event threat - detection custom module method over gRPC. - - Validates the given Event Threat Detection custom - module. - - Returns: - Callable[[~.ValidateEventThreatDetectionCustomModuleRequest], - Awaitable[~.ValidateEventThreatDetectionCustomModuleResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_event_threat_detection_custom_module' not in self._stubs: - self._stubs['validate_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ValidateEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.deserialize, - ) - return self._stubs['validate_event_threat_detection_custom_module'] - - @property - def get_effective_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], - Awaitable[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]]: - r"""Return a callable for the get effective event threat - detection custom module method over gRPC. - - Gets an effective Event Threat Detection custom - module at the given level. - - Returns: - Callable[[~.GetEffectiveEventThreatDetectionCustomModuleRequest], - Awaitable[~.EffectiveEventThreatDetectionCustomModule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_effective_event_threat_detection_custom_module' not in self._stubs: - self._stubs['get_effective_event_threat_detection_custom_module'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetEffectiveEventThreatDetectionCustomModule', - request_serializer=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.serialize, - response_deserializer=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.deserialize, - ) - return self._stubs['get_effective_event_threat_detection_custom_module'] - - @property - def list_effective_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], - Awaitable[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]]: - r"""Return a callable for the list effective event threat - detection custom modules method over gRPC. - - Lists all effective Event Threat Detection custom - modules for the given parent. This includes resident - modules defined at the scope of the parent along with - modules inherited from its ancestors. - - Returns: - Callable[[~.ListEffectiveEventThreatDetectionCustomModulesRequest], - Awaitable[~.ListEffectiveEventThreatDetectionCustomModulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_effective_event_threat_detection_custom_modules' not in self._stubs: - self._stubs['list_effective_event_threat_detection_custom_modules'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListEffectiveEventThreatDetectionCustomModules', - request_serializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.serialize, - response_deserializer=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.deserialize, - ) - return self._stubs['list_effective_event_threat_detection_custom_modules'] - - @property - def batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse]]: - r"""Return a callable for the batch create resource value - configs method over gRPC. - - Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - Returns: - Callable[[~.BatchCreateResourceValueConfigsRequest], - Awaitable[~.BatchCreateResourceValueConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: - self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/BatchCreateResourceValueConfigs', - request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, - ) - return self._stubs['batch_create_resource_value_configs'] - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete resource value config method over gRPC. - - Deletes a ResourceValueConfig. - - Returns: - Callable[[~.DeleteResourceValueConfigRequest], - 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_resource_value_config' not in self._stubs: - self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteResourceValueConfig', - request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_resource_value_config'] - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - Awaitable[resource_value_config.ResourceValueConfig]]: - r"""Return a callable for the get resource value config method over gRPC. - - Gets a ResourceValueConfig. - - Returns: - Callable[[~.GetResourceValueConfigRequest], - Awaitable[~.ResourceValueConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_resource_value_config' not in self._stubs: - self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetResourceValueConfig', - request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, - response_deserializer=resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['get_resource_value_config'] - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - Awaitable[securitycenter_service.ListResourceValueConfigsResponse]]: - r"""Return a callable for the list resource value configs method over gRPC. - - Lists all ResourceValueConfigs. - - Returns: - Callable[[~.ListResourceValueConfigsRequest], - Awaitable[~.ListResourceValueConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_resource_value_configs' not in self._stubs: - self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListResourceValueConfigs', - request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, - ) - return self._stubs['list_resource_value_configs'] - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - Awaitable[gcs_resource_value_config.ResourceValueConfig]]: - r"""Return a callable for the update resource value config method over gRPC. - - Updates an existing ResourceValueConfigs with new - rules. - - Returns: - Callable[[~.UpdateResourceValueConfigRequest], - Awaitable[~.ResourceValueConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: - self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateResourceValueConfig', - request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, - response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['update_resource_value_config'] - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - Awaitable[securitycenter_service.ListValuedResourcesResponse]]: - r"""Return a callable for the list valued resources method over gRPC. - - Lists the valued resources for a set of simulation - results and filter. - - Returns: - Callable[[~.ListValuedResourcesRequest], - Awaitable[~.ListValuedResourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_valued_resources' not in self._stubs: - self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListValuedResources', - request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, - response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, - ) - return self._stubs['list_valued_resources'] - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - Awaitable[securitycenter_service.ListAttackPathsResponse]]: - r"""Return a callable for the list attack paths method over gRPC. - - Lists the attack paths for a set of simulation - results or valued resources and filter. - - Returns: - Callable[[~.ListAttackPathsRequest], - Awaitable[~.ListAttackPathsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_attack_paths' not in self._stubs: - self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListAttackPaths', - request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, - response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, - ) - return self._stubs['list_attack_paths'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.bulk_mute_findings: gapic_v1.method_async.wrap_method( - self.bulk_mute_findings, - default_timeout=None, - client_info=client_info, - ), - self.create_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( - self.create_security_health_analytics_custom_module, - default_timeout=60.0, - client_info=client_info, - ), - self.create_source: gapic_v1.method_async.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method_async.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.create_mute_config: gapic_v1.method_async.wrap_method( - self.create_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method_async.wrap_method( - self.create_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_mute_config: gapic_v1.method_async.wrap_method( - self.delete_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method_async.wrap_method( - self.delete_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( - self.delete_security_health_analytics_custom_module, - default_timeout=60.0, - client_info=client_info, - ), - self.get_simulation: gapic_v1.method_async.wrap_method( - self.get_simulation, - default_timeout=None, - client_info=client_info, - ), - self.get_valued_resource: gapic_v1.method_async.wrap_method( - self.get_valued_resource, - default_timeout=None, - client_info=client_info, - ), - self.get_big_query_export: gapic_v1.method_async.wrap_method( - self.get_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( - self.get_iam_policy, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_mute_config: gapic_v1.method_async.wrap_method( - self.get_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.get_notification_config: gapic_v1.method_async.wrap_method( - self.get_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_organization_settings: gapic_v1.method_async.wrap_method( - self.get_organization_settings, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_effective_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( - self.get_effective_security_health_analytics_custom_module, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( - self.get_security_health_analytics_custom_module, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_source: gapic_v1.method_async.wrap_method( - self.get_source, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.group_assets: gapic_v1.method_async.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method_async.wrap_method( - self.group_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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method_async.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_descendant_security_health_analytics_custom_modules: gapic_v1.method_async.wrap_method( - self.list_descendant_security_health_analytics_custom_modules, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method_async.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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_mute_configs: gapic_v1.method_async.wrap_method( - self.list_mute_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method_async.wrap_method( - self.list_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_effective_security_health_analytics_custom_modules: gapic_v1.method_async.wrap_method( - self.list_effective_security_health_analytics_custom_modules, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_security_health_analytics_custom_modules: gapic_v1.method_async.wrap_method( - self.list_security_health_analytics_custom_modules, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_sources: gapic_v1.method_async.wrap_method( - self.list_sources, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.run_asset_discovery: gapic_v1.method_async.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method_async.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_mute: gapic_v1.method_async.wrap_method( - self.set_mute, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( - self.test_iam_permissions, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.simulate_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( - self.simulate_security_health_analytics_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.update_external_system: gapic_v1.method_async.wrap_method( - self.update_external_system, - default_timeout=None, - client_info=client_info, - ), - self.update_finding: gapic_v1.method_async.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_mute_config: gapic_v1.method_async.wrap_method( - self.update_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method_async.wrap_method( - self.update_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method_async.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_health_analytics_custom_module: gapic_v1.method_async.wrap_method( - self.update_security_health_analytics_custom_module, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method_async.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method_async.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=client_info, - ), - self.create_big_query_export: gapic_v1.method_async.wrap_method( - self.create_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.delete_big_query_export: gapic_v1.method_async.wrap_method( - self.delete_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.update_big_query_export: gapic_v1.method_async.wrap_method( - self.update_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.list_big_query_exports: gapic_v1.method_async.wrap_method( - self.list_big_query_exports, - default_timeout=None, - client_info=client_info, - ), - self.create_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( - self.create_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.delete_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( - self.delete_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.get_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( - self.get_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.list_descendant_event_threat_detection_custom_modules: gapic_v1.method_async.wrap_method( - self.list_descendant_event_threat_detection_custom_modules, - default_timeout=None, - client_info=client_info, - ), - self.list_event_threat_detection_custom_modules: gapic_v1.method_async.wrap_method( - self.list_event_threat_detection_custom_modules, - default_timeout=None, - client_info=client_info, - ), - self.update_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( - self.update_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.validate_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( - self.validate_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.get_effective_event_threat_detection_custom_module: gapic_v1.method_async.wrap_method( - self.get_effective_event_threat_detection_custom_module, - default_timeout=None, - client_info=client_info, - ), - self.list_effective_event_threat_detection_custom_modules: gapic_v1.method_async.wrap_method( - self.list_effective_event_threat_detection_custom_modules, - default_timeout=None, - client_info=client_info, - ), - self.batch_create_resource_value_configs: gapic_v1.method_async.wrap_method( - self.batch_create_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.delete_resource_value_config: gapic_v1.method_async.wrap_method( - self.delete_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.get_resource_value_config: gapic_v1.method_async.wrap_method( - self.get_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.list_resource_value_configs: gapic_v1.method_async.wrap_method( - self.list_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.update_resource_value_config: gapic_v1.method_async.wrap_method( - self.update_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.list_valued_resources: gapic_v1.method_async.wrap_method( - self.list_valued_resources, - default_timeout=None, - client_info=client_info, - ), - self.list_attack_paths: gapic_v1.method_async.wrap_method( - self.list_attack_paths, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - return 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"] - - -__all__ = ( - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py deleted file mode 100644 index cafbd10f6efa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/services/security_center/transports/rest.py +++ /dev/null @@ -1,8529 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # 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 path_template -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 -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -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.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import valued_resource -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SecurityCenterRestInterceptor: - """Interceptor for SecurityCenter. - - 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 SecurityCenterRestTransport. - - .. code-block:: python - class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): - def pre_batch_create_resource_value_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_create_resource_value_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_bulk_mute_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_bulk_mute_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_big_query_export(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_event_threat_detection_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_event_threat_detection_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_mute_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_security_health_analytics_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_security_health_analytics_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_event_threat_detection_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_resource_value_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_security_health_analytics_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_big_query_export(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_effective_event_threat_detection_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_effective_event_threat_detection_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_effective_security_health_analytics_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_effective_security_health_analytics_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_event_threat_detection_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_event_threat_detection_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_mute_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_organization_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_organization_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_resource_value_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_resource_value_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_security_health_analytics_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_security_health_analytics_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_simulation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_simulation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_valued_resource(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_valued_resource(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_assets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_assets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_attack_paths(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_attack_paths(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_big_query_exports(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_big_query_exports(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_descendant_event_threat_detection_custom_modules(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_descendant_event_threat_detection_custom_modules(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_descendant_security_health_analytics_custom_modules(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_descendant_security_health_analytics_custom_modules(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_effective_event_threat_detection_custom_modules(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_effective_event_threat_detection_custom_modules(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_effective_security_health_analytics_custom_modules(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_effective_security_health_analytics_custom_modules(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_event_threat_detection_custom_modules(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_event_threat_detection_custom_modules(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_mute_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_mute_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_notification_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_notification_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_resource_value_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_resource_value_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_security_health_analytics_custom_modules(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_security_health_analytics_custom_modules(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_sources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_sources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_valued_resources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_valued_resources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_run_asset_discovery(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_run_asset_discovery(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_finding_state(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_finding_state(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_mute(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_mute(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_simulate_security_health_analytics_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_simulate_security_health_analytics_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_big_query_export(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_event_threat_detection_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_event_threat_detection_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_external_system(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_external_system(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_mute_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_organization_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_organization_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_resource_value_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_resource_value_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_security_health_analytics_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_security_health_analytics_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_security_marks(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_security_marks(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_validate_event_threat_detection_custom_module(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_validate_event_threat_detection_custom_module(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) - client = SecurityCenterClient(transport=transport) - - - """ - def pre_batch_create_resource_value_configs(self, request: securitycenter_service.BatchCreateResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BatchCreateResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_create_resource_value_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_batch_create_resource_value_configs(self, response: securitycenter_service.BatchCreateResourceValueConfigsResponse) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - """Post-rpc interceptor for batch_create_resource_value_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_bulk_mute_findings(self, request: securitycenter_service.BulkMuteFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BulkMuteFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for bulk_mute_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_bulk_mute_findings(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for bulk_mute_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_big_query_export(self, request: securitycenter_service.CreateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: - """Post-rpc interceptor for create_big_query_export - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_event_threat_detection_custom_module(self, request: securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_event_threat_detection_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_event_threat_detection_custom_module(self, response: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - """Post-rpc interceptor for create_event_threat_detection_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for create_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_mute_config(self, request: securitycenter_service.CreateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: - """Post-rpc interceptor for create_mute_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_notification_config(self, request: securitycenter_service.CreateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: - """Post-rpc interceptor for create_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_security_health_analytics_custom_module(self, request: securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_security_health_analytics_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_security_health_analytics_custom_module(self, response: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - """Post-rpc interceptor for create_security_health_analytics_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for create_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_delete_big_query_export(self, request: securitycenter_service.DeleteBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_event_threat_detection_custom_module(self, request: securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_event_threat_detection_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_mute_config(self, request: securitycenter_service.DeleteMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_notification_config(self, request: securitycenter_service.DeleteNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_resource_value_config(self, request: securitycenter_service.DeleteResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteResourceValueConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_resource_value_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_security_health_analytics_custom_module(self, request: securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_security_health_analytics_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_get_big_query_export(self, request: securitycenter_service.GetBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: - """Post-rpc interceptor for get_big_query_export - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_effective_event_threat_detection_custom_module(self, request: securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_effective_event_threat_detection_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_effective_event_threat_detection_custom_module(self, response: effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: - """Post-rpc interceptor for get_effective_event_threat_detection_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_effective_security_health_analytics_custom_module(self, request: securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_effective_security_health_analytics_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_effective_security_health_analytics_custom_module(self, response: effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: - """Post-rpc interceptor for get_effective_security_health_analytics_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_event_threat_detection_custom_module(self, request: securitycenter_service.GetEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_event_threat_detection_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_event_threat_detection_custom_module(self, response: event_threat_detection_custom_module.EventThreatDetectionCustomModule) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: - """Post-rpc interceptor for get_event_threat_detection_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_mute_config(self, request: securitycenter_service.GetMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_mute_config(self, response: mute_config.MuteConfig) -> mute_config.MuteConfig: - """Post-rpc interceptor for get_mute_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_notification_config(self, request: securitycenter_service.GetNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_notification_config(self, response: notification_config.NotificationConfig) -> notification_config.NotificationConfig: - """Post-rpc interceptor for get_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_organization_settings(self, request: securitycenter_service.GetOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_organization_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_organization_settings(self, response: organization_settings.OrganizationSettings) -> organization_settings.OrganizationSettings: - """Post-rpc interceptor for get_organization_settings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_resource_value_config(self, request: securitycenter_service.GetResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetResourceValueConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_resource_value_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_resource_value_config(self, response: resource_value_config.ResourceValueConfig) -> resource_value_config.ResourceValueConfig: - """Post-rpc interceptor for get_resource_value_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_security_health_analytics_custom_module(self, request: securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_security_health_analytics_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_security_health_analytics_custom_module(self, response: security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - """Post-rpc interceptor for get_security_health_analytics_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_simulation(self, request: securitycenter_service.GetSimulationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSimulationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_simulation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_simulation(self, response: simulation.Simulation) -> simulation.Simulation: - """Post-rpc interceptor for get_simulation - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_source(self, response: source.Source) -> source.Source: - """Post-rpc interceptor for get_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_valued_resource(self, request: securitycenter_service.GetValuedResourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetValuedResourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_valued_resource - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_valued_resource(self, response: valued_resource.ValuedResource) -> valued_resource.ValuedResource: - """Post-rpc interceptor for get_valued_resource - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_assets(self, request: securitycenter_service.GroupAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_assets(self, response: securitycenter_service.GroupAssetsResponse) -> securitycenter_service.GroupAssetsResponse: - """Post-rpc interceptor for group_assets - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: - """Post-rpc interceptor for group_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_assets(self, request: securitycenter_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_assets(self, response: securitycenter_service.ListAssetsResponse) -> securitycenter_service.ListAssetsResponse: - """Post-rpc interceptor for list_assets - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_attack_paths(self, request: securitycenter_service.ListAttackPathsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAttackPathsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_attack_paths - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_attack_paths(self, response: securitycenter_service.ListAttackPathsResponse) -> securitycenter_service.ListAttackPathsResponse: - """Post-rpc interceptor for list_attack_paths - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_big_query_exports(self, request: securitycenter_service.ListBigQueryExportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListBigQueryExportsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_big_query_exports - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_big_query_exports(self, response: securitycenter_service.ListBigQueryExportsResponse) -> securitycenter_service.ListBigQueryExportsResponse: - """Post-rpc interceptor for list_big_query_exports - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_descendant_event_threat_detection_custom_modules(self, request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_descendant_event_threat_detection_custom_modules - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_descendant_event_threat_detection_custom_modules(self, response: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse) -> securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse: - """Post-rpc interceptor for list_descendant_event_threat_detection_custom_modules - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_descendant_security_health_analytics_custom_modules(self, request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_descendant_security_health_analytics_custom_modules - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_descendant_security_health_analytics_custom_modules(self, response: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse) -> securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse: - """Post-rpc interceptor for list_descendant_security_health_analytics_custom_modules - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_effective_event_threat_detection_custom_modules(self, request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_effective_event_threat_detection_custom_modules - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_effective_event_threat_detection_custom_modules(self, response: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse) -> securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse: - """Post-rpc interceptor for list_effective_event_threat_detection_custom_modules - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_effective_security_health_analytics_custom_modules(self, request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_effective_security_health_analytics_custom_modules - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_effective_security_health_analytics_custom_modules(self, response: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse) -> securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse: - """Post-rpc interceptor for list_effective_security_health_analytics_custom_modules - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_event_threat_detection_custom_modules(self, request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListEventThreatDetectionCustomModulesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_event_threat_detection_custom_modules - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_event_threat_detection_custom_modules(self, response: securitycenter_service.ListEventThreatDetectionCustomModulesResponse) -> securitycenter_service.ListEventThreatDetectionCustomModulesResponse: - """Post-rpc interceptor for list_event_threat_detection_custom_modules - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. - """ - return request, metadata - - def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: - """Post-rpc interceptor for list_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_mute_configs(self, request: securitycenter_service.ListMuteConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListMuteConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_mute_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_mute_configs(self, response: securitycenter_service.ListMuteConfigsResponse) -> securitycenter_service.ListMuteConfigsResponse: - """Post-rpc interceptor for list_mute_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_notification_configs(self, request: securitycenter_service.ListNotificationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListNotificationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_notification_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_notification_configs(self, response: securitycenter_service.ListNotificationConfigsResponse) -> securitycenter_service.ListNotificationConfigsResponse: - """Post-rpc interceptor for list_notification_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_resource_value_configs(self, request: securitycenter_service.ListResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_resource_value_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_resource_value_configs(self, response: securitycenter_service.ListResourceValueConfigsResponse) -> securitycenter_service.ListResourceValueConfigsResponse: - """Post-rpc interceptor for list_resource_value_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_security_health_analytics_custom_modules(self, request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_security_health_analytics_custom_modules - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_security_health_analytics_custom_modules(self, response: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse) -> securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse: - """Post-rpc interceptor for list_security_health_analytics_custom_modules - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_sources - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: - """Post-rpc interceptor for list_sources - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_valued_resources(self, request: securitycenter_service.ListValuedResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListValuedResourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_valued_resources - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_valued_resources(self, response: securitycenter_service.ListValuedResourcesResponse) -> securitycenter_service.ListValuedResourcesResponse: - """Post-rpc interceptor for list_valued_resources - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_run_asset_discovery(self, request: securitycenter_service.RunAssetDiscoveryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.RunAssetDiscoveryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for run_asset_discovery - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_run_asset_discovery(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for run_asset_discovery - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_set_mute(self, request: securitycenter_service.SetMuteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetMuteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_mute - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_set_mute(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for set_mute - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_simulate_security_health_analytics_custom_module(self, request: securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for simulate_security_health_analytics_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_simulate_security_health_analytics_custom_module(self, response: securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: - """Post-rpc interceptor for simulate_security_health_analytics_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_big_query_export(self, request: securitycenter_service.UpdateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: - """Post-rpc interceptor for update_big_query_export - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_event_threat_detection_custom_module(self, request: securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_event_threat_detection_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_event_threat_detection_custom_module(self, response: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - """Post-rpc interceptor for update_event_threat_detection_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_external_system(self, request: securitycenter_service.UpdateExternalSystemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateExternalSystemRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_external_system - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_external_system(self, response: gcs_external_system.ExternalSystem) -> gcs_external_system.ExternalSystem: - """Post-rpc interceptor for update_external_system - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for update_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_mute_config(self, request: securitycenter_service.UpdateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: - """Post-rpc interceptor for update_mute_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_notification_config(self, request: securitycenter_service.UpdateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: - """Post-rpc interceptor for update_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_organization_settings(self, request: securitycenter_service.UpdateOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_organization_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_organization_settings(self, response: gcs_organization_settings.OrganizationSettings) -> gcs_organization_settings.OrganizationSettings: - """Post-rpc interceptor for update_organization_settings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_resource_value_config(self, request: securitycenter_service.UpdateResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateResourceValueConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_resource_value_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_resource_value_config(self, response: gcs_resource_value_config.ResourceValueConfig) -> gcs_resource_value_config.ResourceValueConfig: - """Post-rpc interceptor for update_resource_value_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_security_health_analytics_custom_module(self, request: securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_security_health_analytics_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_security_health_analytics_custom_module(self, response: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - """Post-rpc interceptor for update_security_health_analytics_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: - """Post-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for update_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_validate_event_threat_detection_custom_module(self, request: securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for validate_event_threat_detection_custom_module - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_validate_event_threat_detection_custom_module(self, response: securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: - """Post-rpc interceptor for validate_event_threat_detection_custom_module - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SecurityCenterRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SecurityCenterRestInterceptor - - -class SecurityCenterRestTransport(SecurityCenterTransport): - """REST backend transport for SecurityCenter. - - V1 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SecurityCenterRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 - 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 - ) - 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 SecurityCenterRestInterceptor() - 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=organizations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/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 _BatchCreateResourceValueConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("BatchCreateResourceValueConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.BatchCreateResourceValueConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - r"""Call the batch create resource - value configs method over HTTP. - - Args: - request (~.securitycenter_service.BatchCreateResourceValueConfigsRequest): - The request object. Request message to create multiple - resource value configs - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.BatchCreateResourceValueConfigsResponse: - Response message for - BatchCreateResourceValueConfigs - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/resourceValueConfigs:batchCreate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_create_resource_value_configs(request, metadata) - pb_request = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.BatchCreateResourceValueConfigsResponse() - pb_resp = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_create_resource_value_configs(resp) - return resp - - class _BulkMuteFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("BulkMuteFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.BulkMuteFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the bulk mute findings method over HTTP. - - Args: - request (~.securitycenter_service.BulkMuteFindingsRequest): - The request object. Request message for bulk findings - update. - Note: - - 1. If multiple bulk update requests - match the same resource, the order - in which they get executed is not - defined. - 2. Once a bulk operation is started, - there is no way to stop it. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/findings:bulkMute', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_bulk_mute_findings(request, metadata) - pb_request = securitycenter_service.BulkMuteFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_bulk_mute_findings(resp) - return resp - - class _CreateBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "bigQueryExportId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> bigquery_export.BigQueryExport: - r"""Call the create big query export method over HTTP. - - Args: - request (~.securitycenter_service.CreateBigQueryExportRequest): - The request object. Request message for creating a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.bigquery_export.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/bigQueryExports', - 'body': 'big_query_export', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*}/bigQueryExports', - 'body': 'big_query_export', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/bigQueryExports', - 'body': 'big_query_export', - }, - ] - request, metadata = self._interceptor.pre_create_big_query_export(request, metadata) - pb_request = securitycenter_service.CreateBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = bigquery_export.BigQueryExport() - pb_resp = bigquery_export.BigQueryExport.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_big_query_export(resp) - return resp - - class _CreateEventThreatDetectionCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateEventThreatDetectionCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Call the create event threat - detection custom module method over HTTP. - - Args: - request (~.securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): - The request object. Request to create an Event Threat - Detection custom module. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/customModules', - 'body': 'event_threat_detection_custom_module', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/customModules', - 'body': 'event_threat_detection_custom_module', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/customModules', - 'body': 'event_threat_detection_custom_module', - }, - ] - request, metadata = self._interceptor.pre_create_event_threat_detection_custom_module(request, metadata) - pb_request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - pb_resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_event_threat_detection_custom_module(resp) - return resp - - class _CreateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "findingId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the create finding method over HTTP. - - Args: - request (~.securitycenter_service.CreateFindingRequest): - The request object. Request message for creating a - finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/sources/*}/findings', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_create_finding(request, metadata) - pb_request = securitycenter_service.CreateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_finding(resp) - return resp - - class _CreateMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "muteConfigId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_mute_config.MuteConfig: - r"""Call the create mute config method over HTTP. - - Args: - request (~.securitycenter_service.CreateMuteConfigRequest): - The request object. Request message for creating a mute - config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_mute_config.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/locations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*/locations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/muteConfigs', - 'body': 'mute_config', - }, - ] - request, metadata = self._interceptor.pre_create_mute_config(request, metadata) - pb_request = securitycenter_service.CreateMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_mute_config.MuteConfig() - pb_resp = gcs_mute_config.MuteConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_mute_config(resp) - return resp - - class _CreateNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "configId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_notification_config.NotificationConfig: - r"""Call the create notification - config method over HTTP. - - Args: - request (~.securitycenter_service.CreateNotificationConfigRequest): - The request object. Request message for creating a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/notificationConfigs', - 'body': 'notification_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*}/notificationConfigs', - 'body': 'notification_config', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/notificationConfigs', - 'body': 'notification_config', - }, - ] - request, metadata = self._interceptor.pre_create_notification_config(request, metadata) - pb_request = securitycenter_service.CreateNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_notification_config.NotificationConfig() - pb_resp = gcs_notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_notification_config(resp) - return resp - - class _CreateSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateSecurityHealthAnalyticsCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Call the create security health - analytics custom module method over HTTP. - - Args: - request (~.securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): - The request object. Request message for creating Security - Health Analytics custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules', - 'body': 'security_health_analytics_custom_module', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules', - 'body': 'security_health_analytics_custom_module', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules', - 'body': 'security_health_analytics_custom_module', - }, - ] - request, metadata = self._interceptor.pre_create_security_health_analytics_custom_module(request, metadata) - pb_request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - pb_resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_security_health_analytics_custom_module(resp) - return resp - - class _CreateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the create source method over HTTP. - - Args: - request (~.securitycenter_service.CreateSourceRequest): - The request object. Request message for creating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/sources', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_create_source(request, metadata) - pb_request = securitycenter_service.CreateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_source(resp) - return resp - - class _DeleteBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete big query export method over HTTP. - - Args: - request (~.securitycenter_service.DeleteBigQueryExportRequest): - The request object. Request message for deleting a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/bigQueryExports/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=folders/*/bigQueryExports/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/bigQueryExports/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_big_query_export(request, metadata) - pb_request = securitycenter_service.DeleteBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteEventThreatDetectionCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteEventThreatDetectionCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete event threat - detection custom module method over HTTP. - - Args: - request (~.securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): - The request object. Request to delete an Event Threat - Detection custom module. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/eventThreatDetectionSettings/customModules/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=folders/*/eventThreatDetectionSettings/customModules/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/eventThreatDetectionSettings/customModules/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_event_threat_detection_custom_module(request, metadata) - pb_request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete mute config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteMuteConfigRequest): - The request object. Request message for deleting a mute - config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=folders/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=folders/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/muteConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_mute_config(request, metadata) - pb_request = securitycenter_service.DeleteMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete notification - config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteNotificationConfigRequest): - The request object. Request message for deleting a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/notificationConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=folders/*/notificationConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/notificationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_notification_config(request, metadata) - pb_request = securitycenter_service.DeleteNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteResourceValueConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteResourceValueConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteResourceValueConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete resource value - config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteResourceValueConfigRequest): - The request object. Request message to delete resource - value config - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/resourceValueConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_resource_value_config(request, metadata) - pb_request = securitycenter_service.DeleteResourceValueConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteSecurityHealthAnalyticsCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete security health - analytics custom module method over HTTP. - - Args: - request (~.securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): - The request object. Request message for deleting Security - Health Analytics custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/securityHealthAnalyticsSettings/customModules/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=folders/*/securityHealthAnalyticsSettings/customModules/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/securityHealthAnalyticsSettings/customModules/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_security_health_analytics_custom_module(request, metadata) - pb_request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _GetBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("GetBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> bigquery_export.BigQueryExport: - r"""Call the get big query export method over HTTP. - - Args: - request (~.securitycenter_service.GetBigQueryExportRequest): - The request object. Request message for retrieving a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.bigquery_export.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/bigQueryExports/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/bigQueryExports/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/bigQueryExports/*}', - }, - ] - request, metadata = self._interceptor.pre_get_big_query_export(request, metadata) - pb_request = securitycenter_service.GetBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = bigquery_export.BigQueryExport() - pb_resp = bigquery_export.BigQueryExport.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_big_query_export(resp) - return resp - - class _GetEffectiveEventThreatDetectionCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("GetEffectiveEventThreatDetectionCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: - r"""Call the get effective event - threat detection custom module method over HTTP. - - Args: - request (~.securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): - The request object. Request to get an - EffectiveEventThreatDetectionCustomModule. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule: - An EffectiveEventThreatDetectionCustomModule is the - representation of an Event Threat Detection custom - module at a specified level of the resource hierarchy: - organization, folder, or project. If a custom module is - inherited from a parent organization or folder, the - value of the ``enablement_state`` property in - EffectiveEventThreatDetectionCustomModule is set to the - value that is effective in the parent, instead of - ``INHERITED``. For example, if the module is enabled in - a parent organization or folder, the effective - ``enablement_state`` for the module in all child folders - or projects is also ``enabled``. - EffectiveEventThreatDetectionCustomModule is read-only. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/eventThreatDetectionSettings/effectiveCustomModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/eventThreatDetectionSettings/effectiveCustomModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/eventThreatDetectionSettings/effectiveCustomModules/*}', - }, - ] - request, metadata = self._interceptor.pre_get_effective_event_threat_detection_custom_module(request, metadata) - pb_request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - pb_resp = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_effective_event_threat_detection_custom_module(resp) - return resp - - class _GetEffectiveSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("GetEffectiveSecurityHealthAnalyticsCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: - r"""Call the get effective security - health analytics custom module method over HTTP. - - Args: - request (~.securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): - The request object. Request message for getting effective - Security Health Analytics custom - modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule: - An EffectiveSecurityHealthAnalyticsCustomModule is the - representation of a Security Health Analytics custom - module at a specified level of the resource hierarchy: - organization, folder, or project. If a custom module is - inherited from a parent organization or folder, the - value of the ``enablementState`` property in - EffectiveSecurityHealthAnalyticsCustomModule is set to - the value that is effective in the parent, instead of - ``INHERITED``. For example, if the module is enabled in - a parent organization or folder, the effective - enablement_state for the module in all child folders or - projects is also ``enabled``. - EffectiveSecurityHealthAnalyticsCustomModule is - read-only. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}', - }, - ] - request, metadata = self._interceptor.pre_get_effective_security_health_analytics_custom_module(request, metadata) - pb_request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - pb_resp = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_effective_security_health_analytics_custom_module(resp) - return resp - - class _GetEventThreatDetectionCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("GetEventThreatDetectionCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetEventThreatDetectionCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Call the get event threat - detection custom module method over HTTP. - - Args: - request (~.securitycenter_service.GetEventThreatDetectionCustomModuleRequest): - The request object. Request to get an Event Threat - Detection custom module. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.event_threat_detection_custom_module.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/eventThreatDetectionSettings/customModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/eventThreatDetectionSettings/customModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/eventThreatDetectionSettings/customModules/*}', - }, - ] - request, metadata = self._interceptor.pre_get_event_threat_detection_custom_module(request, metadata) - pb_request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - pb_resp = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_event_threat_detection_custom_module(resp) - return resp - - class _GetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=organizations/*/sources/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _GetMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> mute_config.MuteConfig: - r"""Call the get mute config method over HTTP. - - Args: - request (~.securitycenter_service.GetMuteConfigRequest): - The request object. Request message for retrieving a mute - config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.mute_config.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/muteConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_mute_config(request, metadata) - pb_request = securitycenter_service.GetMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = mute_config.MuteConfig() - pb_resp = mute_config.MuteConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_mute_config(resp) - return resp - - class _GetNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> notification_config.NotificationConfig: - r"""Call the get notification config method over HTTP. - - Args: - request (~.securitycenter_service.GetNotificationConfigRequest): - The request object. Request message for getting a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/notificationConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/notificationConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/notificationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_notification_config(request, metadata) - pb_request = securitycenter_service.GetNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = notification_config.NotificationConfig() - pb_resp = notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_notification_config(resp) - return resp - - class _GetOrganizationSettings(SecurityCenterRestStub): - def __hash__(self): - return hash("GetOrganizationSettings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetOrganizationSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> organization_settings.OrganizationSettings: - r"""Call the get organization settings method over HTTP. - - Args: - request (~.securitycenter_service.GetOrganizationSettingsRequest): - The request object. Request message for getting - organization 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: - ~.organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/organizationSettings}', - }, - ] - request, metadata = self._interceptor.pre_get_organization_settings(request, metadata) - pb_request = securitycenter_service.GetOrganizationSettingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = organization_settings.OrganizationSettings() - pb_resp = organization_settings.OrganizationSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_organization_settings(resp) - return resp - - class _GetResourceValueConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetResourceValueConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetResourceValueConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resource_value_config.ResourceValueConfig: - r"""Call the get resource value config method over HTTP. - - Args: - request (~.securitycenter_service.GetResourceValueConfigRequest): - The request object. Request message to get resource value - config - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resource_value_config.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/resourceValueConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_resource_value_config(request, metadata) - pb_request = securitycenter_service.GetResourceValueConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resource_value_config.ResourceValueConfig() - pb_resp = resource_value_config.ResourceValueConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_resource_value_config(resp) - return resp - - class _GetSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSecurityHealthAnalyticsCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Call the get security health - analytics custom module method over HTTP. - - Args: - request (~.securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): - The request object. Request message for getting Security - Health Analytics custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/securityHealthAnalyticsSettings/customModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/securityHealthAnalyticsSettings/customModules/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/securityHealthAnalyticsSettings/customModules/*}', - }, - ] - request, metadata = self._interceptor.pre_get_security_health_analytics_custom_module(request, metadata) - pb_request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - pb_resp = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_security_health_analytics_custom_module(resp) - return resp - - class _GetSimulation(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSimulation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSimulationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> simulation.Simulation: - r"""Call the get simulation method over HTTP. - - Args: - request (~.securitycenter_service.GetSimulationRequest): - The request object. Request message for getting - simulation. Simulation name can include - "latest" to retrieve the latest - simulation For example, - "organizations/123/simulations/latest". - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.simulation.Simulation: - Attack path simulation - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/simulations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_simulation(request, metadata) - pb_request = securitycenter_service.GetSimulationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = simulation.Simulation() - pb_resp = simulation.Simulation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_simulation(resp) - return resp - - class _GetSource(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> source.Source: - r"""Call the get source method over HTTP. - - Args: - request (~.securitycenter_service.GetSourceRequest): - The request object. Request message for getting a source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/sources/*}', - }, - ] - request, metadata = self._interceptor.pre_get_source(request, metadata) - pb_request = securitycenter_service.GetSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = source.Source() - pb_resp = source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_source(resp) - return resp - - class _GetValuedResource(SecurityCenterRestStub): - def __hash__(self): - return hash("GetValuedResource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetValuedResourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> valued_resource.ValuedResource: - r"""Call the get valued resource method over HTTP. - - Args: - request (~.securitycenter_service.GetValuedResourceRequest): - The request object. Request message for getting a valued - resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.valued_resource.ValuedResource: - A resource that is determined to have - value to a user's system - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/simulations/*/valuedResources/*}', - }, - ] - request, metadata = self._interceptor.pre_get_valued_resource(request, metadata) - pb_request = securitycenter_service.GetValuedResourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = valued_resource.ValuedResource() - pb_resp = valued_resource.ValuedResource.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_valued_resource(resp) - return resp - - class _GroupAssets(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupAssets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupAssetsResponse: - r"""Call the group assets method over HTTP. - - Args: - request (~.securitycenter_service.GroupAssetsRequest): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupAssetsResponse: - Response message for grouping by - assets. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/assets:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*}/assets:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*}/assets:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_assets(request, metadata) - pb_request = securitycenter_service.GroupAssetsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupAssetsResponse() - pb_resp = securitycenter_service.GroupAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_assets(resp) - return resp - - class _GroupFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupFindingsResponse: - r"""Call the group findings method over HTTP. - - Args: - request (~.securitycenter_service.GroupFindingsRequest): - The request object. Request message for grouping by - findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupFindingsResponse: - Response message for group by - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/sources/*}/findings:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_findings(request, metadata) - pb_request = securitycenter_service.GroupFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupFindingsResponse() - pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_findings(resp) - return resp - - class _ListAssets(SecurityCenterRestStub): - def __hash__(self): - return hash("ListAssets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListAssetsResponse: - r"""Call the list assets method over HTTP. - - Args: - request (~.securitycenter_service.ListAssetsRequest): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListAssetsResponse: - Response message for listing assets. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*}/assets', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*}/assets', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*}/assets', - }, - ] - request, metadata = self._interceptor.pre_list_assets(request, metadata) - pb_request = securitycenter_service.ListAssetsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListAssetsResponse() - pb_resp = securitycenter_service.ListAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_assets(resp) - return resp - - class _ListAttackPaths(SecurityCenterRestStub): - def __hash__(self): - return hash("ListAttackPaths") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListAttackPathsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListAttackPathsResponse: - r"""Call the list attack paths method over HTTP. - - Args: - request (~.securitycenter_service.ListAttackPathsRequest): - The request object. Request message for listing the - attack paths for a given simulation or - valued resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListAttackPathsResponse: - Response message for listing the - attack paths for a given simulation or - valued resource. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/simulations/*}/attackPaths', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/simulations/*/valuedResources/*}/attackPaths', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/simulations/*/attackExposureResults/*}/attackPaths', - }, - ] - request, metadata = self._interceptor.pre_list_attack_paths(request, metadata) - pb_request = securitycenter_service.ListAttackPathsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListAttackPathsResponse() - pb_resp = securitycenter_service.ListAttackPathsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_attack_paths(resp) - return resp - - class _ListBigQueryExports(SecurityCenterRestStub): - def __hash__(self): - return hash("ListBigQueryExports") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListBigQueryExportsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListBigQueryExportsResponse: - r"""Call the list big query exports method over HTTP. - - Args: - request (~.securitycenter_service.ListBigQueryExportsRequest): - The request object. Request message for listing BigQuery - exports at a given scope e.g. - organization, folder or 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: - ~.securitycenter_service.ListBigQueryExportsResponse: - Response message for listing BigQuery - exports. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*}/bigQueryExports', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*}/bigQueryExports', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*}/bigQueryExports', - }, - ] - request, metadata = self._interceptor.pre_list_big_query_exports(request, metadata) - pb_request = securitycenter_service.ListBigQueryExportsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListBigQueryExportsResponse() - pb_resp = securitycenter_service.ListBigQueryExportsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_big_query_exports(resp) - return resp - - class _ListDescendantEventThreatDetectionCustomModules(SecurityCenterRestStub): - def __hash__(self): - return hash("ListDescendantEventThreatDetectionCustomModules") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse: - r"""Call the list descendant event - threat detection custom modules method over HTTP. - - Args: - request (~.securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): - The request object. Request to list current and - descendant resident Event Threat - Detection custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse: - Response for listing current and - descendant resident Event Threat - Detection custom modules. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/customModules:listDescendant', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/customModules:listDescendant', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/customModules:listDescendant', - }, - ] - request, metadata = self._interceptor.pre_list_descendant_event_threat_detection_custom_modules(request, metadata) - pb_request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - pb_resp = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_descendant_event_threat_detection_custom_modules(resp) - return resp - - class _ListDescendantSecurityHealthAnalyticsCustomModules(SecurityCenterRestStub): - def __hash__(self): - return hash("ListDescendantSecurityHealthAnalyticsCustomModules") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse: - r"""Call the list descendant security - health analytics custom modules method over HTTP. - - Args: - request (~.securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - The request object. Request message for listing - descendant Security Health Analytics - custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse: - Response message for listing - descendant Security Health Analytics - custom modules. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules:listDescendant', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules:listDescendant', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules:listDescendant', - }, - ] - request, metadata = self._interceptor.pre_list_descendant_security_health_analytics_custom_modules(request, metadata) - pb_request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - pb_resp = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_descendant_security_health_analytics_custom_modules(resp) - return resp - - class _ListEffectiveEventThreatDetectionCustomModules(SecurityCenterRestStub): - def __hash__(self): - return hash("ListEffectiveEventThreatDetectionCustomModules") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse: - r"""Call the list effective event - threat detection custom modules method over HTTP. - - Args: - request (~.securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): - The request object. Request to list effective Event - Threat Detection custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse: - Response for listing - EffectiveEventThreatDetectionCustomModules. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/effectiveCustomModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/effectiveCustomModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/effectiveCustomModules', - }, - ] - request, metadata = self._interceptor.pre_list_effective_event_threat_detection_custom_modules(request, metadata) - pb_request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - pb_resp = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_effective_event_threat_detection_custom_modules(resp) - return resp - - class _ListEffectiveSecurityHealthAnalyticsCustomModules(SecurityCenterRestStub): - def __hash__(self): - return hash("ListEffectiveSecurityHealthAnalyticsCustomModules") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse: - r"""Call the list effective security - health analytics custom modules method over HTTP. - - Args: - request (~.securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - The request object. Request message for listing effective - Security Health Analytics custom - modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse: - Response message for listing - effective Security Health Analytics - custom modules. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/effectiveCustomModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/effectiveCustomModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/effectiveCustomModules', - }, - ] - request, metadata = self._interceptor.pre_list_effective_security_health_analytics_custom_modules(request, metadata) - pb_request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - pb_resp = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_effective_security_health_analytics_custom_modules(resp) - return resp - - class _ListEventThreatDetectionCustomModules(SecurityCenterRestStub): - def __hash__(self): - return hash("ListEventThreatDetectionCustomModules") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListEventThreatDetectionCustomModulesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListEventThreatDetectionCustomModulesResponse: - r"""Call the list event threat - detection custom modules method over HTTP. - - Args: - request (~.securitycenter_service.ListEventThreatDetectionCustomModulesRequest): - The request object. Request to list Event Threat - Detection custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListEventThreatDetectionCustomModulesResponse: - Response for listing Event Threat - Detection custom modules. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}/customModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}/customModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}/customModules', - }, - ] - request, metadata = self._interceptor.pre_list_event_threat_detection_custom_modules(request, metadata) - pb_request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - pb_resp = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_event_threat_detection_custom_modules(resp) - return resp - - class _ListFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("ListFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListFindingsResponse: - r"""Call the list findings method over HTTP. - - Args: - request (~.securitycenter_service.ListFindingsRequest): - The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListFindingsResponse: - Response message for listing - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/sources/*}/findings', - }, - ] - request, metadata = self._interceptor.pre_list_findings(request, metadata) - pb_request = securitycenter_service.ListFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListFindingsResponse() - pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_findings(resp) - return resp - - class _ListMuteConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListMuteConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListMuteConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListMuteConfigsResponse: - r"""Call the list mute configs method over HTTP. - - Args: - request (~.securitycenter_service.ListMuteConfigsRequest): - The request object. Request message for listing mute - configs at a given scope e.g. - organization, folder or 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: - ~.securitycenter_service.ListMuteConfigsResponse: - Response message for listing mute - configs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/locations/*/muteConfigs}', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/locations/*/muteConfigs}', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/muteConfigs}', - }, - ] - request, metadata = self._interceptor.pre_list_mute_configs(request, metadata) - pb_request = securitycenter_service.ListMuteConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListMuteConfigsResponse() - pb_resp = securitycenter_service.ListMuteConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_mute_configs(resp) - return resp - - class _ListNotificationConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListNotificationConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListNotificationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListNotificationConfigsResponse: - r"""Call the list notification configs method over HTTP. - - Args: - request (~.securitycenter_service.ListNotificationConfigsRequest): - The request object. Request message for listing - notification configs. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListNotificationConfigsResponse: - Response message for listing - notification configs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*}/notificationConfigs', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*}/notificationConfigs', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*}/notificationConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_notification_configs(request, metadata) - pb_request = securitycenter_service.ListNotificationConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListNotificationConfigsResponse() - pb_resp = securitycenter_service.ListNotificationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_notification_configs(resp) - return resp - - class _ListResourceValueConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListResourceValueConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListResourceValueConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListResourceValueConfigsResponse: - r"""Call the list resource value - configs method over HTTP. - - Args: - request (~.securitycenter_service.ListResourceValueConfigsRequest): - The request object. Request message to list resource - value configs of a parent - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListResourceValueConfigsResponse: - Response message to list resource - value configs - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*}/resourceValueConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_resource_value_configs(request, metadata) - pb_request = securitycenter_service.ListResourceValueConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListResourceValueConfigsResponse() - pb_resp = securitycenter_service.ListResourceValueConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_resource_value_configs(resp) - return resp - - class _ListSecurityHealthAnalyticsCustomModules(SecurityCenterRestStub): - def __hash__(self): - return hash("ListSecurityHealthAnalyticsCustomModules") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse: - r"""Call the list security health - analytics custom modules method over HTTP. - - Args: - request (~.securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): - The request object. Request message for listing Security - Health Analytics custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse: - Response message for listing Security - Health Analytics custom modules. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules', - }, - ] - request, metadata = self._interceptor.pre_list_security_health_analytics_custom_modules(request, metadata) - pb_request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - pb_resp = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_security_health_analytics_custom_modules(resp) - return resp - - class _ListSources(SecurityCenterRestStub): - def __hash__(self): - return hash("ListSources") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListSourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListSourcesResponse: - r"""Call the list sources method over HTTP. - - Args: - request (~.securitycenter_service.ListSourcesRequest): - The request object. Request message for listing sources. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListSourcesResponse: - Response message for listing sources. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*}/sources', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=folders/*}/sources', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*}/sources', - }, - ] - request, metadata = self._interceptor.pre_list_sources(request, metadata) - pb_request = securitycenter_service.ListSourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListSourcesResponse() - pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_sources(resp) - return resp - - class _ListValuedResources(SecurityCenterRestStub): - def __hash__(self): - return hash("ListValuedResources") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListValuedResourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListValuedResourcesResponse: - r"""Call the list valued resources method over HTTP. - - Args: - request (~.securitycenter_service.ListValuedResourcesRequest): - The request object. Request message for listing the - valued resources for a given simulation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListValuedResourcesResponse: - Response message for listing the - valued resources for a given simulation. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/simulations/*}/valuedResources', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/simulations/*/attackExposureResults/*}/valuedResources', - }, - ] - request, metadata = self._interceptor.pre_list_valued_resources(request, metadata) - pb_request = securitycenter_service.ListValuedResourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListValuedResourcesResponse() - pb_resp = securitycenter_service.ListValuedResourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_valued_resources(resp) - return resp - - class _RunAssetDiscovery(SecurityCenterRestStub): - def __hash__(self): - return hash("RunAssetDiscovery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.RunAssetDiscoveryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the run asset discovery method over HTTP. - - Args: - request (~.securitycenter_service.RunAssetDiscoveryRequest): - The request object. Request message for running asset - discovery for an organization. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*}/assets:runDiscovery', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_run_asset_discovery(request, metadata) - pb_request = securitycenter_service.RunAssetDiscoveryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_run_asset_discovery(resp) - return resp - - class _SetFindingState(SecurityCenterRestStub): - def __hash__(self): - return hash("SetFindingState") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SetFindingStateRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the set finding state method over HTTP. - - Args: - request (~.securitycenter_service.SetFindingStateRequest): - The request object. Request message for updating a - finding's state. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=organizations/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=folders/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/sources/*/findings/*}:setState', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_finding_state(request, metadata) - pb_request = securitycenter_service.SetFindingStateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_set_finding_state(resp) - return resp - - class _SetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=organizations/*/sources/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _SetMute(SecurityCenterRestStub): - def __hash__(self): - return hash("SetMute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SetMuteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the set mute method over HTTP. - - Args: - request (~.securitycenter_service.SetMuteRequest): - The request object. Request message for updating a - finding's mute status. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=organizations/*/sources/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=folders/*/sources/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/sources/*/findings/*}:setMute', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_mute(request, metadata) - pb_request = securitycenter_service.SetMuteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_set_mute(resp) - return resp - - class _SimulateSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("SimulateSecurityHealthAnalyticsCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: - r"""Call the simulate security health - analytics custom module method over HTTP. - - Args: - request (~.securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): - The request object. Request message to simulate a - CustomConfig against a given test - resource. Maximum size of the request is - 4 MB by default. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse: - Response message for simulating a - ``SecurityHealthAnalyticsCustomModule`` against a given - resource. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/securityHealthAnalyticsSettings}/customModules:simulate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*/securityHealthAnalyticsSettings}/customModules:simulate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/securityHealthAnalyticsSettings}/customModules:simulate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_simulate_security_health_analytics_custom_module(request, metadata) - pb_request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - pb_resp = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_simulate_security_health_analytics_custom_module(resp) - return resp - - class _TestIamPermissions(SecurityCenterRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=organizations/*/sources/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UpdateBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> bigquery_export.BigQueryExport: - r"""Call the update big query export method over HTTP. - - Args: - request (~.securitycenter_service.UpdateBigQueryExportRequest): - The request object. Request message for updating a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.bigquery_export.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{big_query_export.name=organizations/*/bigQueryExports/*}', - 'body': 'big_query_export', - }, -{ - 'method': 'patch', - 'uri': '/v1/{big_query_export.name=folders/*/bigQueryExports/*}', - 'body': 'big_query_export', - }, -{ - 'method': 'patch', - 'uri': '/v1/{big_query_export.name=projects/*/bigQueryExports/*}', - 'body': 'big_query_export', - }, - ] - request, metadata = self._interceptor.pre_update_big_query_export(request, metadata) - pb_request = securitycenter_service.UpdateBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = bigquery_export.BigQueryExport() - pb_resp = bigquery_export.BigQueryExport.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_big_query_export(resp) - return resp - - class _UpdateEventThreatDetectionCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateEventThreatDetectionCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - r"""Call the update event threat - detection custom module method over HTTP. - - Args: - request (~.securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): - The request object. Request to update an Event Threat - Detection custom module. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule: - Represents an instance of an Event - Threat Detection custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by child folders and projects. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{event_threat_detection_custom_module.name=organizations/*/eventThreatDetectionSettings/customModules/*}', - 'body': 'event_threat_detection_custom_module', - }, -{ - 'method': 'patch', - 'uri': '/v1/{event_threat_detection_custom_module.name=folders/*/eventThreatDetectionSettings/customModules/*}', - 'body': 'event_threat_detection_custom_module', - }, -{ - 'method': 'patch', - 'uri': '/v1/{event_threat_detection_custom_module.name=projects/*/eventThreatDetectionSettings/customModules/*}', - 'body': 'event_threat_detection_custom_module', - }, - ] - request, metadata = self._interceptor.pre_update_event_threat_detection_custom_module(request, metadata) - pb_request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - pb_resp = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_event_threat_detection_custom_module(resp) - return resp - - class _UpdateExternalSystem(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateExternalSystem") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateExternalSystemRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_external_system.ExternalSystem: - r"""Call the update external system method over HTTP. - - Args: - request (~.securitycenter_service.UpdateExternalSystemRequest): - The request object. Request message for updating a - ExternalSystem resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_external_system.ExternalSystem: - Representation of third party - SIEM/SOAR fields within SCC. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v1/{external_system.name=folders/*/sources/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v1/{external_system.name=projects/*/sources/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, - ] - request, metadata = self._interceptor.pre_update_external_system(request, metadata) - pb_request = securitycenter_service.UpdateExternalSystemRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_external_system.ExternalSystem() - pb_resp = gcs_external_system.ExternalSystem.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_external_system(resp) - return resp - - class _UpdateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the update finding method over HTTP. - - Args: - request (~.securitycenter_service.UpdateFindingRequest): - The request object. Request message for updating or - creating a finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{finding.name=organizations/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v1/{finding.name=folders/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v1/{finding.name=projects/*/sources/*/findings/*}', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_update_finding(request, metadata) - pb_request = securitycenter_service.UpdateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_finding(resp) - return resp - - class _UpdateMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_mute_config.MuteConfig: - r"""Call the update mute config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateMuteConfigRequest): - The request object. Request message for updating a mute - config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_mute_config.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{mute_config.name=organizations/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{mute_config.name=folders/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{mute_config.name=projects/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{mute_config.name=organizations/*/locations/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{mute_config.name=folders/*/locations/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{mute_config.name=projects/*/locations/*/muteConfigs/*}', - 'body': 'mute_config', - }, - ] - request, metadata = self._interceptor.pre_update_mute_config(request, metadata) - pb_request = securitycenter_service.UpdateMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_mute_config.MuteConfig() - pb_resp = gcs_mute_config.MuteConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_mute_config(resp) - return resp - - class _UpdateNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_notification_config.NotificationConfig: - r"""Call the update notification - config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateNotificationConfigRequest): - The request object. Request message for updating a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{notification_config.name=organizations/*/notificationConfigs/*}', - 'body': 'notification_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{notification_config.name=folders/*/notificationConfigs/*}', - 'body': 'notification_config', - }, -{ - 'method': 'patch', - 'uri': '/v1/{notification_config.name=projects/*/notificationConfigs/*}', - 'body': 'notification_config', - }, - ] - request, metadata = self._interceptor.pre_update_notification_config(request, metadata) - pb_request = securitycenter_service.UpdateNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_notification_config.NotificationConfig() - pb_resp = gcs_notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_notification_config(resp) - return resp - - class _UpdateOrganizationSettings(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateOrganizationSettings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateOrganizationSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Call the update organization - settings method over HTTP. - - Args: - request (~.securitycenter_service.UpdateOrganizationSettingsRequest): - The request object. Request message for updating an - organization's 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: - ~.gcs_organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{organization_settings.name=organizations/*/organizationSettings}', - 'body': 'organization_settings', - }, - ] - request, metadata = self._interceptor.pre_update_organization_settings(request, metadata) - pb_request = securitycenter_service.UpdateOrganizationSettingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_organization_settings.OrganizationSettings() - pb_resp = gcs_organization_settings.OrganizationSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_organization_settings(resp) - return resp - - class _UpdateResourceValueConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateResourceValueConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateResourceValueConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_resource_value_config.ResourceValueConfig: - r"""Call the update resource value - config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateResourceValueConfigRequest): - The request object. Request message to update resource - value config - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_resource_value_config.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{resource_value_config.name=organizations/*/resourceValueConfigs/*}', - 'body': 'resource_value_config', - }, - ] - request, metadata = self._interceptor.pre_update_resource_value_config(request, metadata) - pb_request = securitycenter_service.UpdateResourceValueConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_resource_value_config.ResourceValueConfig() - pb_resp = gcs_resource_value_config.ResourceValueConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_resource_value_config(resp) - return resp - - class _UpdateSecurityHealthAnalyticsCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSecurityHealthAnalyticsCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - r"""Call the update security health - analytics custom module method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): - The request object. Request message for updating Security - Health Analytics custom modules. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule: - Represents an instance of a Security - Health Analytics custom module, - including its full module name, display - name, enablement state, and last updated - time. You can create a custom module at - the organization, folder, or project - level. Custom modules that you create at - the organization or folder level are - inherited by the child folders and - projects. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{security_health_analytics_custom_module.name=organizations/*/securityHealthAnalyticsSettings/customModules/*}', - 'body': 'security_health_analytics_custom_module', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_health_analytics_custom_module.name=folders/*/securityHealthAnalyticsSettings/customModules/*}', - 'body': 'security_health_analytics_custom_module', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_health_analytics_custom_module.name=projects/*/securityHealthAnalyticsSettings/customModules/*}', - 'body': 'security_health_analytics_custom_module', - }, - ] - request, metadata = self._interceptor.pre_update_security_health_analytics_custom_module(request, metadata) - pb_request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - pb_resp = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_security_health_analytics_custom_module(resp) - return resp - - class _UpdateSecurityMarks(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSecurityMarks") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSecurityMarksRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_security_marks.SecurityMarks: - r"""Call the update security marks method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSecurityMarksRequest): - The request object. Request message for updating a - SecurityMarks resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{security_marks.name=organizations/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_marks.name=folders/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_marks.name=projects/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, - ] - request, metadata = self._interceptor.pre_update_security_marks(request, metadata) - pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_security_marks.SecurityMarks() - pb_resp = gcs_security_marks.SecurityMarks.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_security_marks(resp) - return resp - - class _UpdateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the update source method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSourceRequest): - The request object. Request message for updating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{source.name=organizations/*/sources/*}', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_update_source(request, metadata) - pb_request = securitycenter_service.UpdateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_source(resp) - return resp - - class _ValidateEventThreatDetectionCustomModule(SecurityCenterRestStub): - def __hash__(self): - return hash("ValidateEventThreatDetectionCustomModule") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: - r"""Call the validate event threat - detection custom module method over HTTP. - - Args: - request (~.securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): - The request object. Request to validate an Event Threat - Detection custom module. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse: - Response to validating an Event - Threat Detection custom module. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/eventThreatDetectionSettings}:validateCustomModule', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=folders/*/eventThreatDetectionSettings}:validateCustomModule', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/eventThreatDetectionSettings}:validateCustomModule', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_validate_event_threat_detection_custom_module(request, metadata) - pb_request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() - pb_resp = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_validate_event_threat_detection_custom_module(resp) - return resp - - @property - def batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - securitycenter_service.BatchCreateResourceValueConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchCreateResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - 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._BulkMuteFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.CreateEventThreatDetectionCustomModuleRequest], - gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest], - gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - 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._DeleteBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest], - 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._DeleteEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - 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._DeleteMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - 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._DeleteNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - 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._DeleteResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest], - 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._DeleteSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - bigquery_export.BigQueryExport]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_effective_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest], - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEffectiveEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_effective_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEffectiveSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.GetEventThreatDetectionCustomModuleRequest], - event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - mute_config.MuteConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - resource_value_config.ResourceValueConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest], - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - simulation.Simulation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSimulation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - valued_resource.ValuedResource]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetValuedResource(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - securitycenter_service.ListAttackPathsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListAttackPaths(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - securitycenter_service.ListBigQueryExportsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListBigQueryExports(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_descendant_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest], - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDescendantEventThreatDetectionCustomModules(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_descendant_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDescendantSecurityHealthAnalyticsCustomModules(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_effective_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest], - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEffectiveEventThreatDetectionCustomModules(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_effective_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEffectiveSecurityHealthAnalyticsCustomModules(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_event_threat_detection_custom_modules(self) -> Callable[ - [securitycenter_service.ListEventThreatDetectionCustomModulesRequest], - securitycenter_service.ListEventThreatDetectionCustomModulesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEventThreatDetectionCustomModules(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.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_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - securitycenter_service.ListMuteConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListMuteConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListNotificationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - securitycenter_service.ListResourceValueConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_security_health_analytics_custom_modules(self) -> Callable[ - [securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest], - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSecurityHealthAnalyticsCustomModules(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSources(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - securitycenter_service.ListValuedResourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListValuedResources(self._session, self._host, self._interceptor) # type: ignore - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - 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._RunAssetDiscovery(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - 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._SetMute(self._session, self._host, self._interceptor) # type: ignore - - @property - def simulate_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest], - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SimulateSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest], - gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - gcs_external_system.ExternalSystem]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateExternalSystem(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - gcs_resource_value_config.ResourceValueConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_security_health_analytics_custom_module(self) -> Callable[ - [securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest], - gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSecurityHealthAnalyticsCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def validate_event_threat_detection_custom_module(self) -> Callable[ - [securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest], - securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ValidateEventThreatDetectionCustomModule(self._session, self._host, self._interceptor) # type: ignore - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=organizations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In 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(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In 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(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), 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(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/operations}', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SecurityCenterRestTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py deleted file mode 100644 index fae209c726d0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/__init__.py +++ /dev/null @@ -1,440 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .access import ( - Access, - Geolocation, - ServiceAccountDelegationInfo, -) -from .application import ( - Application, -) -from .asset import ( - Asset, -) -from .attack_exposure import ( - AttackExposure, -) -from .attack_path import ( - AttackPath, -) -from .backup_disaster_recovery import ( - BackupDisasterRecovery, -) -from .bigquery_export import ( - BigQueryExport, -) -from .cloud_armor import ( - AdaptiveProtection, - Attack, - CloudArmor, - Requests, - SecurityPolicy, -) -from .cloud_dlp_data_profile import ( - CloudDlpDataProfile, -) -from .cloud_dlp_inspection import ( - CloudDlpInspection, -) -from .compliance import ( - Compliance, -) -from .connection import ( - Connection, -) -from .contact_details import ( - Contact, - ContactDetails, -) -from .container import ( - Container, -) -from .database import ( - Database, -) -from .effective_event_threat_detection_custom_module import ( - EffectiveEventThreatDetectionCustomModule, -) -from .effective_security_health_analytics_custom_module import ( - EffectiveSecurityHealthAnalyticsCustomModule, -) -from .event_threat_detection_custom_module import ( - EventThreatDetectionCustomModule, -) -from .event_threat_detection_custom_module_validation_errors import ( - CustomModuleValidationError, - CustomModuleValidationErrors, - Position, -) -from .exfiltration import ( - ExfilResource, - Exfiltration, -) -from .external_system import ( - ExternalSystem, -) -from .file import ( - File, -) -from .finding import ( - Finding, -) -from .folder import ( - Folder, -) -from .group_membership import ( - GroupMembership, -) -from .iam_binding import ( - IamBinding, -) -from .indicator import ( - Indicator, -) -from .kernel_rootkit import ( - KernelRootkit, -) -from .kubernetes import ( - Kubernetes, -) -from .label import ( - Label, -) -from .load_balancer import ( - LoadBalancer, -) -from .log_entry import ( - CloudLoggingEntry, - LogEntry, -) -from .mitre_attack import ( - MitreAttack, -) -from .mute_config import ( - MuteConfig, -) -from .notebook import ( - Notebook, -) -from .notification_config import ( - NotificationConfig, -) -from .notification_message import ( - NotificationMessage, -) -from .org_policy import ( - OrgPolicy, -) -from .organization_settings import ( - OrganizationSettings, -) -from .process import ( - EnvironmentVariable, - Process, -) -from .resource import ( - AwsMetadata, - AzureMetadata, - Resource, - ResourcePath, - CloudProvider, -) -from .resource_value_config import ( - ResourceValueConfig, - ResourceValue, -) -from .run_asset_discovery_response import ( - RunAssetDiscoveryResponse, -) -from .security_health_analytics_custom_config import ( - CustomConfig, -) -from .security_health_analytics_custom_module import ( - SecurityHealthAnalyticsCustomModule, -) -from .security_marks import ( - SecurityMarks, -) -from .security_posture import ( - SecurityPosture, -) -from .securitycenter_service import ( - BatchCreateResourceValueConfigsRequest, - BatchCreateResourceValueConfigsResponse, - BulkMuteFindingsRequest, - BulkMuteFindingsResponse, - CreateBigQueryExportRequest, - CreateEventThreatDetectionCustomModuleRequest, - CreateFindingRequest, - CreateMuteConfigRequest, - CreateNotificationConfigRequest, - CreateResourceValueConfigRequest, - CreateSecurityHealthAnalyticsCustomModuleRequest, - CreateSourceRequest, - DeleteBigQueryExportRequest, - DeleteEventThreatDetectionCustomModuleRequest, - DeleteMuteConfigRequest, - DeleteNotificationConfigRequest, - DeleteResourceValueConfigRequest, - DeleteSecurityHealthAnalyticsCustomModuleRequest, - GetBigQueryExportRequest, - GetEffectiveEventThreatDetectionCustomModuleRequest, - GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, - GetEventThreatDetectionCustomModuleRequest, - GetMuteConfigRequest, - GetNotificationConfigRequest, - GetOrganizationSettingsRequest, - GetResourceValueConfigRequest, - GetSecurityHealthAnalyticsCustomModuleRequest, - GetSimulationRequest, - GetSourceRequest, - GetValuedResourceRequest, - GroupAssetsRequest, - GroupAssetsResponse, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListAssetsRequest, - ListAssetsResponse, - ListAttackPathsRequest, - ListAttackPathsResponse, - ListBigQueryExportsRequest, - ListBigQueryExportsResponse, - ListDescendantEventThreatDetectionCustomModulesRequest, - ListDescendantEventThreatDetectionCustomModulesResponse, - ListDescendantSecurityHealthAnalyticsCustomModulesRequest, - ListDescendantSecurityHealthAnalyticsCustomModulesResponse, - ListEffectiveEventThreatDetectionCustomModulesRequest, - ListEffectiveEventThreatDetectionCustomModulesResponse, - ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, - ListEffectiveSecurityHealthAnalyticsCustomModulesResponse, - ListEventThreatDetectionCustomModulesRequest, - ListEventThreatDetectionCustomModulesResponse, - ListFindingsRequest, - ListFindingsResponse, - ListMuteConfigsRequest, - ListMuteConfigsResponse, - ListNotificationConfigsRequest, - ListNotificationConfigsResponse, - ListResourceValueConfigsRequest, - ListResourceValueConfigsResponse, - ListSecurityHealthAnalyticsCustomModulesRequest, - ListSecurityHealthAnalyticsCustomModulesResponse, - ListSourcesRequest, - ListSourcesResponse, - ListValuedResourcesRequest, - ListValuedResourcesResponse, - RunAssetDiscoveryRequest, - SetFindingStateRequest, - SetMuteRequest, - SimulateSecurityHealthAnalyticsCustomModuleRequest, - SimulateSecurityHealthAnalyticsCustomModuleResponse, - UpdateBigQueryExportRequest, - UpdateEventThreatDetectionCustomModuleRequest, - UpdateExternalSystemRequest, - UpdateFindingRequest, - UpdateMuteConfigRequest, - UpdateNotificationConfigRequest, - UpdateOrganizationSettingsRequest, - UpdateResourceValueConfigRequest, - UpdateSecurityHealthAnalyticsCustomModuleRequest, - UpdateSecurityMarksRequest, - UpdateSourceRequest, - ValidateEventThreatDetectionCustomModuleRequest, - ValidateEventThreatDetectionCustomModuleResponse, -) -from .simulation import ( - Simulation, -) -from .source import ( - Source, -) -from .toxic_combination import ( - ToxicCombination, -) -from .valued_resource import ( - ResourceValueConfigMetadata, - ValuedResource, -) -from .vulnerability import ( - Cve, - Cvssv3, - Package, - Reference, - SecurityBulletin, - Vulnerability, -) - -__all__ = ( - 'Access', - 'Geolocation', - 'ServiceAccountDelegationInfo', - 'Application', - 'Asset', - 'AttackExposure', - 'AttackPath', - 'BackupDisasterRecovery', - 'BigQueryExport', - 'AdaptiveProtection', - 'Attack', - 'CloudArmor', - 'Requests', - 'SecurityPolicy', - 'CloudDlpDataProfile', - 'CloudDlpInspection', - 'Compliance', - 'Connection', - 'Contact', - 'ContactDetails', - 'Container', - 'Database', - 'EffectiveEventThreatDetectionCustomModule', - 'EffectiveSecurityHealthAnalyticsCustomModule', - 'EventThreatDetectionCustomModule', - 'CustomModuleValidationError', - 'CustomModuleValidationErrors', - 'Position', - 'ExfilResource', - 'Exfiltration', - 'ExternalSystem', - 'File', - 'Finding', - 'Folder', - 'GroupMembership', - 'IamBinding', - 'Indicator', - 'KernelRootkit', - 'Kubernetes', - 'Label', - 'LoadBalancer', - 'CloudLoggingEntry', - 'LogEntry', - 'MitreAttack', - 'MuteConfig', - 'Notebook', - 'NotificationConfig', - 'NotificationMessage', - 'OrgPolicy', - 'OrganizationSettings', - 'EnvironmentVariable', - 'Process', - 'AwsMetadata', - 'AzureMetadata', - 'Resource', - 'ResourcePath', - 'CloudProvider', - 'ResourceValueConfig', - 'ResourceValue', - 'RunAssetDiscoveryResponse', - 'CustomConfig', - 'SecurityHealthAnalyticsCustomModule', - 'SecurityMarks', - 'SecurityPosture', - 'BatchCreateResourceValueConfigsRequest', - 'BatchCreateResourceValueConfigsResponse', - 'BulkMuteFindingsRequest', - 'BulkMuteFindingsResponse', - 'CreateBigQueryExportRequest', - 'CreateEventThreatDetectionCustomModuleRequest', - 'CreateFindingRequest', - 'CreateMuteConfigRequest', - 'CreateNotificationConfigRequest', - 'CreateResourceValueConfigRequest', - 'CreateSecurityHealthAnalyticsCustomModuleRequest', - 'CreateSourceRequest', - 'DeleteBigQueryExportRequest', - 'DeleteEventThreatDetectionCustomModuleRequest', - 'DeleteMuteConfigRequest', - 'DeleteNotificationConfigRequest', - 'DeleteResourceValueConfigRequest', - 'DeleteSecurityHealthAnalyticsCustomModuleRequest', - 'GetBigQueryExportRequest', - 'GetEffectiveEventThreatDetectionCustomModuleRequest', - 'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', - 'GetEventThreatDetectionCustomModuleRequest', - 'GetMuteConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetResourceValueConfigRequest', - 'GetSecurityHealthAnalyticsCustomModuleRequest', - 'GetSimulationRequest', - 'GetSourceRequest', - 'GetValuedResourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListAttackPathsRequest', - 'ListAttackPathsResponse', - 'ListBigQueryExportsRequest', - 'ListBigQueryExportsResponse', - 'ListDescendantEventThreatDetectionCustomModulesRequest', - 'ListDescendantEventThreatDetectionCustomModulesResponse', - 'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', - 'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', - 'ListEffectiveEventThreatDetectionCustomModulesRequest', - 'ListEffectiveEventThreatDetectionCustomModulesResponse', - 'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', - 'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', - 'ListEventThreatDetectionCustomModulesRequest', - 'ListEventThreatDetectionCustomModulesResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListMuteConfigsRequest', - 'ListMuteConfigsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListResourceValueConfigsRequest', - 'ListResourceValueConfigsResponse', - 'ListSecurityHealthAnalyticsCustomModulesRequest', - 'ListSecurityHealthAnalyticsCustomModulesResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListValuedResourcesRequest', - 'ListValuedResourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'SetMuteRequest', - 'SimulateSecurityHealthAnalyticsCustomModuleRequest', - 'SimulateSecurityHealthAnalyticsCustomModuleResponse', - 'UpdateBigQueryExportRequest', - 'UpdateEventThreatDetectionCustomModuleRequest', - 'UpdateExternalSystemRequest', - 'UpdateFindingRequest', - 'UpdateMuteConfigRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateResourceValueConfigRequest', - 'UpdateSecurityHealthAnalyticsCustomModuleRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'ValidateEventThreatDetectionCustomModuleRequest', - 'ValidateEventThreatDetectionCustomModuleResponse', - 'Simulation', - 'Source', - 'ToxicCombination', - 'ResourceValueConfigMetadata', - 'ValuedResource', - 'Cve', - 'Cvssv3', - 'Package', - 'Reference', - 'SecurityBulletin', - 'Vulnerability', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py deleted file mode 100644 index 46f1bc1e8a57..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/access.py +++ /dev/null @@ -1,193 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v1', - manifest={ - 'Access', - 'ServiceAccountDelegationInfo', - 'Geolocation', - }, -) - - -class Access(proto.Message): - r"""Represents an access event. - - Attributes: - principal_email (str): - Associated email, such as "foo@google.com". - - The email address of the authenticated user or a service - account acting on behalf of a third party principal making - the request. For third party identity callers, the - ``principal_subject`` field is populated instead of this - field. For privacy reasons, the principal email address is - sometimes redacted. For more information, see `Caller - identities in audit - logs `__. - caller_ip (str): - Caller's IP address, such as "1.1.1.1". - caller_ip_geo (google.cloud.securitycenter_v1.types.Geolocation): - The caller IP's geolocation, which identifies - where the call came from. - user_agent_family (str): - Type of user agent associated with the - finding. For example, an operating system shell - or an embedded or standalone application. - user_agent (str): - The caller's user agent string associated - with the finding. - service_name (str): - This is the API service that the service - account made a call to, e.g. - "iam.googleapis.com". - method_name (str): - The method that the service account called, - e.g. "SetIamPolicy". - principal_subject (str): - A string that represents the principal_subject that is - associated with the identity. Unlike ``principal_email``, - ``principal_subject`` supports principals that aren't - associated with email addresses, such as third party - principals. For most identities, the format is - ``principal://iam.googleapis.com/{identity pool name}/subject/{subject}``. - Some GKE identities, such as GKE_WORKLOAD, FREEFORM, and - GKE_HUB_WORKLOAD, still use the legacy format - ``serviceAccount:{identity pool name}[{subject}]``. - service_account_key_name (str): - The name of the service account key that was used to create - or exchange credentials when authenticating the service - account that made the request. This is a scheme-less URI - full resource name. For example: - - "//iam.googleapis.com/projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}". - service_account_delegation_info (MutableSequence[google.cloud.securitycenter_v1.types.ServiceAccountDelegationInfo]): - The identity delegation history of an authenticated service - account that made the request. The - ``serviceAccountDelegationInfo[]`` object contains - information about the real authorities that try to access - Google Cloud resources by delegating on a service account. - When multiple authorities are present, they are guaranteed - to be sorted based on the original ordering of the identity - delegation events. - user_name (str): - A string that represents a username. The - username provided depends on the type of the - finding and is likely not an IAM principal. For - example, this can be a system username if the - finding is related to a virtual machine, or it - can be an application login username. - """ - - principal_email: str = proto.Field( - proto.STRING, - number=1, - ) - caller_ip: str = proto.Field( - proto.STRING, - number=2, - ) - caller_ip_geo: 'Geolocation' = proto.Field( - proto.MESSAGE, - number=3, - message='Geolocation', - ) - user_agent_family: str = proto.Field( - proto.STRING, - number=4, - ) - user_agent: str = proto.Field( - proto.STRING, - number=12, - ) - service_name: str = proto.Field( - proto.STRING, - number=5, - ) - method_name: str = proto.Field( - proto.STRING, - number=6, - ) - principal_subject: str = proto.Field( - proto.STRING, - number=7, - ) - service_account_key_name: str = proto.Field( - proto.STRING, - number=8, - ) - service_account_delegation_info: MutableSequence['ServiceAccountDelegationInfo'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='ServiceAccountDelegationInfo', - ) - user_name: str = proto.Field( - proto.STRING, - number=11, - ) - - -class ServiceAccountDelegationInfo(proto.Message): - r"""Identity delegation history of an authenticated service - account. - - Attributes: - principal_email (str): - The email address of a Google account. - principal_subject (str): - A string representing the principal_subject associated with - the identity. As compared to ``principal_email``, supports - principals that aren't associated with email addresses, such - as third party principals. For most identities, the format - will be - ``principal://iam.googleapis.com/{identity pool name}/subjects/{subject}`` - except for some GKE identities (GKE_WORKLOAD, FREEFORM, - GKE_HUB_WORKLOAD) that are still in the legacy format - ``serviceAccount:{identity pool name}[{subject}]`` - """ - - principal_email: str = proto.Field( - proto.STRING, - number=1, - ) - principal_subject: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Geolocation(proto.Message): - r"""Represents a geographical location for a given access. - - Attributes: - region_code (str): - A CLDR. - """ - - region_code: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.py deleted file mode 100644 index 96e0a3cd61dc..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/application.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Application', - }, -) - - -class Application(proto.Message): - r"""Represents an application associated with a finding. - - Attributes: - base_uri (str): - The base URI that identifies the network location of the - application in which the vulnerability was detected. For - example, ``http://example.com``. - full_uri (str): - The full URI with payload that can be used to reproduce the - vulnerability. For example, - ``http://example.com?p=aMmYgI6H``. - """ - - base_uri: str = proto.Field( - proto.STRING, - number=1, - ) - full_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py deleted file mode 100644 index 5c4a957c4d1e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/asset.py +++ /dev/null @@ -1,227 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1.types import folder -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Asset', - }, -) - - -class Asset(proto.Message): - r"""Security Command Center representation of a Google Cloud - resource. - - The Asset is a Security Command Center resource that captures - information about a single Google Cloud resource. All - modifications to an Asset are only within the context of - Security Command Center and don't affect the referenced Google - Cloud resource. - - Attributes: - name (str): - The relative resource name of this asset. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (google.cloud.securitycenter_v1.types.Asset.SecurityCenterProperties): - Security Command Center managed properties. - These properties are managed by Security Command - Center and cannot be modified by the user. - resource_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Resource managed properties. These properties - are managed and defined by the Google Cloud - resource and cannot be modified by the user. - security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): - User specified security marks. These marks - are entirely managed by the user and come from - the SecurityMarks resource that belongs to the - asset. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was created in - Security Command Center. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was last updated - or added in Cloud SCC. - iam_policy (google.cloud.securitycenter_v1.types.Asset.IamPolicy): - Cloud IAM Policy information associated with - the Google Cloud resource described by the - Security Command Center asset. This information - is managed and defined by the Google Cloud - resource and cannot be modified by the user. - canonical_name (str): - The canonical name of the resource. It's either - "organizations/{organization_id}/assets/{asset_id}", - "folders/{folder_id}/assets/{asset_id}" or - "projects/{project_number}/assets/{asset_id}", depending on - the closest CRM ancestor of the resource. - """ - - class SecurityCenterProperties(proto.Message): - r"""Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified by - the user. - - Attributes: - resource_name (str): - The full resource name of the Google Cloud resource this - asset represents. This field is immutable after create time. - See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_type (str): - The type of the Google Cloud resource. - Examples include: APPLICATION, PROJECT, and - ORGANIZATION. This is a case insensitive field - defined by Security Command Center and/or the - producer of the resource and is immutable after - create time. - resource_parent (str): - The full resource name of the immediate parent of the - resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_project (str): - The full resource name of the project the resource belongs - to. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_owners (MutableSequence[str]): - Owners of the Google Cloud resource. - resource_display_name (str): - The user defined display name for this - resource. - resource_parent_display_name (str): - The user defined display name for the parent - of this resource. - resource_project_display_name (str): - The user defined display name for the project - of this resource. - folders (MutableSequence[google.cloud.securitycenter_v1.types.Folder]): - Contains a Folder message for each folder in - the assets ancestry. The first folder is the - deepest nested folder, and the last folder is - the folder directly under the Organization. - """ - - resource_name: str = proto.Field( - proto.STRING, - number=1, - ) - resource_type: str = proto.Field( - proto.STRING, - number=2, - ) - resource_parent: str = proto.Field( - proto.STRING, - number=3, - ) - resource_project: str = proto.Field( - proto.STRING, - number=4, - ) - resource_owners: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - resource_display_name: str = proto.Field( - proto.STRING, - number=6, - ) - resource_parent_display_name: str = proto.Field( - proto.STRING, - number=7, - ) - resource_project_display_name: str = proto.Field( - proto.STRING, - number=8, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=folder.Folder, - ) - - class IamPolicy(proto.Message): - r"""Cloud IAM Policy information associated with the Google Cloud - resource described by the Security Command Center asset. This - information is managed and defined by the Google Cloud resource - and cannot be modified by the user. - - Attributes: - policy_blob (str): - The JSON representation of the Policy - associated with the asset. See - https://cloud.google.com/iam/reference/rest/v1/Policy - for format details. - """ - - policy_blob: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - security_center_properties: SecurityCenterProperties = proto.Field( - proto.MESSAGE, - number=2, - message=SecurityCenterProperties, - ) - resource_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - iam_policy: IamPolicy = proto.Field( - proto.MESSAGE, - number=11, - message=IamPolicy, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=13, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.py deleted file mode 100644 index 71c641c4f226..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_exposure.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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'AttackExposure', - }, -) - - -class AttackExposure(proto.Message): - r"""An attack exposure contains the results of an attack path - simulation run. - - Attributes: - score (float): - A number between 0 (inclusive) and infinity - that represents how important this finding is to - remediate. The higher the score, the more - important it is to remediate. - latest_calculation_time (google.protobuf.timestamp_pb2.Timestamp): - The most recent time the attack exposure was - updated on this finding. - attack_exposure_result (str): - The resource name of the attack path simulation result that - contains the details regarding this attack exposure score. - Example: - ``organizations/123/simulations/456/attackExposureResults/789`` - state (google.cloud.securitycenter_v1.types.AttackExposure.State): - What state this AttackExposure is in. This - captures whether or not an attack exposure has - been calculated or not. - exposed_high_value_resources_count (int): - The number of high value resources that are - exposed as a result of this finding. - exposed_medium_value_resources_count (int): - The number of medium value resources that are - exposed as a result of this finding. - exposed_low_value_resources_count (int): - The number of high value resources that are - exposed as a result of this finding. - """ - class State(proto.Enum): - r"""This enum defines the various states an AttackExposure can be - in. - - Values: - STATE_UNSPECIFIED (0): - The state is not specified. - CALCULATED (1): - The attack exposure has been calculated. - NOT_CALCULATED (2): - The attack exposure has not been calculated. - """ - STATE_UNSPECIFIED = 0 - CALCULATED = 1 - NOT_CALCULATED = 2 - - score: float = proto.Field( - proto.DOUBLE, - number=1, - ) - latest_calculation_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - attack_exposure_result: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - exposed_high_value_resources_count: int = proto.Field( - proto.INT32, - number=5, - ) - exposed_medium_value_resources_count: int = proto.Field( - proto.INT32, - number=6, - ) - exposed_low_value_resources_count: int = proto.Field( - proto.INT32, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py deleted file mode 100644 index d298b28f7407..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/attack_path.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v1', - manifest={ - 'AttackPath', - }, -) - - -class AttackPath(proto.Message): - r"""A path that an attacker could take to reach an exposed - resource. - - Attributes: - name (str): - The attack path name, for example, - ``organizations/12/simulation/34/valuedResources/56/attackPaths/78`` - path_nodes (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode]): - A list of nodes that exist in this attack - path. - edges (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathEdge]): - A list of the edges between nodes in this - attack path. - """ - - class AttackPathNode(proto.Message): - r"""Represents one point that an attacker passes through in this - attack path. - - Attributes: - resource (str): - The name of the resource at this point in the attack path. - The format of the name follows the Cloud Asset Inventory - `resource name - format `__ - resource_type (str): - The `supported resource - type `__ - display_name (str): - Human-readable name of this resource. - associated_findings (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode.PathNodeAssociatedFinding]): - The findings associated with this node in the - attack path. - uuid (str): - Unique id of the attack path node. - attack_steps (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode.AttackStepNode]): - A list of attack step nodes that exist in - this attack path node. - """ - class NodeType(proto.Enum): - r"""The type of the incoming attack step node. - - Values: - NODE_TYPE_UNSPECIFIED (0): - Type not specified - NODE_TYPE_AND (1): - Incoming edge joined with AND - NODE_TYPE_OR (2): - Incoming edge joined with OR - NODE_TYPE_DEFENSE (3): - Incoming edge is defense - NODE_TYPE_ATTACKER (4): - Incoming edge is attacker - """ - NODE_TYPE_UNSPECIFIED = 0 - NODE_TYPE_AND = 1 - NODE_TYPE_OR = 2 - NODE_TYPE_DEFENSE = 3 - NODE_TYPE_ATTACKER = 4 - - class PathNodeAssociatedFinding(proto.Message): - r"""A finding that is associated with this node in the attack - path. - - Attributes: - canonical_finding (str): - Canonical name of the associated findings. Example: - ``organizations/123/sources/456/findings/789`` - finding_category (str): - The additional taxonomy group within findings - from a given source. - name (str): - Full resource name of the finding. - """ - - canonical_finding: str = proto.Field( - proto.STRING, - number=1, - ) - finding_category: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - class AttackStepNode(proto.Message): - r"""Detailed steps the attack can take between path nodes. - - Attributes: - uuid (str): - Unique ID for one Node - type_ (google.cloud.securitycenter_v1.types.AttackPath.AttackPathNode.NodeType): - Attack step type. Can be either AND, OR or - DEFENSE - display_name (str): - User friendly name of the attack step - labels (MutableMapping[str, str]): - Attack step labels for metadata - description (str): - Attack step description - """ - - uuid: str = proto.Field( - proto.STRING, - number=1, - ) - type_: 'AttackPath.AttackPathNode.NodeType' = proto.Field( - proto.ENUM, - number=2, - enum='AttackPath.AttackPathNode.NodeType', - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - description: str = proto.Field( - proto.STRING, - number=5, - ) - - resource: str = proto.Field( - proto.STRING, - number=1, - ) - resource_type: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - associated_findings: MutableSequence['AttackPath.AttackPathNode.PathNodeAssociatedFinding'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='AttackPath.AttackPathNode.PathNodeAssociatedFinding', - ) - uuid: str = proto.Field( - proto.STRING, - number=5, - ) - attack_steps: MutableSequence['AttackPath.AttackPathNode.AttackStepNode'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='AttackPath.AttackPathNode.AttackStepNode', - ) - - class AttackPathEdge(proto.Message): - r"""Represents a connection between a source node and a - destination node in this attack path. - - Attributes: - source (str): - The attack node uuid of the source node. - destination (str): - The attack node uuid of the destination node. - """ - - source: str = proto.Field( - proto.STRING, - number=1, - ) - destination: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - path_nodes: MutableSequence[AttackPathNode] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=AttackPathNode, - ) - edges: MutableSequence[AttackPathEdge] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=AttackPathEdge, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py deleted file mode 100644 index 2497cff8afd8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/backup_disaster_recovery.py +++ /dev/null @@ -1,137 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v1', - manifest={ - 'BackupDisasterRecovery', - }, -) - - -class BackupDisasterRecovery(proto.Message): - r"""Information related to Google Cloud Backup and DR Service - findings. - - Attributes: - backup_template (str): - The name of a Backup and DR template which comprises one or - more backup policies. See the `Backup and DR - documentation `__ - for more information. For example, ``snap-ov``. - policies (MutableSequence[str]): - The names of Backup and DR policies that are associated with - a template and that define when to run a backup, how - frequently to run a backup, and how long to retain the - backup image. For example, ``onvaults``. - host (str): - The name of a Backup and DR host, which is managed by the - backup and recovery appliance and known to the management - console. The host can be of type Generic (for example, - Compute Engine, SQL Server, Oracle DB, SMB file system, - etc.), vCenter, or an ESX server. See the `Backup and DR - documentation on - hosts `__ - for more information. For example, ``centos7-01``. - applications (MutableSequence[str]): - The names of Backup and DR applications. An application is a - VM, database, or file system on a managed host monitored by - a backup and recovery appliance. For example, - ``centos7-01-vol00``, ``centos7-01-vol01``, - ``centos7-01-vol02``. - storage_pool (str): - The name of the Backup and DR storage pool that the backup - and recovery appliance is storing data in. The storage pool - could be of type Cloud, Primary, Snapshot, or OnVault. See - the `Backup and DR documentation on storage - pools `__. - For example, ``DiskPoolOne``. - policy_options (MutableSequence[str]): - The names of Backup and DR advanced policy options of a - policy applying to an application. See the `Backup and DR - documentation on policy - options `__. - For example, ``skipofflineappsincongrp, nounmap``. - profile (str): - The name of the Backup and DR resource profile that - specifies the storage media for backups of application and - VM data. See the `Backup and DR documentation on - profiles `__. - For example, ``GCP``. - appliance (str): - The name of the Backup and DR appliance that captures, - moves, and manages the lifecycle of backup data. For - example, ``backup-server-57137``. - backup_type (str): - The backup type of the Backup and DR image. For example, - ``Snapshot``, ``Remote Snapshot``, ``OnVault``. - backup_create_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp at which the Backup and DR - backup was created. - """ - - backup_template: str = proto.Field( - proto.STRING, - number=1, - ) - policies: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - host: str = proto.Field( - proto.STRING, - number=3, - ) - applications: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - storage_pool: str = proto.Field( - proto.STRING, - number=5, - ) - policy_options: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - profile: str = proto.Field( - proto.STRING, - number=7, - ) - appliance: str = proto.Field( - proto.STRING, - number=8, - ) - backup_type: str = proto.Field( - proto.STRING, - number=9, - ) - backup_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py deleted file mode 100644 index 9e8288f7fd7b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/bigquery_export.py +++ /dev/null @@ -1,135 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v1', - manifest={ - 'BigQueryExport', - }, -) - - -class BigQueryExport(proto.Message): - r"""Configures how to deliver Findings to BigQuery Instance. - - Attributes: - name (str): - The relative resource name of this export. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name. - Example format: - "organizations/{organization_id}/bigQueryExports/{export_id}" - Example format: - "folders/{folder_id}/bigQueryExports/{export_id}" Example - format: "projects/{project_id}/bigQueryExports/{export_id}" - This field is provided in responses, and is ignored when - provided in create requests. - description (str): - The description of the export (max of 1024 - characters). - filter (str): - Expression that defines the filter to apply across - create/update events of findings. The expression is a list - of zero or more restrictions combined via logical operators - ``AND`` and ``OR``. Parentheses are supported, and ``OR`` - has higher precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - dataset (str): - The dataset to write findings' updates to. Its format is - "projects/[project_id]/datasets/[bigquery_dataset_id]". - BigQuery Dataset unique ID must contain only letters (a-z, - A-Z), numbers (0-9), or underscores (_). - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the BigQuery - export was created. This field is set by the - server and will be ignored if provided on export - on creation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The most recent time at which - the BigQuery export was updated. This field is - set by the server and will be ignored if - provided on export creation or update. - most_recent_editor (str): - Output only. Email address of the user who - last edited the BigQuery export. This field is - set by the server and will be ignored if - provided on export creation or update. - principal (str): - Output only. The service account that needs - permission to create table and upload data to - the BigQuery dataset. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - filter: str = proto.Field( - proto.STRING, - number=3, - ) - dataset: 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, - ) - most_recent_editor: str = proto.Field( - proto.STRING, - number=7, - ) - principal: str = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.py deleted file mode 100644 index 45b7e2fb7d51..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_armor.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.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'CloudArmor', - 'SecurityPolicy', - 'Requests', - 'AdaptiveProtection', - 'Attack', - }, -) - - -class CloudArmor(proto.Message): - r"""Fields related to Google Cloud Armor findings. - - Attributes: - security_policy (google.cloud.securitycenter_v1.types.SecurityPolicy): - Information about the `Google Cloud Armor security - policy `__ - relevant to the finding. - requests (google.cloud.securitycenter_v1.types.Requests): - Information about incoming requests evaluated by `Google - Cloud Armor security - policies `__. - adaptive_protection (google.cloud.securitycenter_v1.types.AdaptiveProtection): - Information about potential Layer 7 DDoS attacks identified - by `Google Cloud Armor Adaptive - Protection `__. - attack (google.cloud.securitycenter_v1.types.Attack): - Information about DDoS attack volume and - classification. - threat_vector (str): - Distinguish between volumetric & protocol DDoS attack and - application layer attacks. For example, "L3_4" for Layer 3 - and Layer 4 DDoS attacks, or "L_7" for Layer 7 DDoS attacks. - duration (google.protobuf.duration_pb2.Duration): - Duration of attack from the start until the - current moment (updated every 5 minutes). - """ - - security_policy: 'SecurityPolicy' = proto.Field( - proto.MESSAGE, - number=1, - message='SecurityPolicy', - ) - requests: 'Requests' = proto.Field( - proto.MESSAGE, - number=2, - message='Requests', - ) - adaptive_protection: 'AdaptiveProtection' = proto.Field( - proto.MESSAGE, - number=3, - message='AdaptiveProtection', - ) - attack: 'Attack' = proto.Field( - proto.MESSAGE, - number=4, - message='Attack', - ) - threat_vector: str = proto.Field( - proto.STRING, - number=5, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - - -class SecurityPolicy(proto.Message): - r"""Information about the `Google Cloud Armor security - policy `__ - relevant to the finding. - - Attributes: - name (str): - The name of the Google Cloud Armor security - policy, for example, "my-security-policy". - type_ (str): - The type of Google Cloud Armor security - policy for example, 'backend security policy', - 'edge security policy', 'network edge security - policy', or 'always-on DDoS protection'. - preview (bool): - Whether or not the associated rule or policy - is in preview mode. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - preview: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class Requests(proto.Message): - r"""Information about the requests relevant to the finding. - - Attributes: - ratio (float): - For 'Increasing deny ratio', the ratio is the - denied traffic divided by the allowed traffic. - For 'Allowed traffic spike', the ratio is the - allowed traffic in the short term divided by - allowed traffic in the long term. - short_term_allowed (int): - Allowed RPS (requests per second) in the - short term. - long_term_allowed (int): - Allowed RPS (requests per second) over the - long term. - long_term_denied (int): - Denied RPS (requests per second) over the - long term. - """ - - ratio: float = proto.Field( - proto.DOUBLE, - number=1, - ) - short_term_allowed: int = proto.Field( - proto.INT32, - number=2, - ) - long_term_allowed: int = proto.Field( - proto.INT32, - number=3, - ) - long_term_denied: int = proto.Field( - proto.INT32, - number=4, - ) - - -class AdaptiveProtection(proto.Message): - r"""Information about `Google Cloud Armor Adaptive - Protection `__. - - Attributes: - confidence (float): - A score of 0 means that there is low confidence that the - detected event is an actual attack. A score of 1 means that - there is high confidence that the detected event is an - attack. See the `Adaptive Protection - documentation `__ - for further explanation. - """ - - confidence: float = proto.Field( - proto.DOUBLE, - number=1, - ) - - -class Attack(proto.Message): - r"""Information about DDoS attack volume and classification. - - Attributes: - volume_pps (int): - Total PPS (packets per second) volume of - attack. - volume_bps (int): - Total BPS (bytes per second) volume of - attack. - classification (str): - Type of attack, for example, 'SYN-flood', - 'NTP-udp', or 'CHARGEN-udp'. - """ - - volume_pps: int = proto.Field( - proto.INT32, - number=1, - ) - volume_bps: int = proto.Field( - proto.INT32, - number=2, - ) - classification: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.py deleted file mode 100644 index 52cece2651fc..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_data_profile.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.cloud.securitycenter.v1', - manifest={ - 'CloudDlpDataProfile', - }, -) - - -class CloudDlpDataProfile(proto.Message): - r"""The `data - profile `__ - associated with the finding. - - Attributes: - data_profile (str): - Name of the data profile, for example, - ``projects/123/locations/europe/tableProfiles/8383929``. - parent_type (google.cloud.securitycenter_v1.types.CloudDlpDataProfile.ParentType): - The resource hierarchy level at which the - data profile was generated. - """ - class ParentType(proto.Enum): - r"""Parents for configurations that produce data profile - findings. - - Values: - PARENT_TYPE_UNSPECIFIED (0): - Unspecified parent type. - ORGANIZATION (1): - Organization-level configurations. - PROJECT (2): - Project-level configurations. - """ - PARENT_TYPE_UNSPECIFIED = 0 - ORGANIZATION = 1 - PROJECT = 2 - - data_profile: str = proto.Field( - proto.STRING, - number=1, - ) - parent_type: ParentType = proto.Field( - proto.ENUM, - number=2, - enum=ParentType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.py deleted file mode 100644 index 46b9848965a8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/cloud_dlp_inspection.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'CloudDlpInspection', - }, -) - - -class CloudDlpInspection(proto.Message): - r"""Details about the Cloud Data Loss Prevention (Cloud DLP) `inspection - job `__ - that produced the finding. - - Attributes: - inspect_job (str): - Name of the inspection job, for example, - ``projects/123/locations/europe/dlpJobs/i-8383929``. - info_type (str): - The type of information (or - `infoType `__) - found, for example, ``EMAIL_ADDRESS`` or ``STREET_ADDRESS``. - info_type_count (int): - The number of times Cloud DLP found this - infoType within this job and resource. - full_scan (bool): - Whether Cloud DLP scanned the complete - resource or a sampled subset. - """ - - inspect_job: str = proto.Field( - proto.STRING, - number=1, - ) - info_type: str = proto.Field( - proto.STRING, - number=2, - ) - info_type_count: int = proto.Field( - proto.INT64, - number=3, - ) - full_scan: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.py deleted file mode 100644 index 432ca7841d82..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/compliance.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Compliance', - }, -) - - -class Compliance(proto.Message): - r"""Contains compliance information about a security standard - indicating unmet recommendations. - - Attributes: - standard (str): - Industry-wide compliance standards or - benchmarks, such as CIS, PCI, and OWASP. - version (str): - Version of the standard or benchmark, for - example, 1.1 - ids (MutableSequence[str]): - Policies within the standard or benchmark, - for example, A.12.4.1 - """ - - standard: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.py deleted file mode 100644 index 0f36fbdfd761..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/connection.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.cloud.securitycenter.v1', - manifest={ - 'Connection', - }, -) - - -class Connection(proto.Message): - r"""Contains information about the IP connection associated with - the finding. - - Attributes: - destination_ip (str): - Destination IP address. Not present for - sockets that are listening and not connected. - destination_port (int): - Destination port. Not present for sockets - that are listening and not connected. - source_ip (str): - Source IP address. - source_port (int): - Source port. - protocol (google.cloud.securitycenter_v1.types.Connection.Protocol): - IANA Internet Protocol Number such as TCP(6) - and UDP(17). - """ - class Protocol(proto.Enum): - r"""IANA Internet Protocol Number such as TCP(6) and UDP(17). - - Values: - PROTOCOL_UNSPECIFIED (0): - Unspecified protocol (not HOPOPT). - ICMP (1): - Internet Control Message Protocol. - TCP (6): - Transmission Control Protocol. - UDP (17): - User Datagram Protocol. - GRE (47): - Generic Routing Encapsulation. - ESP (50): - Encap Security Payload. - """ - PROTOCOL_UNSPECIFIED = 0 - ICMP = 1 - TCP = 6 - UDP = 17 - GRE = 47 - ESP = 50 - - destination_ip: str = proto.Field( - proto.STRING, - number=1, - ) - destination_port: int = proto.Field( - proto.INT32, - number=2, - ) - source_ip: str = proto.Field( - proto.STRING, - number=3, - ) - source_port: int = proto.Field( - proto.INT32, - number=4, - ) - protocol: Protocol = proto.Field( - proto.ENUM, - number=5, - enum=Protocol, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.py deleted file mode 100644 index 7fdd88c15c7e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/contact_details.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'ContactDetails', - 'Contact', - }, -) - - -class ContactDetails(proto.Message): - r"""Details about specific contacts - - Attributes: - contacts (MutableSequence[google.cloud.securitycenter_v1.types.Contact]): - A list of contacts - """ - - contacts: MutableSequence['Contact'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Contact', - ) - - -class Contact(proto.Message): - r"""The email address of a contact. - - Attributes: - email (str): - An email address. For example, "``person123@company.com``". - """ - - email: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.py deleted file mode 100644 index d953244d3583..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/container.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v1.types import label -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Container', - }, -) - - -class Container(proto.Message): - r"""Container associated with the finding. - - Attributes: - name (str): - Name of the container. - uri (str): - Container image URI provided when configuring - a pod or container. This string can identify a - container image version using mutable tags. - image_id (str): - Optional container image ID, if provided by - the container runtime. Uniquely identifies the - container image launched using a container image - digest. - labels (MutableSequence[google.cloud.securitycenter_v1.types.Label]): - Container labels, as provided by the - container runtime. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the container was created. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - image_id: str = proto.Field( - proto.STRING, - number=3, - ) - labels: MutableSequence[label.Label] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=label.Label, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.py deleted file mode 100644 index 3372ba324532..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/database.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Database', - }, -) - - -class Database(proto.Message): - r"""Represents database access information, such as queries. A database - may be a sub-resource of an instance (as in the case of Cloud SQL - instances or Cloud Spanner instances), or the database instance - itself. Some database resources might not have the `full resource - name `__ populated - because these resource types, such as Cloud SQL databases, are not - yet supported by Cloud Asset Inventory. In these cases only the - display name is provided. - - Attributes: - name (str): - Some database resources may not have the `full resource - name `__ - populated because these resource types are not yet supported - by Cloud Asset Inventory (e.g. Cloud SQL databases). In - these cases only the display name will be provided. The - `full resource - name `__ of - the database that the user connected to, if it is supported - by Cloud Asset Inventory. - display_name (str): - The human-readable name of the database that - the user connected to. - user_name (str): - The username used to connect to the database. - The username might not be an IAM principal and - does not have a set format. - query (str): - The SQL statement that is associated with the - database access. - grantees (MutableSequence[str]): - The target usernames, roles, or groups of an - SQL privilege grant, which is not an IAM policy - change. - version (str): - The version of the database, for example, POSTGRES_14. See - `the complete - list `__. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - user_name: str = proto.Field( - proto.STRING, - number=3, - ) - query: str = proto.Field( - proto.STRING, - number=4, - ) - grantees: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - version: str = proto.Field( - proto.STRING, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.py deleted file mode 100644 index ba51ed0b1ec6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_event_threat_detection_custom_module.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.cloud.securitycenter.v1', - manifest={ - 'EffectiveEventThreatDetectionCustomModule', - }, -) - - -class EffectiveEventThreatDetectionCustomModule(proto.Message): - r"""An EffectiveEventThreatDetectionCustomModule is the representation - of an Event Threat Detection custom module at a specified level of - the resource hierarchy: organization, folder, or project. If a - custom module is inherited from a parent organization or folder, the - value of the ``enablement_state`` property in - EffectiveEventThreatDetectionCustomModule is set to the value that - is effective in the parent, instead of ``INHERITED``. For example, - if the module is enabled in a parent organization or folder, the - effective ``enablement_state`` for the module in all child folders - or projects is also ``enabled``. - EffectiveEventThreatDetectionCustomModule is read-only. - - Attributes: - name (str): - Output only. The resource name of the effective ETD custom - module. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - config (google.protobuf.struct_pb2.Struct): - Output only. Config for the effective module. - enablement_state (google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule.EnablementState): - Output only. The effective state of - enablement for the module at the given level of - the hierarchy. - type_ (str): - Output only. Type for the module. e.g. CONFIGURABLE_BAD_IP. - display_name (str): - Output only. The human readable name to be - displayed for the module. - description (str): - Output only. The description for the module. - """ - class EnablementState(proto.Enum): - r"""The enablement state of the module. - - Values: - ENABLEMENT_STATE_UNSPECIFIED (0): - Unspecified enablement state. - ENABLED (1): - The module is enabled at the given level. - DISABLED (2): - The module is disabled at the given level. - """ - ENABLEMENT_STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - config: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - enablement_state: EnablementState = proto.Field( - proto.ENUM, - number=3, - enum=EnablementState, - ) - type_: str = proto.Field( - proto.STRING, - number=4, - ) - display_name: str = proto.Field( - proto.STRING, - number=5, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.py deleted file mode 100644 index 2396c38d1aaf..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/effective_security_health_analytics_custom_module.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'EffectiveSecurityHealthAnalyticsCustomModule', - }, -) - - -class EffectiveSecurityHealthAnalyticsCustomModule(proto.Message): - r"""An EffectiveSecurityHealthAnalyticsCustomModule is the - representation of a Security Health Analytics custom module at a - specified level of the resource hierarchy: organization, folder, or - project. If a custom module is inherited from a parent organization - or folder, the value of the ``enablementState`` property in - EffectiveSecurityHealthAnalyticsCustomModule is set to the value - that is effective in the parent, instead of ``INHERITED``. For - example, if the module is enabled in a parent organization or - folder, the effective enablement_state for the module in all child - folders or projects is also ``enabled``. - EffectiveSecurityHealthAnalyticsCustomModule is read-only. - - Attributes: - name (str): - Output only. The resource name of the custom - module. Its format is - "organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}", - or - "folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}", - or - "projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}". - custom_config (google.cloud.securitycenter_v1.types.CustomConfig): - Output only. The user-specified configuration - for the module. - enablement_state (google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState): - Output only. The effective state of - enablement for the module at the given level of - the hierarchy. - display_name (str): - Output only. The display name for the custom - module. The name must be between 1 and 128 - characters, start with a lowercase letter, and - contain alphanumeric characters or underscores - only. - """ - class EnablementState(proto.Enum): - r"""The enablement state of the module. - - Values: - ENABLEMENT_STATE_UNSPECIFIED (0): - Unspecified enablement state. - ENABLED (1): - The module is enabled at the given level. - DISABLED (2): - The module is disabled at the given level. - """ - ENABLEMENT_STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - custom_config: security_health_analytics_custom_config.CustomConfig = proto.Field( - proto.MESSAGE, - number=2, - message=security_health_analytics_custom_config.CustomConfig, - ) - enablement_state: EnablementState = proto.Field( - proto.ENUM, - number=3, - enum=EnablementState, - ) - display_name: str = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.py deleted file mode 100644 index 6b6e83626bb9..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'EventThreatDetectionCustomModule', - }, -) - - -class EventThreatDetectionCustomModule(proto.Message): - r"""Represents an instance of an Event Threat Detection custom - module, including its full module name, display name, enablement - state, and last updated time. You can create a custom module at - the organization, folder, or project level. Custom modules that - you create at the organization or folder level are inherited by - child folders and projects. - - Attributes: - name (str): - Immutable. The resource name of the Event Threat Detection - custom module. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. - config (google.protobuf.struct_pb2.Struct): - Config for the module. For the resident - module, its config value is defined at this - level. For the inherited module, its config - value is inherited from the ancestor module. - ancestor_module (str): - Output only. The closest ancestor module that - this module inherits the enablement state from. - The format is the same as the - EventThreatDetectionCustomModule resource name. - enablement_state (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule.EnablementState): - The state of enablement for the module at the - given level of the hierarchy. - type_ (str): - Type for the module. e.g. CONFIGURABLE_BAD_IP. - display_name (str): - The human readable name to be displayed for - the module. - description (str): - The description for the module. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the module was last - updated. - last_editor (str): - Output only. The editor the module was last - updated by. - """ - class EnablementState(proto.Enum): - r"""The enablement state of the module. - - Values: - ENABLEMENT_STATE_UNSPECIFIED (0): - Unspecified enablement state. - ENABLED (1): - The module is enabled at the given level. - DISABLED (2): - The module is disabled at the given level. - INHERITED (3): - When the enablement state is inherited. - """ - ENABLEMENT_STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - INHERITED = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - config: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - ancestor_module: str = proto.Field( - proto.STRING, - number=3, - ) - enablement_state: EnablementState = proto.Field( - proto.ENUM, - number=4, - enum=EnablementState, - ) - type_: str = proto.Field( - proto.STRING, - number=5, - ) - display_name: str = proto.Field( - proto.STRING, - number=6, - ) - description: str = proto.Field( - proto.STRING, - number=7, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - last_editor: str = proto.Field( - proto.STRING, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.py deleted file mode 100644 index 12b7e815de3f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/event_threat_detection_custom_module_validation_errors.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'CustomModuleValidationErrors', - 'CustomModuleValidationError', - 'Position', - }, -) - - -class CustomModuleValidationErrors(proto.Message): - r"""A list of zero or more errors encountered while validating - the uploaded configuration of an Event Threat Detection Custom - Module. - - Attributes: - errors (MutableSequence[google.cloud.securitycenter_v1.types.CustomModuleValidationError]): - - """ - - errors: MutableSequence['CustomModuleValidationError'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='CustomModuleValidationError', - ) - - -class CustomModuleValidationError(proto.Message): - r"""An error encountered while validating the uploaded - configuration of an Event Threat Detection Custom Module. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - description (str): - A description of the error, suitable for - human consumption. Required. - field_path (str): - The path, in RFC 8901 JSON Pointer format, to - the field that failed validation. This may be - left empty if no specific field is affected. - start (google.cloud.securitycenter_v1.types.Position): - The initial position of the error in the - uploaded text version of the module. This field - may be omitted if no specific position applies, - or if one could not be computed. - - This field is a member of `oneof`_ ``_start``. - end (google.cloud.securitycenter_v1.types.Position): - The end position of the error in the uploaded - text version of the module. This field may be - omitted if no specific position applies, or if - one could not be computed.. - - This field is a member of `oneof`_ ``_end``. - """ - - description: str = proto.Field( - proto.STRING, - number=1, - ) - field_path: str = proto.Field( - proto.STRING, - number=2, - ) - start: 'Position' = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message='Position', - ) - end: 'Position' = proto.Field( - proto.MESSAGE, - number=4, - optional=True, - message='Position', - ) - - -class Position(proto.Message): - r"""A position in the uploaded text version of a module. - - Attributes: - line_number (int): - - column_number (int): - - """ - - line_number: int = proto.Field( - proto.INT32, - number=1, - ) - column_number: int = proto.Field( - proto.INT32, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.py deleted file mode 100644 index 68a2b9fd7d98..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/exfiltration.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Exfiltration', - 'ExfilResource', - }, -) - - -class Exfiltration(proto.Message): - r"""Exfiltration represents a data exfiltration attempt from one or more - sources to one or more targets. The ``sources`` attribute lists the - sources of the exfiltrated data. The ``targets`` attribute lists the - destinations the data was copied to. - - Attributes: - sources (MutableSequence[google.cloud.securitycenter_v1.types.ExfilResource]): - If there are multiple sources, then the data - is considered "joined" between them. For - instance, BigQuery can join multiple tables, and - each table would be considered a source. - targets (MutableSequence[google.cloud.securitycenter_v1.types.ExfilResource]): - If there are multiple targets, each target - would get a complete copy of the "joined" source - data. - total_exfiltrated_bytes (int): - Total exfiltrated bytes processed for the - entire job. - """ - - sources: MutableSequence['ExfilResource'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ExfilResource', - ) - targets: MutableSequence['ExfilResource'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ExfilResource', - ) - total_exfiltrated_bytes: int = proto.Field( - proto.INT64, - number=3, - ) - - -class ExfilResource(proto.Message): - r"""Resource where data was exfiltrated from or exfiltrated to. - - Attributes: - name (str): - The resource's `full resource - name `__. - components (MutableSequence[str]): - Subcomponents of the asset that was - exfiltrated, like URIs used during exfiltration, - table names, databases, and filenames. For - example, multiple tables might have been - exfiltrated from the same Cloud SQL instance, or - multiple files might have been exfiltrated from - the same Cloud Storage bucket. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - components: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py deleted file mode 100644 index 50a7a7e921f6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/external_system.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v1', - manifest={ - 'ExternalSystem', - }, -) - - -class ExternalSystem(proto.Message): - r"""Representation of third party SIEM/SOAR fields within SCC. - - Attributes: - name (str): - Full resource name of the external system, - for example: - "organizations/1234/sources/5678/findings/123456/externalSystems/jira", - "folders/1234/sources/5678/findings/123456/externalSystems/jira", - "projects/1234/sources/5678/findings/123456/externalSystems/jira". - assignees (MutableSequence[str]): - References primary/secondary etc assignees in - the external system. - external_uid (str): - The identifier that's used to track the - finding's corresponding case in the external - system. - status (str): - The most recent status of the finding's - corresponding case, as reported by the external - system. - external_system_update_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the case was last updated, as - reported by the external system. - case_uri (str): - The link to the finding's corresponding case - in the external system. - case_priority (str): - The priority of the finding's corresponding - case in the external system. - case_sla (google.protobuf.timestamp_pb2.Timestamp): - The SLA of the finding's corresponding case - in the external system. - case_create_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the case was created, as - reported by the external system. - case_close_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the case was closed, as - reported by the external system. - ticket_info (google.cloud.securitycenter_v1.types.ExternalSystem.TicketInfo): - Information about the ticket, if any, that is - being used to track the resolution of the issue - that is identified by this finding. - """ - - class TicketInfo(proto.Message): - r"""Information about the ticket, if any, that is being used to - track the resolution of the issue that is identified by this - finding. - - Attributes: - id (str): - The identifier of the ticket in the ticket - system. - assignee (str): - The assignee of the ticket in the ticket - system. - description (str): - The description of the ticket in the ticket - system. - uri (str): - The link to the ticket in the ticket system. - status (str): - The latest status of the ticket, as reported - by the ticket system. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the ticket was last updated, as - reported by the ticket system. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - assignee: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - uri: str = proto.Field( - proto.STRING, - number=4, - ) - status: str = proto.Field( - proto.STRING, - number=5, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - assignees: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - external_uid: str = proto.Field( - proto.STRING, - number=3, - ) - status: str = proto.Field( - proto.STRING, - number=4, - ) - external_system_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - case_uri: str = proto.Field( - proto.STRING, - number=6, - ) - case_priority: str = proto.Field( - proto.STRING, - number=7, - ) - case_sla: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - case_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - case_close_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - ticket_info: TicketInfo = proto.Field( - proto.MESSAGE, - number=8, - message=TicketInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.py deleted file mode 100644 index 017abee53151..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/file.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'File', - }, -) - - -class File(proto.Message): - r"""File information about the related binary/library used by an - executable, or the script used by a script interpreter - - Attributes: - path (str): - Absolute path of the file as a JSON encoded - string. - size (int): - Size of the file in bytes. - sha256 (str): - SHA256 hash of the first hashed_size bytes of the file - encoded as a hex string. If hashed_size == size, sha256 - represents the SHA256 hash of the entire file. - hashed_size (int): - The length in bytes of the file prefix that was hashed. If - hashed_size == size, any hashes reported represent the - entire file. - partially_hashed (bool): - True when the hash covers only a prefix of - the file. - contents (str): - Prefix of the file contents as a JSON-encoded - string. - disk_path (google.cloud.securitycenter_v1.types.File.DiskPath): - Path of the file in terms of underlying - disk/partition identifiers. - """ - - class DiskPath(proto.Message): - r"""Path of the file in terms of underlying disk/partition - identifiers. - - Attributes: - partition_uuid (str): - UUID of the partition (format - https://wiki.archlinux.org/title/persistent_block_device_naming#by-uuid) - relative_path (str): - Relative path of the file in the partition as a JSON encoded - string. Example: /home/user1/executable_file.sh - """ - - partition_uuid: str = proto.Field( - proto.STRING, - number=1, - ) - relative_path: str = proto.Field( - proto.STRING, - number=2, - ) - - path: str = proto.Field( - proto.STRING, - number=1, - ) - size: int = proto.Field( - proto.INT64, - number=2, - ) - sha256: str = proto.Field( - proto.STRING, - number=3, - ) - hashed_size: int = proto.Field( - proto.INT64, - number=4, - ) - partially_hashed: bool = proto.Field( - proto.BOOL, - number=5, - ) - contents: str = proto.Field( - proto.STRING, - number=6, - ) - disk_path: DiskPath = proto.Field( - proto.MESSAGE, - number=7, - message=DiskPath, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py deleted file mode 100644 index cc8deabeef4b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/finding.py +++ /dev/null @@ -1,774 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1.types import access as gcs_access -from google.cloud.securitycenter_v1.types import application as gcs_application -from google.cloud.securitycenter_v1.types import attack_exposure as gcs_attack_exposure -from google.cloud.securitycenter_v1.types import backup_disaster_recovery as gcs_backup_disaster_recovery -from google.cloud.securitycenter_v1.types import cloud_armor as gcs_cloud_armor -from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile as gcs_cloud_dlp_data_profile -from google.cloud.securitycenter_v1.types import cloud_dlp_inspection as gcs_cloud_dlp_inspection -from google.cloud.securitycenter_v1.types import compliance -from google.cloud.securitycenter_v1.types import connection -from google.cloud.securitycenter_v1.types import contact_details -from google.cloud.securitycenter_v1.types import container -from google.cloud.securitycenter_v1.types import database as gcs_database -from google.cloud.securitycenter_v1.types import exfiltration as gcs_exfiltration -from google.cloud.securitycenter_v1.types import external_system -from google.cloud.securitycenter_v1.types import file -from google.cloud.securitycenter_v1.types import group_membership -from google.cloud.securitycenter_v1.types import iam_binding -from google.cloud.securitycenter_v1.types import indicator as gcs_indicator -from google.cloud.securitycenter_v1.types import kernel_rootkit as gcs_kernel_rootkit -from google.cloud.securitycenter_v1.types import kubernetes as gcs_kubernetes -from google.cloud.securitycenter_v1.types import load_balancer -from google.cloud.securitycenter_v1.types import log_entry -from google.cloud.securitycenter_v1.types import mitre_attack as gcs_mitre_attack -from google.cloud.securitycenter_v1.types import notebook as gcs_notebook -from google.cloud.securitycenter_v1.types import org_policy -from google.cloud.securitycenter_v1.types import process -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import security_posture as gcs_security_posture -from google.cloud.securitycenter_v1.types import toxic_combination as gcs_toxic_combination -from google.cloud.securitycenter_v1.types import vulnerability as gcs_vulnerability -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - - A finding is a record of assessment data like security, risk, - health, or privacy, that is ingested into Security Command - Center for presentation, notification, analysis, policy testing, - and enforcement. For example, a cross-site scripting (XSS) - vulnerability in an App Engine application is a finding. - - Attributes: - name (str): - The `relative resource - name `__ - of the finding. Example: - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}", - "projects/{project_id}/sources/{source_id}/findings/{finding_id}". - parent (str): - The relative resource name of the source the finding belongs - to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. For example: - "organizations/{organization_id}/sources/{source_id}". - resource_name (str): - For findings on Google Cloud resources, the full resource - name of the Google Cloud resource this finding is for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - This field is immutable after creation time. - state (google.cloud.securitycenter_v1.types.Finding.State): - The state of the finding. - category (str): - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. - Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (google.protobuf.timestamp_pb2.Timestamp): - The time the finding was first detected. If - an existing finding is updated, then this is the - time the update occurred. For example, if the - finding represents an open firewall, this - property captures the time the detector believes - the firewall became open. The accuracy is - determined by the detector. If the finding is - later resolved, then this time reflects when the - finding was resolved. This must not be set to a - value greater than the current timestamp. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the finding was created in - Security Command Center. - severity (google.cloud.securitycenter_v1.types.Finding.Severity): - The severity of the finding. This field is - managed by the source that writes the finding. - canonical_name (str): - The canonical name of the finding. It's either - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" - or - "projects/{project_number}/sources/{source_id}/findings/{finding_id}", - depending on the closest CRM ancestor of the resource - associated with the finding. - mute (google.cloud.securitycenter_v1.types.Finding.Mute): - Indicates the mute state of a finding (either - muted, unmuted or undefined). Unlike other - attributes of a finding, a finding provider - shouldn't set the value of mute. - finding_class (google.cloud.securitycenter_v1.types.Finding.FindingClass): - The class of the finding. - indicator (google.cloud.securitycenter_v1.types.Indicator): - Represents what's commonly known as an *indicator of - compromise* (IoC) in computer forensics. This is an artifact - observed on a network or in an operating system that, with - high confidence, indicates a computer intrusion. For more - information, see `Indicator of - compromise `__. - vulnerability (google.cloud.securitycenter_v1.types.Vulnerability): - Represents vulnerability-specific fields like - CVE and CVSS scores. CVE stands for Common - Vulnerabilities and Exposures - (https://cve.mitre.org/about/) - mute_update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The most recent time this - finding was muted or unmuted. - external_systems (MutableMapping[str, google.cloud.securitycenter_v1.types.ExternalSystem]): - Output only. Third party SIEM/SOAR fields - within SCC, contains external system information - and external system finding fields. - mitre_attack (google.cloud.securitycenter_v1.types.MitreAttack): - MITRE ATT&CK tactics and techniques related - to this finding. See: https://attack.mitre.org - access (google.cloud.securitycenter_v1.types.Access): - Access details associated with the finding, - such as more information on the caller, which - method was accessed, and from where. - connections (MutableSequence[google.cloud.securitycenter_v1.types.Connection]): - Contains information about the IP connection - associated with the finding. - mute_initiator (str): - Records additional information about the mute operation, for - example, the `mute - configuration `__ - that muted the finding and the user who muted the finding. - mute_info (google.cloud.securitycenter_v1.types.Finding.MuteInfo): - Output only. The mute information regarding - this finding. - processes (MutableSequence[google.cloud.securitycenter_v1.types.Process]): - Represents operating system processes - associated with the Finding. - contacts (MutableMapping[str, google.cloud.securitycenter_v1.types.ContactDetails]): - Output only. Map containing the points of contact for the - given finding. The key represents the type of contact, while - the value contains a list of all the contacts that pertain. - Please refer to: - https://cloud.google.com/resource-manager/docs/managing-notification-contacts#notification-categories - - :: - - { - "security": { - "contacts": [ - { - "email": "person1@company.com" - }, - { - "email": "person2@company.com" - } - ] - } - } - compliances (MutableSequence[google.cloud.securitycenter_v1.types.Compliance]): - Contains compliance information for security - standards associated to the finding. - parent_display_name (str): - Output only. The human readable display name - of the finding source such as "Event Threat - Detection" or "Security Health Analytics". - description (str): - Contains more details about the finding. - exfiltration (google.cloud.securitycenter_v1.types.Exfiltration): - Represents exfiltrations associated with the - finding. - iam_bindings (MutableSequence[google.cloud.securitycenter_v1.types.IamBinding]): - Represents IAM bindings associated with the - finding. - next_steps (str): - Steps to address the finding. - module_name (str): - Unique identifier of the module which - generated the finding. Example: - - folders/598186756061/securityHealthAnalyticsSettings/customModules/56799441161885 - containers (MutableSequence[google.cloud.securitycenter_v1.types.Container]): - Containers associated with the finding. This - field provides information for both Kubernetes - and non-Kubernetes containers. - kubernetes (google.cloud.securitycenter_v1.types.Kubernetes): - Kubernetes resources associated with the - finding. - database (google.cloud.securitycenter_v1.types.Database): - Database associated with the finding. - attack_exposure (google.cloud.securitycenter_v1.types.AttackExposure): - The results of an attack path simulation - relevant to this finding. - files (MutableSequence[google.cloud.securitycenter_v1.types.File]): - File associated with the finding. - cloud_dlp_inspection (google.cloud.securitycenter_v1.types.CloudDlpInspection): - Cloud Data Loss Prevention (Cloud DLP) - inspection results that are associated with the - finding. - cloud_dlp_data_profile (google.cloud.securitycenter_v1.types.CloudDlpDataProfile): - Cloud DLP data profile that is associated - with the finding. - kernel_rootkit (google.cloud.securitycenter_v1.types.KernelRootkit): - Signature of the kernel rootkit. - org_policies (MutableSequence[google.cloud.securitycenter_v1.types.OrgPolicy]): - Contains information about the org policies - associated with the finding. - application (google.cloud.securitycenter_v1.types.Application): - Represents an application associated with the - finding. - backup_disaster_recovery (google.cloud.securitycenter_v1.types.BackupDisasterRecovery): - Fields related to Backup and DR findings. - security_posture (google.cloud.securitycenter_v1.types.SecurityPosture): - The security posture associated with the - finding. - log_entries (MutableSequence[google.cloud.securitycenter_v1.types.LogEntry]): - Log entries that are relevant to the finding. - load_balancers (MutableSequence[google.cloud.securitycenter_v1.types.LoadBalancer]): - The load balancers associated with the - finding. - cloud_armor (google.cloud.securitycenter_v1.types.CloudArmor): - Fields related to Cloud Armor findings. - notebook (google.cloud.securitycenter_v1.types.Notebook): - Notebook associated with the finding. - toxic_combination (google.cloud.securitycenter_v1.types.ToxicCombination): - Contains details about a group of security - issues that, when the issues occur together, - represent a greater risk than when the issues - occur independently. A group of such issues is - referred to as a toxic combination. - This field cannot be updated. Its value is - ignored in all update requests. - group_memberships (MutableSequence[google.cloud.securitycenter_v1.types.GroupMembership]): - Contains details about groups of which this - finding is a member. A group is a collection of - findings that are related in some way. This - field cannot be updated. Its value is ignored in - all update requests. - """ - class State(proto.Enum): - r"""The state of the finding. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - ACTIVE (1): - The finding requires attention and has not - been addressed yet. - INACTIVE (2): - The finding has been fixed, triaged as a - non-issue or otherwise addressed and is no - longer active. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - class Severity(proto.Enum): - r"""The severity of the finding. - - Values: - SEVERITY_UNSPECIFIED (0): - This value is used for findings when a source - doesn't write a severity value. - CRITICAL (1): - Vulnerability: - - A critical vulnerability is easily discoverable - by an external actor, exploitable, and results - in the direct ability to execute arbitrary code, - exfiltrate data, and otherwise gain additional - access and privileges to cloud resources and - workloads. Examples include publicly accessible - unprotected user data and public SSH access with - weak or no passwords. - - Threat: - - Indicates a threat that is able to access, - modify, or delete data or execute unauthorized - code within existing resources. - HIGH (2): - Vulnerability: - - A high risk vulnerability can be easily - discovered and exploited in combination with - other vulnerabilities in order to gain direct - access and the ability to execute arbitrary - code, exfiltrate data, and otherwise gain - additional access and privileges to cloud - resources and workloads. An example is a - database with weak or no passwords that is only - accessible internally. This database could - easily be compromised by an actor that had - access to the internal network. - - Threat: - - Indicates a threat that is able to create new - computational resources in an environment but - not able to access data or execute code in - existing resources. - MEDIUM (3): - Vulnerability: - - A medium risk vulnerability could be used by an - actor to gain access to resources or privileges - that enable them to eventually (through multiple - steps or a complex exploit) gain access and the - ability to execute arbitrary code or exfiltrate - data. An example is a service account with - access to more projects than it should have. If - an actor gains access to the service account, - they could potentially use that access to - manipulate a project the service account was not - intended to. - - Threat: - - Indicates a threat that is able to cause - operational impact but may not access data or - execute unauthorized code. - LOW (4): - Vulnerability: - - A low risk vulnerability hampers a security - organization's ability to detect vulnerabilities - or active threats in their deployment, or - prevents the root cause investigation of - security issues. An example is monitoring and - logs being disabled for resource configurations - and access. - - Threat: - - Indicates a threat that has obtained minimal - access to an environment but is not able to - access data, execute code, or create resources. - """ - SEVERITY_UNSPECIFIED = 0 - CRITICAL = 1 - HIGH = 2 - MEDIUM = 3 - LOW = 4 - - class Mute(proto.Enum): - r"""Mute state a finding can be in. - - Values: - MUTE_UNSPECIFIED (0): - Unspecified. - MUTED (1): - Finding has been muted. - UNMUTED (2): - Finding has been unmuted. - UNDEFINED (4): - Finding has never been muted/unmuted. - """ - MUTE_UNSPECIFIED = 0 - MUTED = 1 - UNMUTED = 2 - UNDEFINED = 4 - - class FindingClass(proto.Enum): - r"""Represents what kind of Finding it is. - - Values: - FINDING_CLASS_UNSPECIFIED (0): - Unspecified finding class. - THREAT (1): - Describes unwanted or malicious activity. - VULNERABILITY (2): - Describes a potential weakness in software - that increases risk to Confidentiality & - Integrity & Availability. - MISCONFIGURATION (3): - Describes a potential weakness in cloud - resource/asset configuration that increases - risk. - OBSERVATION (4): - Describes a security observation that is for - informational purposes. - SCC_ERROR (5): - Describes an error that prevents some SCC - functionality. - POSTURE_VIOLATION (6): - Describes a potential security risk due to a - change in the security posture. - TOXIC_COMBINATION (7): - Describes a group of security issues that, - when the issues occur together, represent a - greater risk than when the issues occur - independently. A group of such issues is - referred to as a toxic combination. - """ - FINDING_CLASS_UNSPECIFIED = 0 - THREAT = 1 - VULNERABILITY = 2 - MISCONFIGURATION = 3 - OBSERVATION = 4 - SCC_ERROR = 5 - POSTURE_VIOLATION = 6 - TOXIC_COMBINATION = 7 - - class MuteInfo(proto.Message): - r"""Mute information about the finding, including whether the - finding has a static mute or any matching dynamic mute rules. - - Attributes: - static_mute (google.cloud.securitycenter_v1.types.Finding.MuteInfo.StaticMute): - If set, the static mute applied to this - finding. Static mutes override dynamic mutes. If - unset, there is no static mute. - dynamic_mute_records (MutableSequence[google.cloud.securitycenter_v1.types.Finding.MuteInfo.DynamicMuteRecord]): - The list of dynamic mute rules that currently - match the finding. - """ - - class StaticMute(proto.Message): - r"""Information about the static mute state. A static mute state - overrides any dynamic mute rules that apply to this finding. The - static mute state can be set by a static mute rule or by muting - the finding directly. - - Attributes: - state (google.cloud.securitycenter_v1.types.Finding.Mute): - The static mute state. If the value is ``MUTED`` or - ``UNMUTED``, then the finding's overall mute state will have - the same value. - apply_time (google.protobuf.timestamp_pb2.Timestamp): - When the static mute was applied. - """ - - state: 'Finding.Mute' = proto.Field( - proto.ENUM, - number=1, - enum='Finding.Mute', - ) - apply_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - class DynamicMuteRecord(proto.Message): - r"""The record of a dynamic mute rule that matches the finding. - - Attributes: - mute_config (str): - The relative resource name of the mute rule, represented by - a mute config, that created this record, for example - ``organizations/123/muteConfigs/mymuteconfig`` or - ``organizations/123/locations/global/muteConfigs/mymuteconfig``. - match_time (google.protobuf.timestamp_pb2.Timestamp): - When the dynamic mute rule first matched the - finding. - """ - - mute_config: str = proto.Field( - proto.STRING, - number=1, - ) - match_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - static_mute: 'Finding.MuteInfo.StaticMute' = proto.Field( - proto.MESSAGE, - number=1, - message='Finding.MuteInfo.StaticMute', - ) - dynamic_mute_records: MutableSequence['Finding.MuteInfo.DynamicMuteRecord'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Finding.MuteInfo.DynamicMuteRecord', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - resource_name: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - category: str = proto.Field( - proto.STRING, - number=5, - ) - external_uri: str = proto.Field( - proto.STRING, - number=6, - ) - source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - severity: Severity = proto.Field( - proto.ENUM, - number=12, - enum=Severity, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=14, - ) - mute: Mute = proto.Field( - proto.ENUM, - number=15, - enum=Mute, - ) - finding_class: FindingClass = proto.Field( - proto.ENUM, - number=17, - enum=FindingClass, - ) - indicator: gcs_indicator.Indicator = proto.Field( - proto.MESSAGE, - number=18, - message=gcs_indicator.Indicator, - ) - vulnerability: gcs_vulnerability.Vulnerability = proto.Field( - proto.MESSAGE, - number=20, - message=gcs_vulnerability.Vulnerability, - ) - mute_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=21, - message=timestamp_pb2.Timestamp, - ) - external_systems: MutableMapping[str, external_system.ExternalSystem] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=22, - message=external_system.ExternalSystem, - ) - mitre_attack: gcs_mitre_attack.MitreAttack = proto.Field( - proto.MESSAGE, - number=25, - message=gcs_mitre_attack.MitreAttack, - ) - access: gcs_access.Access = proto.Field( - proto.MESSAGE, - number=26, - message=gcs_access.Access, - ) - connections: MutableSequence[connection.Connection] = proto.RepeatedField( - proto.MESSAGE, - number=31, - message=connection.Connection, - ) - mute_initiator: str = proto.Field( - proto.STRING, - number=28, - ) - mute_info: MuteInfo = proto.Field( - proto.MESSAGE, - number=61, - message=MuteInfo, - ) - processes: MutableSequence[process.Process] = proto.RepeatedField( - proto.MESSAGE, - number=30, - message=process.Process, - ) - contacts: MutableMapping[str, contact_details.ContactDetails] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=33, - message=contact_details.ContactDetails, - ) - compliances: MutableSequence[compliance.Compliance] = proto.RepeatedField( - proto.MESSAGE, - number=34, - message=compliance.Compliance, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=36, - ) - description: str = proto.Field( - proto.STRING, - number=37, - ) - exfiltration: gcs_exfiltration.Exfiltration = proto.Field( - proto.MESSAGE, - number=38, - message=gcs_exfiltration.Exfiltration, - ) - iam_bindings: MutableSequence[iam_binding.IamBinding] = proto.RepeatedField( - proto.MESSAGE, - number=39, - message=iam_binding.IamBinding, - ) - next_steps: str = proto.Field( - proto.STRING, - number=40, - ) - module_name: str = proto.Field( - proto.STRING, - number=41, - ) - containers: MutableSequence[container.Container] = proto.RepeatedField( - proto.MESSAGE, - number=42, - message=container.Container, - ) - kubernetes: gcs_kubernetes.Kubernetes = proto.Field( - proto.MESSAGE, - number=43, - message=gcs_kubernetes.Kubernetes, - ) - database: gcs_database.Database = proto.Field( - proto.MESSAGE, - number=44, - message=gcs_database.Database, - ) - attack_exposure: gcs_attack_exposure.AttackExposure = proto.Field( - proto.MESSAGE, - number=45, - message=gcs_attack_exposure.AttackExposure, - ) - files: MutableSequence[file.File] = proto.RepeatedField( - proto.MESSAGE, - number=46, - message=file.File, - ) - cloud_dlp_inspection: gcs_cloud_dlp_inspection.CloudDlpInspection = proto.Field( - proto.MESSAGE, - number=48, - message=gcs_cloud_dlp_inspection.CloudDlpInspection, - ) - cloud_dlp_data_profile: gcs_cloud_dlp_data_profile.CloudDlpDataProfile = proto.Field( - proto.MESSAGE, - number=49, - message=gcs_cloud_dlp_data_profile.CloudDlpDataProfile, - ) - kernel_rootkit: gcs_kernel_rootkit.KernelRootkit = proto.Field( - proto.MESSAGE, - number=50, - message=gcs_kernel_rootkit.KernelRootkit, - ) - org_policies: MutableSequence[org_policy.OrgPolicy] = proto.RepeatedField( - proto.MESSAGE, - number=51, - message=org_policy.OrgPolicy, - ) - application: gcs_application.Application = proto.Field( - proto.MESSAGE, - number=53, - message=gcs_application.Application, - ) - backup_disaster_recovery: gcs_backup_disaster_recovery.BackupDisasterRecovery = proto.Field( - proto.MESSAGE, - number=55, - message=gcs_backup_disaster_recovery.BackupDisasterRecovery, - ) - security_posture: gcs_security_posture.SecurityPosture = proto.Field( - proto.MESSAGE, - number=56, - message=gcs_security_posture.SecurityPosture, - ) - log_entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( - proto.MESSAGE, - number=57, - message=log_entry.LogEntry, - ) - load_balancers: MutableSequence[load_balancer.LoadBalancer] = proto.RepeatedField( - proto.MESSAGE, - number=58, - message=load_balancer.LoadBalancer, - ) - cloud_armor: gcs_cloud_armor.CloudArmor = proto.Field( - proto.MESSAGE, - number=59, - message=gcs_cloud_armor.CloudArmor, - ) - notebook: gcs_notebook.Notebook = proto.Field( - proto.MESSAGE, - number=63, - message=gcs_notebook.Notebook, - ) - toxic_combination: gcs_toxic_combination.ToxicCombination = proto.Field( - proto.MESSAGE, - number=64, - message=gcs_toxic_combination.ToxicCombination, - ) - group_memberships: MutableSequence[group_membership.GroupMembership] = proto.RepeatedField( - proto.MESSAGE, - number=65, - message=group_membership.GroupMembership, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.py deleted file mode 100644 index 577452411641..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/folder.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.securitycenter.v1', - manifest={ - 'Folder', - }, -) - - -class Folder(proto.Message): - r"""Message that contains the resource name and display name of a - folder resource. - - Attributes: - resource_folder (str): - Full resource name of this folder. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_folder_display_name (str): - The user defined display name for this - folder. - """ - - resource_folder: str = proto.Field( - proto.STRING, - number=1, - ) - resource_folder_display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.py deleted file mode 100644 index d95cb97ea0a4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/group_membership.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.cloud.securitycenter.v1', - manifest={ - 'GroupMembership', - }, -) - - -class GroupMembership(proto.Message): - r"""Contains details about groups of which this finding is a - member. A group is a collection of findings that are related in - some way. - - Attributes: - group_type (google.cloud.securitycenter_v1.types.GroupMembership.GroupType): - Type of group. - group_id (str): - ID of the group. - """ - class GroupType(proto.Enum): - r"""Possible types of groups. - - Values: - GROUP_TYPE_UNSPECIFIED (0): - Default value. - GROUP_TYPE_TOXIC_COMBINATION (1): - Group represents a toxic combination. - """ - GROUP_TYPE_UNSPECIFIED = 0 - GROUP_TYPE_TOXIC_COMBINATION = 1 - - group_type: GroupType = proto.Field( - proto.ENUM, - number=1, - enum=GroupType, - ) - group_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py deleted file mode 100644 index cab59d31ec7c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/iam_binding.py +++ /dev/null @@ -1,77 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v1', - manifest={ - 'IamBinding', - }, -) - - -class IamBinding(proto.Message): - r"""Represents a particular IAM binding, which captures a - member's role addition, removal, or state. - - Attributes: - action (google.cloud.securitycenter_v1.types.IamBinding.Action): - The action that was performed on a Binding. - role (str): - Role that is assigned to "members". - For example, "roles/viewer", "roles/editor", or - "roles/owner". - member (str): - A single identity requesting access for a - Cloud Platform resource, for example, - "foo@google.com". - """ - class Action(proto.Enum): - r"""The type of action performed on a Binding in a policy. - - Values: - ACTION_UNSPECIFIED (0): - Unspecified. - ADD (1): - Addition of a Binding. - REMOVE (2): - Removal of a Binding. - """ - ACTION_UNSPECIFIED = 0 - ADD = 1 - REMOVE = 2 - - action: Action = proto.Field( - proto.ENUM, - number=1, - enum=Action, - ) - role: str = proto.Field( - proto.STRING, - number=2, - ) - member: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py deleted file mode 100644 index f75bd00701dd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/indicator.py +++ /dev/null @@ -1,186 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v1', - manifest={ - 'Indicator', - }, -) - - -class Indicator(proto.Message): - r"""Represents what's commonly known as an *indicator of compromise* - (IoC) in computer forensics. This is an artifact observed on a - network or in an operating system that, with high confidence, - indicates a computer intrusion. For more information, see `Indicator - of - compromise `__. - - Attributes: - ip_addresses (MutableSequence[str]): - The list of IP addresses that are associated - with the finding. - domains (MutableSequence[str]): - List of domains associated to the Finding. - signatures (MutableSequence[google.cloud.securitycenter_v1.types.Indicator.ProcessSignature]): - The list of matched signatures indicating - that the given process is present in the - environment. - uris (MutableSequence[str]): - The list of URIs associated to the Findings. - """ - - class ProcessSignature(proto.Message): - r"""Indicates what signature matched this process. - - 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: - memory_hash_signature (google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.MemoryHashSignature): - Signature indicating that a binary family was - matched. - - This field is a member of `oneof`_ ``signature``. - yara_rule_signature (google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.YaraRuleSignature): - Signature indicating that a YARA rule was - matched. - - This field is a member of `oneof`_ ``signature``. - signature_type (google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.SignatureType): - Describes the type of resource associated - with the signature. - """ - class SignatureType(proto.Enum): - r"""Possible resource types to be associated with a signature. - - Values: - SIGNATURE_TYPE_UNSPECIFIED (0): - The default signature type. - SIGNATURE_TYPE_PROCESS (1): - Used for signatures concerning processes. - SIGNATURE_TYPE_FILE (2): - Used for signatures concerning disks. - """ - SIGNATURE_TYPE_UNSPECIFIED = 0 - SIGNATURE_TYPE_PROCESS = 1 - SIGNATURE_TYPE_FILE = 2 - - class MemoryHashSignature(proto.Message): - r"""A signature corresponding to memory page hashes. - - Attributes: - binary_family (str): - The binary family. - detections (MutableSequence[google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.MemoryHashSignature.Detection]): - The list of memory hash detections - contributing to the binary family match. - """ - - class Detection(proto.Message): - r"""Memory hash detection contributing to the binary family - match. - - Attributes: - binary (str): - The name of the binary associated with the - memory hash signature detection. - percent_pages_matched (float): - The percentage of memory page hashes in the - signature that were matched. - """ - - binary: str = proto.Field( - proto.STRING, - number=2, - ) - percent_pages_matched: float = proto.Field( - proto.DOUBLE, - number=3, - ) - - binary_family: str = proto.Field( - proto.STRING, - number=1, - ) - detections: MutableSequence['Indicator.ProcessSignature.MemoryHashSignature.Detection'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Indicator.ProcessSignature.MemoryHashSignature.Detection', - ) - - class YaraRuleSignature(proto.Message): - r"""A signature corresponding to a YARA rule. - - Attributes: - yara_rule (str): - The name of the YARA rule. - """ - - yara_rule: str = proto.Field( - proto.STRING, - number=5, - ) - - memory_hash_signature: 'Indicator.ProcessSignature.MemoryHashSignature' = proto.Field( - proto.MESSAGE, - number=6, - oneof='signature', - message='Indicator.ProcessSignature.MemoryHashSignature', - ) - yara_rule_signature: 'Indicator.ProcessSignature.YaraRuleSignature' = proto.Field( - proto.MESSAGE, - number=7, - oneof='signature', - message='Indicator.ProcessSignature.YaraRuleSignature', - ) - signature_type: 'Indicator.ProcessSignature.SignatureType' = proto.Field( - proto.ENUM, - number=8, - enum='Indicator.ProcessSignature.SignatureType', - ) - - ip_addresses: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - domains: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - signatures: MutableSequence[ProcessSignature] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=ProcessSignature, - ) - uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.py deleted file mode 100644 index d9c18edeec46..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kernel_rootkit.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'KernelRootkit', - }, -) - - -class KernelRootkit(proto.Message): - r"""Kernel mode rootkit signatures. - - Attributes: - name (str): - Rootkit name, when available. - unexpected_code_modification (bool): - True if unexpected modifications of kernel - code memory are present. - unexpected_read_only_data_modification (bool): - True if unexpected modifications of kernel - read-only data memory are present. - unexpected_ftrace_handler (bool): - True if ``ftrace`` points are present with callbacks - pointing to regions that are not in the expected kernel or - module code range. - unexpected_kprobe_handler (bool): - True if ``kprobe`` points are present with callbacks - pointing to regions that are not in the expected kernel or - module code range. - unexpected_kernel_code_pages (bool): - True if kernel code pages that are not in the - expected kernel or module code regions are - present. - unexpected_system_call_handler (bool): - True if system call handlers that are are not - in the expected kernel or module code regions - are present. - unexpected_interrupt_handler (bool): - True if interrupt handlers that are are not - in the expected kernel or module code regions - are present. - unexpected_processes_in_runqueue (bool): - True if unexpected processes in the scheduler - run queue are present. Such processes are in the - run queue, but not in the process task list. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - unexpected_code_modification: bool = proto.Field( - proto.BOOL, - number=2, - ) - unexpected_read_only_data_modification: bool = proto.Field( - proto.BOOL, - number=3, - ) - unexpected_ftrace_handler: bool = proto.Field( - proto.BOOL, - number=4, - ) - unexpected_kprobe_handler: bool = proto.Field( - proto.BOOL, - number=5, - ) - unexpected_kernel_code_pages: bool = proto.Field( - proto.BOOL, - number=6, - ) - unexpected_system_call_handler: bool = proto.Field( - proto.BOOL, - number=7, - ) - unexpected_interrupt_handler: bool = proto.Field( - proto.BOOL, - number=8, - ) - unexpected_processes_in_runqueue: bool = proto.Field( - proto.BOOL, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.py deleted file mode 100644 index b91973ac449b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/kubernetes.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v1.types import container -from google.cloud.securitycenter_v1.types import label - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Kubernetes', - }, -) - - -class Kubernetes(proto.Message): - r"""Kubernetes-related attributes. - - Attributes: - pods (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Pod]): - Kubernetes - `Pods `__ - associated with the finding. This field contains Pod records - for each container that is owned by a Pod. - nodes (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Node]): - Provides Kubernetes - `node `__ - information. - node_pools (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.NodePool]): - GKE `node - pools `__ - associated with the finding. This field contains node pool - information for each node, when it is available. - roles (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Role]): - Provides Kubernetes role information for findings that - involve `Roles or - ClusterRoles `__. - bindings (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Binding]): - Provides Kubernetes role binding information for findings - that involve `RoleBindings or - ClusterRoleBindings `__. - access_reviews (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.AccessReview]): - Provides information on any Kubernetes access - reviews (privilege checks) relevant to the - finding. - objects (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Object]): - Kubernetes objects related to the finding. - """ - - class Pod(proto.Message): - r"""A Kubernetes Pod. - - Attributes: - ns (str): - Kubernetes Pod namespace. - name (str): - Kubernetes Pod name. - labels (MutableSequence[google.cloud.securitycenter_v1.types.Label]): - Pod labels. For Kubernetes containers, these - are applied to the container. - containers (MutableSequence[google.cloud.securitycenter_v1.types.Container]): - Pod containers associated with this finding, - if any. - """ - - ns: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - labels: MutableSequence[label.Label] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=label.Label, - ) - containers: MutableSequence[container.Container] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=container.Container, - ) - - class Node(proto.Message): - r"""Kubernetes nodes associated with the finding. - - Attributes: - name (str): - `Full resource - name `__ of - the Compute Engine VM running the cluster node. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - class NodePool(proto.Message): - r"""Provides GKE node pool information. - - Attributes: - name (str): - Kubernetes node pool name. - nodes (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Node]): - Nodes associated with the finding. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - nodes: MutableSequence['Kubernetes.Node'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Kubernetes.Node', - ) - - class Role(proto.Message): - r"""Kubernetes Role or ClusterRole. - - Attributes: - kind (google.cloud.securitycenter_v1.types.Kubernetes.Role.Kind): - Role type. - ns (str): - Role namespace. - name (str): - Role name. - """ - class Kind(proto.Enum): - r"""Types of Kubernetes roles. - - Values: - KIND_UNSPECIFIED (0): - Role type is not specified. - ROLE (1): - Kubernetes Role. - CLUSTER_ROLE (2): - Kubernetes ClusterRole. - """ - KIND_UNSPECIFIED = 0 - ROLE = 1 - CLUSTER_ROLE = 2 - - kind: 'Kubernetes.Role.Kind' = proto.Field( - proto.ENUM, - number=1, - enum='Kubernetes.Role.Kind', - ) - ns: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - class Binding(proto.Message): - r"""Represents a Kubernetes RoleBinding or ClusterRoleBinding. - - Attributes: - ns (str): - Namespace for the binding. - name (str): - Name for the binding. - role (google.cloud.securitycenter_v1.types.Kubernetes.Role): - The Role or ClusterRole referenced by the - binding. - subjects (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Subject]): - Represents one or more subjects that are - bound to the role. Not always available for - PATCH requests. - """ - - ns: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - role: 'Kubernetes.Role' = proto.Field( - proto.MESSAGE, - number=3, - message='Kubernetes.Role', - ) - subjects: MutableSequence['Kubernetes.Subject'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Kubernetes.Subject', - ) - - class Subject(proto.Message): - r"""Represents a Kubernetes subject. - - Attributes: - kind (google.cloud.securitycenter_v1.types.Kubernetes.Subject.AuthType): - Authentication type for the subject. - ns (str): - Namespace for the subject. - name (str): - Name for the subject. - """ - class AuthType(proto.Enum): - r"""Auth types that can be used for the subject's kind field. - - Values: - AUTH_TYPE_UNSPECIFIED (0): - Authentication is not specified. - USER (1): - User with valid certificate. - SERVICEACCOUNT (2): - Users managed by Kubernetes API with - credentials stored as secrets. - GROUP (3): - Collection of users. - """ - AUTH_TYPE_UNSPECIFIED = 0 - USER = 1 - SERVICEACCOUNT = 2 - GROUP = 3 - - kind: 'Kubernetes.Subject.AuthType' = proto.Field( - proto.ENUM, - number=1, - enum='Kubernetes.Subject.AuthType', - ) - ns: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - class AccessReview(proto.Message): - r"""Conveys information about a Kubernetes access review (such as one - returned by a - ```kubectl auth can-i`` `__ - command) that was involved in a finding. - - Attributes: - group (str): - The API group of the resource. "*" means all. - ns (str): - Namespace of the action being requested. - Currently, there is no distinction between no - namespace and all namespaces. Both are - represented by "" (empty). - name (str): - The name of the resource being requested. - Empty means all. - resource (str): - The optional resource type requested. "*" means all. - subresource (str): - The optional subresource type. - verb (str): - A Kubernetes resource API verb, like get, list, watch, - create, update, delete, proxy. "*" means all. - version (str): - The API version of the resource. "*" means all. - """ - - group: str = proto.Field( - proto.STRING, - number=1, - ) - ns: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - resource: str = proto.Field( - proto.STRING, - number=4, - ) - subresource: str = proto.Field( - proto.STRING, - number=5, - ) - verb: str = proto.Field( - proto.STRING, - number=6, - ) - version: str = proto.Field( - proto.STRING, - number=7, - ) - - class Object(proto.Message): - r"""Kubernetes object related to the finding, uniquely identified - by GKNN. Used if the object Kind is not one of Pod, Node, - NodePool, Binding, or AccessReview. - - Attributes: - group (str): - Kubernetes object group, such as - "policy.k8s.io/v1". - kind (str): - Kubernetes object kind, such as "Namespace". - ns (str): - Kubernetes object namespace. Must be a valid - DNS label. Named "ns" to avoid collision with - C++ namespace keyword. For details see - https://kubernetes.io/docs/tasks/administer-cluster/namespaces/. - name (str): - Kubernetes object name. For details see - https://kubernetes.io/docs/concepts/overview/working-with-objects/names/. - containers (MutableSequence[google.cloud.securitycenter_v1.types.Container]): - Pod containers associated with this finding, - if any. - """ - - group: str = proto.Field( - proto.STRING, - number=1, - ) - kind: str = proto.Field( - proto.STRING, - number=2, - ) - ns: str = proto.Field( - proto.STRING, - number=3, - ) - name: str = proto.Field( - proto.STRING, - number=4, - ) - containers: MutableSequence[container.Container] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=container.Container, - ) - - pods: MutableSequence[Pod] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Pod, - ) - nodes: MutableSequence[Node] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Node, - ) - node_pools: MutableSequence[NodePool] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=NodePool, - ) - roles: MutableSequence[Role] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=Role, - ) - bindings: MutableSequence[Binding] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Binding, - ) - access_reviews: MutableSequence[AccessReview] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=AccessReview, - ) - objects: MutableSequence[Object] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Object, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.py deleted file mode 100644 index 8ece19d81c07..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/label.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.securitycenter.v1', - manifest={ - 'Label', - }, -) - - -class Label(proto.Message): - r"""Represents a generic name-value label. A label has separate name and - value fields to support filtering with the ``contains()`` function. - For more information, see `Filtering on array-type - fields `__. - - Attributes: - name (str): - Name of the label. - value (str): - Value that corresponds to the label's name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.py deleted file mode 100644 index 050b3b0c6c9a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/load_balancer.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.cloud.securitycenter.v1', - manifest={ - 'LoadBalancer', - }, -) - - -class LoadBalancer(proto.Message): - r"""Contains information related to the load balancer associated - with the finding. - - Attributes: - name (str): - The name of the load balancer associated with - the finding. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.py deleted file mode 100644 index 6e4222745dd0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/log_entry.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 __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.securitycenter.v1', - manifest={ - 'LogEntry', - 'CloudLoggingEntry', - }, -) - - -class LogEntry(proto.Message): - r"""An individual entry in a log. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - cloud_logging_entry (google.cloud.securitycenter_v1.types.CloudLoggingEntry): - An individual entry in a log stored in Cloud - Logging. - - This field is a member of `oneof`_ ``log_entry``. - """ - - cloud_logging_entry: 'CloudLoggingEntry' = proto.Field( - proto.MESSAGE, - number=1, - oneof='log_entry', - message='CloudLoggingEntry', - ) - - -class CloudLoggingEntry(proto.Message): - r"""Metadata taken from a `Cloud Logging - LogEntry `__ - - Attributes: - insert_id (str): - A unique identifier for the log entry. - log_id (str): - The type of the log (part of ``log_name``. ``log_name`` is - the resource name of the log to which this log entry - belongs). For example: - ``cloudresourcemanager.googleapis.com/activity``. Note that - this field is not URL-encoded, unlike the ``LOG_ID`` field - in ``LogEntry``. - resource_container (str): - The organization, folder, or project of the - monitored resource that produced this log entry. - timestamp (google.protobuf.timestamp_pb2.Timestamp): - The time the event described by the log entry - occurred. - """ - - insert_id: str = proto.Field( - proto.STRING, - number=1, - ) - log_id: str = proto.Field( - proto.STRING, - number=2, - ) - resource_container: str = proto.Field( - proto.STRING, - number=3, - ) - timestamp: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.py deleted file mode 100644 index 1bdd822aa661..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mitre_attack.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'MitreAttack', - }, -) - - -class MitreAttack(proto.Message): - r"""MITRE ATT&CK tactics and techniques related to this finding. - See: https://attack.mitre.org - - Attributes: - primary_tactic (google.cloud.securitycenter_v1.types.MitreAttack.Tactic): - The MITRE ATT&CK tactic most closely - represented by this finding, if any. - primary_techniques (MutableSequence[google.cloud.securitycenter_v1.types.MitreAttack.Technique]): - The MITRE ATT&CK technique most closely represented by this - finding, if any. primary_techniques is a repeated field - because there are multiple levels of MITRE ATT&CK - techniques. If the technique most closely represented by - this finding is a sub-technique (e.g. - ``SCANNING_IP_BLOCKS``), both the sub-technique and its - parent technique(s) will be listed (e.g. - ``SCANNING_IP_BLOCKS``, ``ACTIVE_SCANNING``). - additional_tactics (MutableSequence[google.cloud.securitycenter_v1.types.MitreAttack.Tactic]): - Additional MITRE ATT&CK tactics related to - this finding, if any. - additional_techniques (MutableSequence[google.cloud.securitycenter_v1.types.MitreAttack.Technique]): - Additional MITRE ATT&CK techniques related to - this finding, if any, along with any of their - respective parent techniques. - version (str): - The MITRE ATT&CK version referenced by the - above fields. E.g. "8". - """ - class Tactic(proto.Enum): - r"""MITRE ATT&CK tactics that can be referenced by SCC findings. - See: https://attack.mitre.org/tactics/enterprise/ - - Values: - TACTIC_UNSPECIFIED (0): - Unspecified value. - RECONNAISSANCE (1): - TA0043 - RESOURCE_DEVELOPMENT (2): - TA0042 - INITIAL_ACCESS (5): - TA0001 - EXECUTION (3): - TA0002 - PERSISTENCE (6): - TA0003 - PRIVILEGE_ESCALATION (8): - TA0004 - DEFENSE_EVASION (7): - TA0005 - CREDENTIAL_ACCESS (9): - TA0006 - DISCOVERY (10): - TA0007 - LATERAL_MOVEMENT (11): - TA0008 - COLLECTION (12): - TA0009 - COMMAND_AND_CONTROL (4): - TA0011 - EXFILTRATION (13): - TA0010 - IMPACT (14): - TA0040 - """ - TACTIC_UNSPECIFIED = 0 - RECONNAISSANCE = 1 - RESOURCE_DEVELOPMENT = 2 - INITIAL_ACCESS = 5 - EXECUTION = 3 - PERSISTENCE = 6 - PRIVILEGE_ESCALATION = 8 - DEFENSE_EVASION = 7 - CREDENTIAL_ACCESS = 9 - DISCOVERY = 10 - LATERAL_MOVEMENT = 11 - COLLECTION = 12 - COMMAND_AND_CONTROL = 4 - EXFILTRATION = 13 - IMPACT = 14 - - class Technique(proto.Enum): - r"""MITRE ATT&CK techniques that can be referenced by SCC - findings. See: https://attack.mitre.org/techniques/enterprise/ - Next ID: 65 - - Values: - TECHNIQUE_UNSPECIFIED (0): - Unspecified value. - MASQUERADING (49): - T1036 - MATCH_LEGITIMATE_NAME_OR_LOCATION (50): - T1036.005 - BOOT_OR_LOGON_INITIALIZATION_SCRIPTS (37): - T1037 - STARTUP_ITEMS (38): - T1037.005 - NETWORK_SERVICE_DISCOVERY (32): - T1046 - PROCESS_DISCOVERY (56): - T1057 - COMMAND_AND_SCRIPTING_INTERPRETER (6): - T1059 - UNIX_SHELL (7): - T1059.004 - PYTHON (59): - T1059.006 - EXPLOITATION_FOR_PRIVILEGE_ESCALATION (63): - T1068 - PERMISSION_GROUPS_DISCOVERY (18): - T1069 - CLOUD_GROUPS (19): - T1069.003 - INDICATOR_REMOVAL_FILE_DELETION (64): - T1070.004 - APPLICATION_LAYER_PROTOCOL (45): - T1071 - DNS (46): - T1071.004 - SOFTWARE_DEPLOYMENT_TOOLS (47): - T1072 - VALID_ACCOUNTS (14): - T1078 - DEFAULT_ACCOUNTS (35): - T1078.001 - LOCAL_ACCOUNTS (15): - T1078.003 - CLOUD_ACCOUNTS (16): - T1078.004 - PROXY (9): - T1090 - EXTERNAL_PROXY (10): - T1090.002 - MULTI_HOP_PROXY (11): - T1090.003 - ACCOUNT_MANIPULATION (22): - T1098 - ADDITIONAL_CLOUD_CREDENTIALS (40): - T1098.001 - SSH_AUTHORIZED_KEYS (23): - T1098.004 - ADDITIONAL_CONTAINER_CLUSTER_ROLES (58): - T1098.006 - INGRESS_TOOL_TRANSFER (3): - T1105 - NATIVE_API (4): - T1106 - BRUTE_FORCE (44): - T1110 - SHARED_MODULES (5): - T1129 - ACCESS_TOKEN_MANIPULATION (33): - T1134 - TOKEN_IMPERSONATION_OR_THEFT (39): - T1134.001 - EXPLOIT_PUBLIC_FACING_APPLICATION (27): - T1190 - DOMAIN_POLICY_MODIFICATION (30): - T1484 - DATA_DESTRUCTION (29): - T1485 - SERVICE_STOP (52): - T1489 - INHIBIT_SYSTEM_RECOVERY (36): - T1490 - RESOURCE_HIJACKING (8): - T1496 - NETWORK_DENIAL_OF_SERVICE (17): - T1498 - CLOUD_SERVICE_DISCOVERY (48): - T1526 - STEAL_APPLICATION_ACCESS_TOKEN (42): - T1528 - ACCOUNT_ACCESS_REMOVAL (51): - T1531 - STEAL_WEB_SESSION_COOKIE (25): - T1539 - CREATE_OR_MODIFY_SYSTEM_PROCESS (24): - T1543 - ABUSE_ELEVATION_CONTROL_MECHANISM (34): - T1548 - UNSECURED_CREDENTIALS (13): - T1552 - MODIFY_AUTHENTICATION_PROCESS (28): - T1556 - IMPAIR_DEFENSES (31): - T1562 - DISABLE_OR_MODIFY_TOOLS (55): - T1562.001 - EXFILTRATION_OVER_WEB_SERVICE (20): - T1567 - EXFILTRATION_TO_CLOUD_STORAGE (21): - T1567.002 - DYNAMIC_RESOLUTION (12): - T1568 - LATERAL_TOOL_TRANSFER (41): - T1570 - MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE (26): - T1578 - CREATE_SNAPSHOT (54): - T1578.001 - CLOUD_INFRASTRUCTURE_DISCOVERY (53): - T1580 - OBTAIN_CAPABILITIES (43): - T1588 - ACTIVE_SCANNING (1): - T1595 - SCANNING_IP_BLOCKS (2): - T1595.001 - CONTAINER_ADMINISTRATION_COMMAND (60): - T1609 - ESCAPE_TO_HOST (61): - T1611 - CONTAINER_AND_RESOURCE_DISCOVERY (57): - T1613 - STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES (62): - T1649 - """ - TECHNIQUE_UNSPECIFIED = 0 - MASQUERADING = 49 - MATCH_LEGITIMATE_NAME_OR_LOCATION = 50 - BOOT_OR_LOGON_INITIALIZATION_SCRIPTS = 37 - STARTUP_ITEMS = 38 - NETWORK_SERVICE_DISCOVERY = 32 - PROCESS_DISCOVERY = 56 - COMMAND_AND_SCRIPTING_INTERPRETER = 6 - UNIX_SHELL = 7 - PYTHON = 59 - EXPLOITATION_FOR_PRIVILEGE_ESCALATION = 63 - PERMISSION_GROUPS_DISCOVERY = 18 - CLOUD_GROUPS = 19 - INDICATOR_REMOVAL_FILE_DELETION = 64 - APPLICATION_LAYER_PROTOCOL = 45 - DNS = 46 - SOFTWARE_DEPLOYMENT_TOOLS = 47 - VALID_ACCOUNTS = 14 - DEFAULT_ACCOUNTS = 35 - LOCAL_ACCOUNTS = 15 - CLOUD_ACCOUNTS = 16 - PROXY = 9 - EXTERNAL_PROXY = 10 - MULTI_HOP_PROXY = 11 - ACCOUNT_MANIPULATION = 22 - ADDITIONAL_CLOUD_CREDENTIALS = 40 - SSH_AUTHORIZED_KEYS = 23 - ADDITIONAL_CONTAINER_CLUSTER_ROLES = 58 - INGRESS_TOOL_TRANSFER = 3 - NATIVE_API = 4 - BRUTE_FORCE = 44 - SHARED_MODULES = 5 - ACCESS_TOKEN_MANIPULATION = 33 - TOKEN_IMPERSONATION_OR_THEFT = 39 - EXPLOIT_PUBLIC_FACING_APPLICATION = 27 - DOMAIN_POLICY_MODIFICATION = 30 - DATA_DESTRUCTION = 29 - SERVICE_STOP = 52 - INHIBIT_SYSTEM_RECOVERY = 36 - RESOURCE_HIJACKING = 8 - NETWORK_DENIAL_OF_SERVICE = 17 - CLOUD_SERVICE_DISCOVERY = 48 - STEAL_APPLICATION_ACCESS_TOKEN = 42 - ACCOUNT_ACCESS_REMOVAL = 51 - STEAL_WEB_SESSION_COOKIE = 25 - CREATE_OR_MODIFY_SYSTEM_PROCESS = 24 - ABUSE_ELEVATION_CONTROL_MECHANISM = 34 - UNSECURED_CREDENTIALS = 13 - MODIFY_AUTHENTICATION_PROCESS = 28 - IMPAIR_DEFENSES = 31 - DISABLE_OR_MODIFY_TOOLS = 55 - EXFILTRATION_OVER_WEB_SERVICE = 20 - EXFILTRATION_TO_CLOUD_STORAGE = 21 - DYNAMIC_RESOLUTION = 12 - LATERAL_TOOL_TRANSFER = 41 - MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE = 26 - CREATE_SNAPSHOT = 54 - CLOUD_INFRASTRUCTURE_DISCOVERY = 53 - OBTAIN_CAPABILITIES = 43 - ACTIVE_SCANNING = 1 - SCANNING_IP_BLOCKS = 2 - CONTAINER_ADMINISTRATION_COMMAND = 60 - ESCAPE_TO_HOST = 61 - CONTAINER_AND_RESOURCE_DISCOVERY = 57 - STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES = 62 - - primary_tactic: Tactic = proto.Field( - proto.ENUM, - number=1, - enum=Tactic, - ) - primary_techniques: MutableSequence[Technique] = proto.RepeatedField( - proto.ENUM, - number=2, - enum=Technique, - ) - additional_tactics: MutableSequence[Tactic] = proto.RepeatedField( - proto.ENUM, - number=3, - enum=Tactic, - ) - additional_techniques: MutableSequence[Technique] = proto.RepeatedField( - proto.ENUM, - number=4, - enum=Technique, - ) - version: str = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py deleted file mode 100644 index f6be11e40d9c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/mute_config.py +++ /dev/null @@ -1,171 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'MuteConfig', - }, -) - - -class MuteConfig(proto.Message): - r"""A mute config is a Cloud SCC resource that contains the - configuration to mute create/update events of findings. - - Attributes: - name (str): - This field will be ignored if provided on config creation. - Format - ``organizations/{organization}/muteConfigs/{mute_config}`` - ``folders/{folder}/muteConfigs/{mute_config}`` - ``projects/{project}/muteConfigs/{mute_config}`` - ``organizations/{organization}/locations/global/muteConfigs/{mute_config}`` - ``folders/{folder}/locations/global/muteConfigs/{mute_config}`` - ``projects/{project}/locations/global/muteConfigs/{mute_config}`` - display_name (str): - The human readable name to be displayed for - the mute config. - description (str): - A description of the mute config. - filter (str): - Required. An expression that defines the filter to apply - across create/update events of findings. While creating a - filter string, be mindful of the scope in which the mute - configuration is being created. E.g., If a filter contains - project = X but is created under the project = Y scope, it - might not match any findings. - - The following field and operator combinations are supported: - - - severity: ``=``, ``:`` - - category: ``=``, ``:`` - - resource.name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.folders.resource_folder: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - - finding_class: ``=``, ``:`` - - indicator.ip_addresses: ``=``, ``:`` - - indicator.domains: ``=``, ``:`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the mute - config was created. This field is set by the - server and will be ignored if provided on config - creation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The most recent time at which - the mute config was updated. This field is set - by the server and will be ignored if provided on - config creation or update. - most_recent_editor (str): - Output only. Email address of the user who - last edited the mute config. This field is set - by the server and will be ignored if provided on - config creation or update. - type_ (google.cloud.securitycenter_v1.types.MuteConfig.MuteConfigType): - Optional. The type of the mute config, which - determines what type of mute state the config - affects. The static mute state takes precedence - over the dynamic mute state. Immutable after - creation. STATIC by default if not set during - creation. - expiry_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The expiry of the mute config. Only - applicable for dynamic configs. If the expiry is - set, when the config expires, it is removed from - all findings. - """ - class MuteConfigType(proto.Enum): - r"""The type of MuteConfig. - - Values: - MUTE_CONFIG_TYPE_UNSPECIFIED (0): - Unused. - STATIC (1): - A static mute config, which sets the static - mute state of future matching findings to muted. - Once the static mute state has been set, finding - or config modifications will not affect the - state. - DYNAMIC (2): - A dynamic mute config, which is applied to - existing and future matching findings, setting - their dynamic mute state to "muted". If the - config is updated or deleted, or a matching - finding is updated, such that the finding - doesn't match the config, the config will be - removed from the finding, and the finding's - dynamic mute state may become "unmuted" (unless - other configs still match). - """ - MUTE_CONFIG_TYPE_UNSPECIFIED = 0 - STATIC = 1 - DYNAMIC = 2 - - 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, - ) - filter: 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, - ) - most_recent_editor: str = proto.Field( - proto.STRING, - number=7, - ) - type_: MuteConfigType = proto.Field( - proto.ENUM, - number=8, - enum=MuteConfigType, - ) - expiry_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py deleted file mode 100644 index 564197159f0c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notebook.py +++ /dev/null @@ -1,72 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v1', - manifest={ - 'Notebook', - }, -) - - -class Notebook(proto.Message): - r"""Represents a Jupyter notebook IPYNB file, such as a `Colab - Enterprise - notebook `__ file, - that is associated with a finding. - - Attributes: - name (str): - The name of the notebook. - service (str): - The source notebook service, for example, - "Colab Enterprise". - last_author (str): - The user ID of the latest author to modify - the notebook. - notebook_update_time (google.protobuf.timestamp_pb2.Timestamp): - The most recent time the notebook was - updated. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - service: str = proto.Field( - proto.STRING, - number=2, - ) - last_author: str = proto.Field( - proto.STRING, - number=3, - ) - notebook_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.py deleted file mode 100644 index d26990314b74..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_config.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'NotificationConfig', - }, -) - - -class NotificationConfig(proto.Message): - r"""Cloud Security Command Center (Cloud SCC) notification - configs. - A notification config is a Cloud SCC resource that contains the - configuration to send notifications for create/update events of - findings, assets and etc. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The relative resource name of this notification config. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/notificationConfigs/notify_public_bucket", - "folders/{folder_id}/notificationConfigs/notify_public_bucket", - or - "projects/{project_id}/notificationConfigs/notify_public_bucket". - description (str): - The description of the notification config - (max of 1024 characters). - pubsub_topic (str): - The Pub/Sub topic to send notifications to. Its format is - "projects/[project_id]/topics/[topic]". - service_account (str): - Output only. The service account that needs - "pubsub.topics.publish" permission to publish to - the Pub/Sub topic. - streaming_config (google.cloud.securitycenter_v1.types.NotificationConfig.StreamingConfig): - The config for triggering streaming-based - notifications. - - This field is a member of `oneof`_ ``notify_config``. - """ - - class StreamingConfig(proto.Message): - r"""The config for streaming-based notifications, which send each - event as soon as it is detected. - - Attributes: - filter (str): - Expression that defines the filter to apply across - create/update events of assets or findings as specified by - the event type. The expression is a list of zero or more - restrictions combined via logical operators ``AND`` and - ``OR``. Parentheses are supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - """ - - filter: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - pubsub_topic: str = proto.Field( - proto.STRING, - number=3, - ) - service_account: str = proto.Field( - proto.STRING, - number=4, - ) - streaming_config: StreamingConfig = proto.Field( - proto.MESSAGE, - number=5, - oneof='notify_config', - message=StreamingConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.py deleted file mode 100644 index f979d5f7a0ec..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/notification_message.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import resource as gcs_resource - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'NotificationMessage', - }, -) - - -class NotificationMessage(proto.Message): - r"""Cloud SCC's Notification - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - notification_config_name (str): - Name of the notification config that - generated current notification. - finding (google.cloud.securitycenter_v1.types.Finding): - If it's a Finding based notification config, - this field will be populated. - - This field is a member of `oneof`_ ``event``. - resource (google.cloud.securitycenter_v1.types.Resource): - The Cloud resource tied to this - notification's Finding. - """ - - notification_config_name: str = proto.Field( - proto.STRING, - number=1, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=2, - oneof='event', - message=gcs_finding.Finding, - ) - resource: gcs_resource.Resource = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_resource.Resource, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.py deleted file mode 100644 index ebd7ac4b0424..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/org_policy.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.cloud.securitycenter.v1', - manifest={ - 'OrgPolicy', - }, -) - - -class OrgPolicy(proto.Message): - r"""Contains information about the org policies associated with - the finding. - - Attributes: - name (str): - The resource name of the org policy. Example: - "organizations/{organization_id}/policies/{constraint_name}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.py deleted file mode 100644 index 81c2816a1e66..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/organization_settings.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'OrganizationSettings', - }, -) - - -class OrganizationSettings(proto.Message): - r"""User specified settings that are attached to the Security - Command Center organization. - - Attributes: - name (str): - The relative resource name of the settings. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/organizationSettings". - enable_asset_discovery (bool): - A flag that indicates if Asset Discovery should be enabled. - If the flag is set to ``true``, then discovery of assets - will occur. If it is set to ``false``, all historical assets - will remain, but discovery of future assets will not occur. - asset_discovery_config (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig): - The configuration used for Asset Discovery - runs. - """ - - class AssetDiscoveryConfig(proto.Message): - r"""The configuration used for Asset Discovery runs. - - Attributes: - project_ids (MutableSequence[str]): - The project ids to use for filtering asset - discovery. - inclusion_mode (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): - The mode to use for filtering asset - discovery. - folder_ids (MutableSequence[str]): - The folder ids to use for filtering asset - discovery. It consists of only digits, e.g., - 756619654966. - """ - class InclusionMode(proto.Enum): - r"""The mode of inclusion when running Asset Discovery. Asset discovery - can be limited by explicitly identifying projects to be included or - excluded. If INCLUDE_ONLY is set, then only those projects within - the organization and their children are discovered during asset - discovery. If EXCLUDE is set, then projects that don't match those - projects are discovered during asset discovery. If neither are set, - then all projects within the organization are discovered during - asset discovery. - - Values: - INCLUSION_MODE_UNSPECIFIED (0): - Unspecified. Setting the mode with this value - will disable inclusion/exclusion filtering for - Asset Discovery. - INCLUDE_ONLY (1): - Asset Discovery will capture only the - resources within the projects specified. All - other resources will be ignored. - EXCLUDE (2): - Asset Discovery will ignore all resources - under the projects specified. All other - resources will be retrieved. - """ - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - project_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - inclusion_mode: 'OrganizationSettings.AssetDiscoveryConfig.InclusionMode' = proto.Field( - proto.ENUM, - number=2, - enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', - ) - folder_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - enable_asset_discovery: bool = proto.Field( - proto.BOOL, - number=2, - ) - asset_discovery_config: AssetDiscoveryConfig = proto.Field( - proto.MESSAGE, - number=3, - message=AssetDiscoveryConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py deleted file mode 100644 index 881b8df6dfa1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/process.py +++ /dev/null @@ -1,136 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1.types import file - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Process', - 'EnvironmentVariable', - }, -) - - -class Process(proto.Message): - r"""Represents an operating system process. - - Attributes: - name (str): - The process name, as displayed in utilities like ``top`` and - ``ps``. This name can be accessed through - ``/proc/[pid]/comm`` and changed with - ``prctl(PR_SET_NAME)``. - binary (google.cloud.securitycenter_v1.types.File): - File information for the process executable. - libraries (MutableSequence[google.cloud.securitycenter_v1.types.File]): - File information for libraries loaded by the - process. - script (google.cloud.securitycenter_v1.types.File): - When the process represents the invocation of a script, - ``binary`` provides information about the interpreter, while - ``script`` provides information about the script file - provided to the interpreter. - args (MutableSequence[str]): - Process arguments as JSON encoded strings. - arguments_truncated (bool): - True if ``args`` is incomplete. - env_variables (MutableSequence[google.cloud.securitycenter_v1.types.EnvironmentVariable]): - Process environment variables. - env_variables_truncated (bool): - True if ``env_variables`` is incomplete. - pid (int): - The process ID. - parent_pid (int): - The parent process ID. - """ - - name: str = proto.Field( - proto.STRING, - number=12, - ) - binary: file.File = proto.Field( - proto.MESSAGE, - number=3, - message=file.File, - ) - libraries: MutableSequence[file.File] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=file.File, - ) - script: file.File = proto.Field( - proto.MESSAGE, - number=5, - message=file.File, - ) - args: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - arguments_truncated: bool = proto.Field( - proto.BOOL, - number=7, - ) - env_variables: MutableSequence['EnvironmentVariable'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='EnvironmentVariable', - ) - env_variables_truncated: bool = proto.Field( - proto.BOOL, - number=9, - ) - pid: int = proto.Field( - proto.INT64, - number=10, - ) - parent_pid: int = proto.Field( - proto.INT64, - number=11, - ) - - -class EnvironmentVariable(proto.Message): - r"""A name-value pair representing an environment variable used - in an operating system process. - - Attributes: - name (str): - Environment variable name as a JSON encoded - string. - val (str): - Environment variable value as a JSON encoded - string. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - val: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py deleted file mode 100644 index f66c0ab5f06d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource.py +++ /dev/null @@ -1,474 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1.types import folder - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'CloudProvider', - 'Resource', - 'AwsMetadata', - 'AzureMetadata', - 'ResourcePath', - }, -) - - -class CloudProvider(proto.Enum): - r"""Enumeration representing the various cloud providers a - finding's resource could reside in. - - Values: - CLOUD_PROVIDER_UNSPECIFIED (0): - The cloud provider is unspecified. - GOOGLE_CLOUD_PLATFORM (1): - The cloud provider is Google Cloud Platform. - AMAZON_WEB_SERVICES (2): - The cloud provider is Amazon Web Services. - MICROSOFT_AZURE (3): - The cloud provider is Microsoft Azure. - """ - CLOUD_PROVIDER_UNSPECIFIED = 0 - GOOGLE_CLOUD_PLATFORM = 1 - AMAZON_WEB_SERVICES = 2 - MICROSOFT_AZURE = 3 - - -class Resource(proto.Message): - r"""Information related to the Google Cloud 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): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - display_name (str): - The human readable name of the resource. - type_ (str): - The full resource type of the resource. - project (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The project ID that the resource belongs to. - parent (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (MutableSequence[google.cloud.securitycenter_v1.types.Folder]): - Output only. Contains a Folder message for - each folder in the assets ancestry. The first - folder is the deepest nested folder, and the - last folder is the folder directly under the - Organization. - cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): - Indicates which cloud provider the resource - resides in. - organization (str): - Indicates which organization or tenant in the - cloud provider the finding applies to. - service (str): - The parent service or product from which the - resource is provided, for example, GKE or SNS. - location (str): - The region or location of the service (if - applicable). - aws_metadata (google.cloud.securitycenter_v1.types.AwsMetadata): - The AWS metadata associated with the finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - azure_metadata (google.cloud.securitycenter_v1.types.AzureMetadata): - The Azure metadata associated with the - finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - resource_path (google.cloud.securitycenter_v1.types.ResourcePath): - Provides the path to the resource within the - resource hierarchy. - resource_path_string (str): - A string representation of the resource path. For Google - Cloud, it has the format of - ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` - where there can be any number of folders. For AWS, it has - the format of - ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` - where there can be any number of organizational units. For - Azure, it has the format of - ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` - where there can be any number of management groups. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=8, - ) - type_: str = proto.Field( - proto.STRING, - number=6, - ) - project: str = proto.Field( - proto.STRING, - number=2, - ) - project_display_name: str = proto.Field( - proto.STRING, - number=3, - ) - parent: str = proto.Field( - proto.STRING, - number=4, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=5, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=folder.Folder, - ) - cloud_provider: 'CloudProvider' = proto.Field( - proto.ENUM, - number=9, - enum='CloudProvider', - ) - organization: str = proto.Field( - proto.STRING, - number=10, - ) - service: str = proto.Field( - proto.STRING, - number=11, - ) - location: str = proto.Field( - proto.STRING, - number=12, - ) - aws_metadata: 'AwsMetadata' = proto.Field( - proto.MESSAGE, - number=16, - oneof='cloud_provider_metadata', - message='AwsMetadata', - ) - azure_metadata: 'AzureMetadata' = proto.Field( - proto.MESSAGE, - number=17, - oneof='cloud_provider_metadata', - message='AzureMetadata', - ) - resource_path: 'ResourcePath' = proto.Field( - proto.MESSAGE, - number=18, - message='ResourcePath', - ) - resource_path_string: str = proto.Field( - proto.STRING, - number=19, - ) - - -class AwsMetadata(proto.Message): - r"""AWS metadata associated with the resource, only applicable if - the finding's cloud provider is Amazon Web Services. - - Attributes: - organization (google.cloud.securitycenter_v1.types.AwsMetadata.AwsOrganization): - The AWS organization associated with the - resource. - organizational_units (MutableSequence[google.cloud.securitycenter_v1.types.AwsMetadata.AwsOrganizationalUnit]): - A list of AWS organizational units associated - with the resource, ordered from lowest level - (closest to the account) to highest level. - account (google.cloud.securitycenter_v1.types.AwsMetadata.AwsAccount): - The AWS account associated with the resource. - """ - - class AwsOrganization(proto.Message): - r"""An organization is a collection of accounts that are - centrally managed together using consolidated billing, organized - hierarchically with organizational units (OUs), and controlled - with policies. - - Attributes: - id (str): - The unique identifier (ID) for the - organization. The regex pattern for an - organization ID string requires "o-" followed by - from 10 to 32 lowercase letters or digits. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - - class AwsOrganizationalUnit(proto.Message): - r"""An Organizational Unit (OU) is a container of AWS accounts - within a root of an organization. Policies that are attached to - an OU apply to all accounts contained in that OU and in any - child OUs. - - Attributes: - id (str): - The unique identifier (ID) associated with - this OU. The regex pattern for an organizational - unit ID string requires "ou-" followed by from 4 - to 32 lowercase letters or digits (the ID of the - root that contains the OU). This string is - followed by a second "-" dash and from 8 to 32 - additional lowercase letters or digits. For - example, "ou-ab12-cd34ef56". - name (str): - The friendly name of the OU. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - - class AwsAccount(proto.Message): - r"""An AWS account that is a member of an organization. - - Attributes: - id (str): - The unique identifier (ID) of the account, - containing exactly 12 digits. - name (str): - The friendly name of this account. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - - organization: AwsOrganization = proto.Field( - proto.MESSAGE, - number=2, - message=AwsOrganization, - ) - organizational_units: MutableSequence[AwsOrganizationalUnit] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=AwsOrganizationalUnit, - ) - account: AwsAccount = proto.Field( - proto.MESSAGE, - number=4, - message=AwsAccount, - ) - - -class AzureMetadata(proto.Message): - r"""Azure metadata associated with the resource, only applicable - if the finding's cloud provider is Microsoft Azure. - - Attributes: - management_groups (MutableSequence[google.cloud.securitycenter_v1.types.AzureMetadata.AzureManagementGroup]): - A list of Azure management groups associated - with the resource, ordered from lowest level - (closest to the subscription) to highest level. - subscription (google.cloud.securitycenter_v1.types.AzureMetadata.AzureSubscription): - The Azure subscription associated with the - resource. - resource_group (google.cloud.securitycenter_v1.types.AzureMetadata.AzureResourceGroup): - The Azure resource group associated with the - resource. - """ - - class AzureManagementGroup(proto.Message): - r"""Represents an Azure management group. - - Attributes: - id (str): - The UUID of the Azure management group, for example, - ``20000000-0001-0000-0000-000000000000``. - display_name (str): - The display name of the Azure management - group. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - class AzureSubscription(proto.Message): - r"""Represents an Azure subscription. - - Attributes: - id (str): - The UUID of the Azure subscription, for example, - ``291bba3f-e0a5-47bc-a099-3bdcb2a50a05``. - display_name (str): - The display name of the Azure subscription. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - class AzureResourceGroup(proto.Message): - r"""Represents an Azure resource group. - - Attributes: - name (str): - The name of the Azure resource group. This is - not a UUID. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - management_groups: MutableSequence[AzureManagementGroup] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=AzureManagementGroup, - ) - subscription: AzureSubscription = proto.Field( - proto.MESSAGE, - number=5, - message=AzureSubscription, - ) - resource_group: AzureResourceGroup = proto.Field( - proto.MESSAGE, - number=6, - message=AzureResourceGroup, - ) - - -class ResourcePath(proto.Message): - r"""Represents the path of resources leading up to the resource - this finding is about. - - Attributes: - nodes (MutableSequence[google.cloud.securitycenter_v1.types.ResourcePath.ResourcePathNode]): - The list of nodes that make the up resource - path, ordered from lowest level to highest - level. - """ - class ResourcePathNodeType(proto.Enum): - r"""The type of resource the node represents. - - Values: - RESOURCE_PATH_NODE_TYPE_UNSPECIFIED (0): - Node type is unspecified. - GCP_ORGANIZATION (1): - The node represents a Google Cloud - organization. - GCP_FOLDER (2): - The node represents a Google Cloud folder. - GCP_PROJECT (3): - The node represents a Google Cloud project. - AWS_ORGANIZATION (4): - The node represents an AWS organization. - AWS_ORGANIZATIONAL_UNIT (5): - The node represents an AWS organizational - unit. - AWS_ACCOUNT (6): - The node represents an AWS account. - AZURE_MANAGEMENT_GROUP (7): - The node represents an Azure management - group. - AZURE_SUBSCRIPTION (8): - The node represents an Azure subscription. - AZURE_RESOURCE_GROUP (9): - The node represents an Azure resource group. - """ - RESOURCE_PATH_NODE_TYPE_UNSPECIFIED = 0 - GCP_ORGANIZATION = 1 - GCP_FOLDER = 2 - GCP_PROJECT = 3 - AWS_ORGANIZATION = 4 - AWS_ORGANIZATIONAL_UNIT = 5 - AWS_ACCOUNT = 6 - AZURE_MANAGEMENT_GROUP = 7 - AZURE_SUBSCRIPTION = 8 - AZURE_RESOURCE_GROUP = 9 - - class ResourcePathNode(proto.Message): - r"""A node within the resource path. Each node represents a - resource within the resource hierarchy. - - Attributes: - node_type (google.cloud.securitycenter_v1.types.ResourcePath.ResourcePathNodeType): - The type of resource this node represents. - id (str): - The ID of the resource this node represents. - display_name (str): - The display name of the resource this node - represents. - """ - - node_type: 'ResourcePath.ResourcePathNodeType' = proto.Field( - proto.ENUM, - number=1, - enum='ResourcePath.ResourcePathNodeType', - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - - nodes: MutableSequence[ResourcePathNode] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ResourcePathNode, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py deleted file mode 100644 index f88354103169..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/resource_value_config.py +++ /dev/null @@ -1,189 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1.types import resource -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'ResourceValue', - 'ResourceValueConfig', - }, -) - - -class ResourceValue(proto.Enum): - r"""Value enum to map to a resource - - Values: - RESOURCE_VALUE_UNSPECIFIED (0): - Unspecific value - HIGH (1): - High resource value - MEDIUM (2): - Medium resource value - LOW (3): - Low resource value - NONE (4): - No resource value, e.g. ignore these - resources - """ - RESOURCE_VALUE_UNSPECIFIED = 0 - HIGH = 1 - MEDIUM = 2 - LOW = 3 - NONE = 4 - - -class ResourceValueConfig(proto.Message): - r"""A resource value configuration (RVC) is a mapping - configuration of user's resources to resource values. Used in - Attack path simulations. - - Attributes: - name (str): - Name for the resource value configuration - resource_value (google.cloud.securitycenter_v1.types.ResourceValue): - Required. Resource value level this - expression represents - tag_values (MutableSequence[str]): - Required. Tag values combined with ``AND`` to check against. - Values in the form "tagValues/123" Example: - ``[ "tagValues/123", "tagValues/456", "tagValues/789" ]`` - https://cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing - resource_type (str): - Apply resource_value only to resources that match - resource_type. resource_type will be checked with ``AND`` of - other resources. For example, - "storage.googleapis.com/Bucket" with resource_value "HIGH" - will apply "HIGH" value only to - "storage.googleapis.com/Bucket" resources. - scope (str): - Project or folder to scope this configuration to. For - example, "project/456" would apply this configuration only - to resources in "project/456" scope will be checked with - ``AND`` of other resources. - resource_labels_selector (MutableMapping[str, str]): - List of resource labels to search for, evaluated with - ``AND``. For example, - ``"resource_labels_selector": {"key": "value", "env": "prod"}`` - will match resources with labels "key": "value" ``AND`` - "env": "prod" - https://cloud.google.com/resource-manager/docs/creating-managing-labels - description (str): - Description of the resource value - configuration. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp this resource value - configuration was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp this resource value - configuration was last updated. - cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): - Cloud provider this configuration applies to - sensitive_data_protection_mapping (google.cloud.securitycenter_v1.types.ResourceValueConfig.SensitiveDataProtectionMapping): - A mapping of the sensitivity on Sensitive Data Protection - finding to resource values. This mapping can only be used in - combination with a resource_type that is related to - BigQuery, e.g. "bigquery.googleapis.com/Dataset". - """ - - class SensitiveDataProtectionMapping(proto.Message): - r"""Resource value mapping for Sensitive Data Protection findings. If - any of these mappings have a resource value that is not unspecified, - the resource_value field will be ignored when reading this - configuration. - - Attributes: - high_sensitivity_mapping (google.cloud.securitycenter_v1.types.ResourceValue): - Resource value mapping for high-sensitivity - Sensitive Data Protection findings - medium_sensitivity_mapping (google.cloud.securitycenter_v1.types.ResourceValue): - Resource value mapping for medium-sensitivity - Sensitive Data Protection findings - """ - - high_sensitivity_mapping: 'ResourceValue' = proto.Field( - proto.ENUM, - number=1, - enum='ResourceValue', - ) - medium_sensitivity_mapping: 'ResourceValue' = proto.Field( - proto.ENUM, - number=2, - enum='ResourceValue', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - resource_value: 'ResourceValue' = proto.Field( - proto.ENUM, - number=2, - enum='ResourceValue', - ) - tag_values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - resource_type: str = proto.Field( - proto.STRING, - number=4, - ) - scope: str = proto.Field( - proto.STRING, - number=5, - ) - resource_labels_selector: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=6, - ) - description: str = proto.Field( - proto.STRING, - number=7, - ) - 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, - ) - cloud_provider: resource.CloudProvider = proto.Field( - proto.ENUM, - number=10, - enum=resource.CloudProvider, - ) - sensitive_data_protection_mapping: SensitiveDataProtectionMapping = proto.Field( - proto.MESSAGE, - number=11, - message=SensitiveDataProtectionMapping, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py deleted file mode 100644 index e6ccc16862c3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.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 - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'RunAssetDiscoveryResponse', - }, -) - - -class RunAssetDiscoveryResponse(proto.Message): - r"""Response of asset discovery run - - Attributes: - state (google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse.State): - The state of an asset discovery run. - duration (google.protobuf.duration_pb2.Duration): - The duration between asset discovery run - start and end - """ - class State(proto.Enum): - r"""The state of an asset discovery run. - - Values: - STATE_UNSPECIFIED (0): - Asset discovery run state was unspecified. - COMPLETED (1): - Asset discovery run completed successfully. - SUPERSEDED (2): - Asset discovery run was cancelled with tasks - still pending, as another run for the same - organization was started with a higher priority. - TERMINATED (3): - Asset discovery run was killed and - terminated. - """ - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py deleted file mode 100644 index bb412145607c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_config.py +++ /dev/null @@ -1,173 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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 expr_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'CustomConfig', - }, -) - - -class CustomConfig(proto.Message): - r"""Defines the properties in a custom module configuration for - Security Health Analytics. Use the custom module configuration - to create custom detectors that generate custom findings for - resources that you specify. - - Attributes: - predicate (google.type.expr_pb2.Expr): - The CEL expression to evaluate to produce - findings. When the expression evaluates to true - against a resource, a finding is generated. - custom_output (google.cloud.securitycenter_v1.types.CustomConfig.CustomOutputSpec): - Custom output properties. - resource_selector (google.cloud.securitycenter_v1.types.CustomConfig.ResourceSelector): - The resource types that the custom module - operates on. Each custom module can specify up - to 5 resource types. - severity (google.cloud.securitycenter_v1.types.CustomConfig.Severity): - The severity to assign to findings generated - by the module. - description (str): - Text that describes the vulnerability or - misconfiguration that the custom module detects. - This explanation is returned with each finding - instance to help investigators understand the - detected issue. The text must be enclosed in - quotation marks. - recommendation (str): - An explanation of the recommended steps that security teams - can take to resolve the detected issue. This explanation is - returned with each finding generated by this module in the - ``nextSteps`` property of the finding JSON. - """ - class Severity(proto.Enum): - r"""Defines the valid value options for the severity of a - finding. - - Values: - SEVERITY_UNSPECIFIED (0): - Unspecified severity. - 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 - - class CustomOutputSpec(proto.Message): - r"""A set of optional name-value pairs that define custom source - properties to return with each finding that is generated by the - custom module. The custom source properties that are defined here - are included in the finding JSON under ``sourceProperties``. - - Attributes: - properties (MutableSequence[google.cloud.securitycenter_v1.types.CustomConfig.CustomOutputSpec.Property]): - A list of custom output properties to add to - the finding. - """ - - class Property(proto.Message): - r"""An individual name-value pair that defines a custom source - property. - - Attributes: - name (str): - Name of the property for the custom output. - value_expression (google.type.expr_pb2.Expr): - The CEL expression for the custom output. A - resource property can be specified to return the - value of the property or a text string enclosed - in quotation marks. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - value_expression: expr_pb2.Expr = proto.Field( - proto.MESSAGE, - number=2, - message=expr_pb2.Expr, - ) - - properties: MutableSequence['CustomConfig.CustomOutputSpec.Property'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='CustomConfig.CustomOutputSpec.Property', - ) - - class ResourceSelector(proto.Message): - r"""Resource for selecting resource type. - - Attributes: - resource_types (MutableSequence[str]): - The resource types to run the detector on. - """ - - resource_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - predicate: expr_pb2.Expr = proto.Field( - proto.MESSAGE, - number=1, - message=expr_pb2.Expr, - ) - custom_output: CustomOutputSpec = proto.Field( - proto.MESSAGE, - number=2, - message=CustomOutputSpec, - ) - resource_selector: ResourceSelector = proto.Field( - proto.MESSAGE, - number=3, - message=ResourceSelector, - ) - severity: Severity = proto.Field( - proto.ENUM, - number=4, - enum=Severity, - ) - description: str = proto.Field( - proto.STRING, - number=5, - ) - recommendation: str = proto.Field( - proto.STRING, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.py deleted file mode 100644 index 654cd7d75826..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_health_analytics_custom_module.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'SecurityHealthAnalyticsCustomModule', - }, -) - - -class SecurityHealthAnalyticsCustomModule(proto.Message): - r"""Represents an instance of a Security Health Analytics custom - module, including its full module name, display name, enablement - state, and last updated time. You can create a custom module at - the organization, folder, or project level. Custom modules that - you create at the organization or folder level are inherited by - the child folders and projects. - - Attributes: - name (str): - Immutable. The resource name of the custom - module. Its format is - "organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}", - or - "folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}", - or - "projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}" - - The id {customModule} is server-generated and is - not user settable. It will be a numeric id - containing 1-20 digits. - display_name (str): - The display name of the Security Health - Analytics custom module. This display name - becomes the finding category for all findings - that are returned by this custom module. The - display name must be between 1 and 128 - characters, start with a lowercase letter, and - contain alphanumeric characters or underscores - only. - enablement_state (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule.EnablementState): - The enablement state of the custom module. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the custom - module was last updated. - last_editor (str): - Output only. The editor that last updated the - custom module. - ancestor_module (str): - Output only. If empty, indicates that the custom module was - created in the organization, folder, or project in which you - are viewing the custom module. Otherwise, - ``ancestor_module`` specifies the organization or folder - from which the custom module is inherited. - custom_config (google.cloud.securitycenter_v1.types.CustomConfig): - The user specified custom configuration for - the module. - """ - class EnablementState(proto.Enum): - r"""Possible enablement states of a custom module. - - Values: - ENABLEMENT_STATE_UNSPECIFIED (0): - Unspecified enablement state. - ENABLED (1): - The module is enabled at the given CRM - resource. - DISABLED (2): - The module is disabled at the given CRM - resource. - INHERITED (3): - State is inherited from an ancestor module. - The module will either be effectively ENABLED or - DISABLED based on its closest non-inherited - ancestor module in the CRM hierarchy. - """ - ENABLEMENT_STATE_UNSPECIFIED = 0 - ENABLED = 1 - DISABLED = 2 - INHERITED = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - enablement_state: EnablementState = proto.Field( - proto.ENUM, - number=4, - enum=EnablementState, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - last_editor: str = proto.Field( - proto.STRING, - number=6, - ) - ancestor_module: str = proto.Field( - proto.STRING, - number=7, - ) - custom_config: security_health_analytics_custom_config.CustomConfig = proto.Field( - proto.MESSAGE, - number=8, - message=security_health_analytics_custom_config.CustomConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.py deleted file mode 100644 index 4c141c1aa108..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_marks.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'SecurityMarks', - }, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (MutableMapping[str, str]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - canonical_name (str): - The canonical name of the marks. Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "folders/{folder_id}/assets/{asset_id}/securityMarks" - "projects/{project_number}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" - "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - marks: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.py deleted file mode 100644 index c929af3ef59a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/security_posture.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'SecurityPosture', - }, -) - - -class SecurityPosture(proto.Message): - r"""Represents a posture that is deployed on Google Cloud by the - Security Command Center Posture Management service. A posture - contains one or more policy sets. A policy set is a group of - policies that enforce a set of security rules on Google Cloud. - - Attributes: - name (str): - Name of the posture, for example, ``CIS-Posture``. - revision_id (str): - The version of the posture, for example, ``c7cfa2a8``. - posture_deployment_resource (str): - The project, folder, or organization on which the posture is - deployed, for example, ``projects/{project_number}``. - posture_deployment (str): - The name of the posture deployment, for example, - ``organizations/{org_id}/posturedeployments/{posture_deployment_id}``. - changed_policy (str): - The name of the updated policy, for example, - ``projects/{project_id}/policies/{constraint_name}``. - policy_set (str): - The name of the updated policyset, for example, - ``cis-policyset``. - policy (str): - The ID of the updated policy, for example, - ``compute-policy-1``. - policy_drift_details (MutableSequence[google.cloud.securitycenter_v1.types.SecurityPosture.PolicyDriftDetails]): - The details about a change in an updated - policy that violates the deployed posture. - """ - - class PolicyDriftDetails(proto.Message): - r"""The policy field that violates the deployed posture and its - expected and detected values. - - Attributes: - field (str): - The name of the updated field, for example - constraint.implementation.policy_rules[0].enforce - expected_value (str): - The value of this field that was configured in a posture, - for example, ``true`` or - ``allowed_values={"projects/29831892"}``. - detected_value (str): - The detected value that violates the deployed posture, for - example, ``false`` or - ``allowed_values={"projects/22831892"}``. - """ - - field: str = proto.Field( - proto.STRING, - number=1, - ) - expected_value: str = proto.Field( - proto.STRING, - number=2, - ) - detected_value: str = proto.Field( - proto.STRING, - number=3, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - ) - posture_deployment_resource: str = proto.Field( - proto.STRING, - number=3, - ) - posture_deployment: str = proto.Field( - proto.STRING, - number=4, - ) - changed_policy: str = proto.Field( - proto.STRING, - number=5, - ) - policy_set: str = proto.Field( - proto.STRING, - number=6, - ) - policy: str = proto.Field( - proto.STRING, - number=7, - ) - policy_drift_details: MutableSequence[PolicyDriftDetails] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=PolicyDriftDetails, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py deleted file mode 100644 index f249dad54176..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py +++ /dev/null @@ -1,3519 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1.types import asset as gcs_asset -from google.cloud.securitycenter_v1.types import attack_path -from google.cloud.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import folder -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import resource as gcs_resource -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import valued_resource -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'BulkMuteFindingsRequest', - 'BulkMuteFindingsResponse', - 'CreateFindingRequest', - 'CreateMuteConfigRequest', - 'CreateResourceValueConfigRequest', - 'BatchCreateResourceValueConfigsRequest', - 'BatchCreateResourceValueConfigsResponse', - 'DeleteResourceValueConfigRequest', - 'GetResourceValueConfigRequest', - 'ListResourceValueConfigsRequest', - 'ListResourceValueConfigsResponse', - 'UpdateResourceValueConfigRequest', - 'CreateNotificationConfigRequest', - 'CreateSecurityHealthAnalyticsCustomModuleRequest', - 'CreateSourceRequest', - 'DeleteMuteConfigRequest', - 'DeleteNotificationConfigRequest', - 'DeleteSecurityHealthAnalyticsCustomModuleRequest', - 'GetBigQueryExportRequest', - 'GetMuteConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetEffectiveSecurityHealthAnalyticsCustomModuleRequest', - 'GetSecurityHealthAnalyticsCustomModuleRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListDescendantSecurityHealthAnalyticsCustomModulesRequest', - 'ListDescendantSecurityHealthAnalyticsCustomModulesResponse', - 'ListValuedResourcesRequest', - 'ListValuedResourcesResponse', - 'ListAttackPathsRequest', - 'ListAttackPathsResponse', - 'GetSimulationRequest', - 'GetValuedResourceRequest', - 'ListMuteConfigsRequest', - 'ListMuteConfigsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListEffectiveSecurityHealthAnalyticsCustomModulesRequest', - 'ListEffectiveSecurityHealthAnalyticsCustomModulesResponse', - 'ListSecurityHealthAnalyticsCustomModulesRequest', - 'ListSecurityHealthAnalyticsCustomModulesResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'SetFindingStateRequest', - 'SetMuteRequest', - 'RunAssetDiscoveryRequest', - 'SimulateSecurityHealthAnalyticsCustomModuleRequest', - 'SimulateSecurityHealthAnalyticsCustomModuleResponse', - 'UpdateExternalSystemRequest', - 'UpdateFindingRequest', - 'UpdateMuteConfigRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityHealthAnalyticsCustomModuleRequest', - 'UpdateSourceRequest', - 'UpdateSecurityMarksRequest', - 'CreateBigQueryExportRequest', - 'UpdateBigQueryExportRequest', - 'ListBigQueryExportsRequest', - 'ListBigQueryExportsResponse', - 'DeleteBigQueryExportRequest', - 'CreateEventThreatDetectionCustomModuleRequest', - 'ValidateEventThreatDetectionCustomModuleRequest', - 'ValidateEventThreatDetectionCustomModuleResponse', - 'DeleteEventThreatDetectionCustomModuleRequest', - 'GetEventThreatDetectionCustomModuleRequest', - 'ListDescendantEventThreatDetectionCustomModulesRequest', - 'ListDescendantEventThreatDetectionCustomModulesResponse', - 'ListEventThreatDetectionCustomModulesRequest', - 'ListEventThreatDetectionCustomModulesResponse', - 'UpdateEventThreatDetectionCustomModuleRequest', - 'GetEffectiveEventThreatDetectionCustomModuleRequest', - 'ListEffectiveEventThreatDetectionCustomModulesRequest', - 'ListEffectiveEventThreatDetectionCustomModulesResponse', - }, -) - - -class BulkMuteFindingsRequest(proto.Message): - r"""Request message for bulk findings update. - - Note: - - 1. If multiple bulk update requests match the same resource, the - order in which they get executed is not defined. - 2. Once a bulk operation is started, there is no way to stop it. - - Attributes: - parent (str): - Required. The parent, at which bulk action needs to be - applied. Its format is ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - filter (str): - Expression that identifies findings that should be updated. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - mute_annotation (str): - This can be a mute configuration name or any - identifier for mute/unmute of findings based on - the filter. - mute_state (google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest.MuteState): - Optional. All findings matching the given filter will have - their mute state set to this value. The default value is - ``MUTED``. Setting this to ``UNDEFINED`` will clear the mute - state on all matching findings. - """ - class MuteState(proto.Enum): - r"""The mute state. - - Values: - MUTE_STATE_UNSPECIFIED (0): - Unused. - MUTED (1): - Matching findings will be muted (default). - UNDEFINED (2): - Matching findings will have their mute state - cleared. - """ - MUTE_STATE_UNSPECIFIED = 0 - MUTED = 1 - UNDEFINED = 2 - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - mute_annotation: str = proto.Field( - proto.STRING, - number=3, - ) - mute_state: MuteState = proto.Field( - proto.ENUM, - number=4, - enum=MuteState, - ) - - -class BulkMuteFindingsResponse(proto.Message): - r"""The response to a BulkMute request. Contains the LRO - information. - - """ - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - - Attributes: - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - ``organizations/[organization_id]/sources/[source_id]``. - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - alphanumeric and less than or equal to 32 - characters and greater than 0 characters in - length. - finding (google.cloud.securitycenter_v1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - finding_id: str = proto.Field( - proto.STRING, - number=2, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_finding.Finding, - ) - - -class CreateMuteConfigRequest(proto.Message): - r"""Request message for creating a mute config. - - Attributes: - parent (str): - Required. Resource name of the new mute configs's parent. - Its format is ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - mute_config (google.cloud.securitycenter_v1.types.MuteConfig): - Required. The mute config being created. - mute_config_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must consist - of only lowercase letters, numbers, and hyphens, - must start with a letter, must end with either a - letter or a number, and must be 63 characters or - less. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - mute_config: gcs_mute_config.MuteConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_mute_config.MuteConfig, - ) - mute_config_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class CreateResourceValueConfigRequest(proto.Message): - r"""Request message to create single resource value config - - Attributes: - parent (str): - Required. Resource name of the new - ResourceValueConfig's parent. - resource_value_config (google.cloud.securitycenter_v1.types.ResourceValueConfig): - Required. The resource value config being - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_resource_value_config.ResourceValueConfig, - ) - - -class BatchCreateResourceValueConfigsRequest(proto.Message): - r"""Request message to create multiple resource value configs - - Attributes: - parent (str): - Required. Resource name of the new - ResourceValueConfig's parent. The parent field - in the CreateResourceValueConfigRequest messages - must either be empty or match this field. - requests (MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]): - Required. The resource value configs to be - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - requests: MutableSequence['CreateResourceValueConfigRequest'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='CreateResourceValueConfigRequest', - ) - - -class BatchCreateResourceValueConfigsResponse(proto.Message): - r"""Response message for BatchCreateResourceValueConfigs - - Attributes: - resource_value_configs (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfig]): - The resource value configs created - """ - - resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_resource_value_config.ResourceValueConfig, - ) - - -class DeleteResourceValueConfigRequest(proto.Message): - r"""Request message to delete resource value config - - Attributes: - name (str): - Required. Name of the ResourceValueConfig to - delete - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetResourceValueConfigRequest(proto.Message): - r"""Request message to get resource value config - - Attributes: - name (str): - Required. Name of the resource value config to retrieve. Its - format is - ``organizations/{organization}/resourceValueConfigs/{config_id}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListResourceValueConfigsRequest(proto.Message): - r"""Request message to list resource value configs of a parent - - Attributes: - parent (str): - Required. The parent, which owns the collection of resource - value configs. Its format is - ``organizations/[organization_id]`` - page_size (int): - The number of results to return. The service - may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - A page token, received from a previous - ``ListResourceValueConfigs`` call. Provide this to retrieve - the subsequent page. - - When paginating, all other parameters provided to - ``ListResourceValueConfigs`` must match the call that - provided the page token. - - page_size can be specified, and the new page_size 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, - ) - - -class ListResourceValueConfigsResponse(proto.Message): - r"""Response message to list resource value configs - - Attributes: - resource_value_configs (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfig]): - The resource value configs from the specified - parent. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is empty, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_resource_value_config.ResourceValueConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateResourceValueConfigRequest(proto.Message): - r"""Request message to update resource value config - - Attributes: - resource_value_config (google.cloud.securitycenter_v1.types.ResourceValueConfig): - Required. The resource value config being - updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - If empty all mutable fields will be updated. - """ - - resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_resource_value_config.ResourceValueConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class CreateNotificationConfigRequest(proto.Message): - r"""Request message for creating a notification config. - - Attributes: - parent (str): - Required. Resource name of the new notification config's - parent. Its format is ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - config_id (str): - Required. - Unique identifier provided by the client within - the parent scope. It must be between 1 and 128 - characters and contain alphanumeric characters, - underscores, or hyphens only. - notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): - Required. The notification config being - created. The name and the service account will - be ignored as they are both output only fields - on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - config_id: str = proto.Field( - proto.STRING, - number=2, - ) - notification_config: gcs_notification_config.NotificationConfig = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_notification_config.NotificationConfig, - ) - - -class CreateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Request message for creating Security Health Analytics custom - modules. - - Attributes: - parent (str): - Required. Resource name of the new custom module's parent. - Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): - Required. SecurityHealthAnalytics custom - module to create. The provided name is ignored - and reset with provided parent information and - server-generated ID. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - security_health_analytics_custom_module: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - ) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be ``organizations/[organization_id]``. - source (google.cloud.securitycenter_v1.types.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_source.Source, - ) - - -class DeleteMuteConfigRequest(proto.Message): - r"""Request message for deleting a mute config. - - Attributes: - name (str): - Required. Name of the mute config to delete. Its format is - ``organizations/{organization}/muteConfigs/{config_id}``, - ``folders/{folder}/muteConfigs/{config_id}``, - ``projects/{project}/muteConfigs/{config_id}``, - ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, - ``folders/{folder}/locations/global/muteConfigs/{config_id}``, - or - ``projects/{project}/locations/global/muteConfigs/{config_id}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteNotificationConfigRequest(proto.Message): - r"""Request message for deleting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to delete. Its - format is - ``organizations/[organization_id]/notificationConfigs/[config_id]``, - ``folders/[folder_id]/notificationConfigs/[config_id]``, or - ``projects/[project_id]/notificationConfigs/[config_id]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Request message for deleting Security Health Analytics custom - modules. - - Attributes: - name (str): - Required. Name of the custom module to delete. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetBigQueryExportRequest(proto.Message): - r"""Request message for retrieving a BigQuery export. - - Attributes: - name (str): - Required. Name of the BigQuery export to retrieve. Its - format is - ``organizations/{organization}/bigQueryExports/{export_id}``, - ``folders/{folder}/bigQueryExports/{export_id}``, or - ``projects/{project}/bigQueryExports/{export_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetMuteConfigRequest(proto.Message): - r"""Request message for retrieving a mute config. - - Attributes: - name (str): - Required. Name of the mute config to retrieve. Its format is - ``organizations/{organization}/muteConfigs/{config_id}``, - ``folders/{folder}/muteConfigs/{config_id}``, - ``projects/{project}/muteConfigs/{config_id}``, - ``organizations/{organization}/locations/global/muteConfigs/{config_id}``, - ``folders/{folder}/locations/global/muteConfigs/{config_id}``, - or - ``projects/{project}/locations/global/muteConfigs/{config_id}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetNotificationConfigRequest(proto.Message): - r"""Request message for getting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to get. Its format - is - ``organizations/[organization_id]/notificationConfigs/[config_id]``, - ``folders/[folder_id]/notificationConfigs/[config_id]``, or - ``projects/[project_id]/notificationConfigs/[config_id]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetOrganizationSettingsRequest(proto.Message): - r"""Request message for getting organization settings. - - Attributes: - name (str): - Required. Name of the organization to get organization - settings for. Its format is - ``organizations/[organization_id]/organizationSettings``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Request message for getting effective Security Health - Analytics custom modules. - - Attributes: - name (str): - Required. Name of the effective custom module to get. Its - format is - ``organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/effectiveCustomModules/{customModule}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Request message for getting Security Health Analytics custom - modules. - - Attributes: - name (str): - Required. Name of the custom module to get. Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings/customModules/{customModule}``, - ``folders/{folder}/securityHealthAnalyticsSettings/customModules/{customModule}``, - or - ``projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is ``organizations/[organization_id]/source/[source_id]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GroupAssetsRequest(proto.Message): - r"""Request message for grouping by assets. - - Attributes: - parent (str): - Required. The name of the parent to group the assets by. Its - format is ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, - ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is - not set: - - - security_center_properties.resource_project - - security_center_properties.resource_project_display_name - - security_center_properties.resource_type - - security_center_properties.resource_parent - - security_center_properties.resource_parent_display_name - - The following fields are supported when compare_duration is - set: - - - security_center_properties.resource_type - - security_center_properties.resource_project_display_name - - security_center_properties.resource_parent_display_name - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the GroupResult's - "state_change" property is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at - reference_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and reference_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupAssetsResponse``; - indicates that this is a continuation of a prior - ``GroupAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - page_size: int = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupAssetsResponse(proto.Message): - r"""Response message for grouping by assets. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - - Attributes: - parent (str): - Required. Name of the source to groupBy. Its format is - ``organizations/[organization_id]/sources/[source_id]``, - ``folders/[folder_id]/sources/[source_id]``, or - ``projects/[project_id]/sources/[source_id]``. To groupBy - across all sources provide a source_id of ``-``. For - example: - ``organizations/{organization_id}/sources/-, folders/{folder_id}/sources/-``, - or ``projects/{project_id}/sources/-`` - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - severity: ``=``, ``:`` - - - workflow_state: ``=``, ``:`` - - - security_marks.marks: ``=``, ``:`` - - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based - on a property existing: - ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - - - resource: - - - resource.name: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping (including ``state_change``). The string value - should follow SQL syntax: comma separated list of fields. - For example: "parent,resource_name". - - The following fields are supported when compare_duration is - set: - - - state_change - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the GroupResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - page_size: int = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message=struct_pb2.Value, - ) - count: int = proto.Field( - proto.INT64, - number=2, - ) - - -class ListDescendantSecurityHealthAnalyticsCustomModulesRequest(proto.Message): - r"""Request message for listing descendant Security Health - Analytics custom modules. - - Attributes: - parent (str): - Required. Name of parent to list descendant custom modules. - Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - page_token (str): - The value returned by the last call - indicating a continuation - """ - - 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 ListDescendantSecurityHealthAnalyticsCustomModulesResponse(proto.Message): - r"""Response message for listing descendant Security Health - Analytics custom modules. - - Attributes: - security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule]): - Custom modules belonging to the requested - parent and its descendants. - next_page_token (str): - If not empty, indicates that there may be - more custom modules to be returned. - """ - - @property - def raw_page(self): - return self - - security_health_analytics_custom_modules: MutableSequence[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListValuedResourcesRequest(proto.Message): - r"""Request message for listing the valued resources for a given - simulation. - - Attributes: - parent (str): - Required. Name of parent to list valued resources. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - filter (str): - The filter expression that filters the valued resources in - the response. Supported fields: - - - ``resource_value`` supports = - - ``resource_type`` supports = - page_token (str): - The value returned by the last - ``ListValuedResourcesResponse``; indicates that this is a - continuation of a prior ``ListValuedResources`` call, and - that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - order_by (str): - Optional. The fields by which to order the valued resources - response. - - Supported fields: - - - ``exposed_score`` - - - ``resource_value`` - - - ``resource_type`` - - - ``resource`` - - - ``display_name`` - - Values should be a comma separated list of fields. For - example: ``exposed_score,resource_value``. - - The default sorting order is descending. To specify - ascending or descending order for a field, append a ``ASC`` - or a ``DESC`` suffix, respectively; for example: - ``exposed_score DESC``. - """ - - 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, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListValuedResourcesResponse(proto.Message): - r"""Response message for listing the valued resources for a given - simulation. - - Attributes: - valued_resources (MutableSequence[google.cloud.securitycenter_v1.types.ValuedResource]): - The valued resources that the attack path - simulation identified. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The estimated total number of results - matching the query. - """ - - @property - def raw_page(self): - return self - - valued_resources: MutableSequence[valued_resource.ValuedResource] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=valued_resource.ValuedResource, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class ListAttackPathsRequest(proto.Message): - r"""Request message for listing the attack paths for a given - simulation or valued resource. - - Attributes: - parent (str): - Required. Name of parent to list attack paths. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - filter (str): - The filter expression that filters the attack path in the - response. Supported fields: - - - ``valued_resources`` supports = - page_token (str): - The value returned by the last ``ListAttackPathsResponse``; - indicates that this is a continuation of a prior - ``ListAttackPaths`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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 ListAttackPathsResponse(proto.Message): - r"""Response message for listing the attack paths for a given - simulation or valued resource. - - Attributes: - attack_paths (MutableSequence[google.cloud.securitycenter_v1.types.AttackPath]): - The attack paths that the attack path - simulation identified. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - attack_paths: MutableSequence[attack_path.AttackPath] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=attack_path.AttackPath, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetSimulationRequest(proto.Message): - r"""Request message for getting simulation. - Simulation name can include "latest" to retrieve the latest - simulation For example, "organizations/123/simulations/latest" - - Attributes: - name (str): - Required. The organization name or simulation name of this - simulation - - Valid format: - ``organizations/{organization}/simulations/latest`` - ``organizations/{organization}/simulations/{simulation}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetValuedResourceRequest(proto.Message): - r"""Request message for getting a valued resource. - - Attributes: - name (str): - Required. The name of this valued resource - - Valid format: - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListMuteConfigsRequest(proto.Message): - r"""Request message for listing mute configs at a given scope - e.g. organization, folder or project. - - Attributes: - parent (str): - Required. The parent, which owns the collection of mute - configs. Its format is ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - page_size (int): - The maximum number of configs to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - A page token, received from a previous ``ListMuteConfigs`` - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListMuteConfigs`` 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 ListMuteConfigsResponse(proto.Message): - r"""Response message for listing mute configs. - - Attributes: - mute_configs (MutableSequence[google.cloud.securitycenter_v1.types.MuteConfig]): - The mute configs from the specified parent. - 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 - - mute_configs: MutableSequence[gcs_mute_config.MuteConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_mute_config.MuteConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListNotificationConfigsRequest(proto.Message): - r"""Request message for listing notification configs. - - Attributes: - parent (str): - Required. The name of the parent in which to list the - notification configurations. Its format is - "organizations/[organization_id]", "folders/[folder_id]", or - "projects/[project_id]". - page_token (str): - The value returned by the last - ``ListNotificationConfigsResponse``; indicates that this is - a continuation of a prior ``ListNotificationConfigs`` call, - and that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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 ListNotificationConfigsResponse(proto.Message): - r"""Response message for listing notification configs. - - Attributes: - notification_configs (MutableSequence[google.cloud.securitycenter_v1.types.NotificationConfig]): - Notification configs belonging to the - requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - notification_configs: MutableSequence[gcs_notification_config.NotificationConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(proto.Message): - r"""Request message for listing effective Security Health - Analytics custom modules. - - Attributes: - parent (str): - Required. Name of parent to list effective custom modules. - Its format is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - page_token (str): - The value returned by the last call - indicating a continuation - """ - - 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 ListEffectiveSecurityHealthAnalyticsCustomModulesResponse(proto.Message): - r"""Response message for listing effective Security Health - Analytics custom modules. - - Attributes: - effective_security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule]): - Effective custom modules belonging to the - requested parent. - next_page_token (str): - If not empty, indicates that there may be - more effective custom modules to be returned. - """ - - @property - def raw_page(self): - return self - - effective_security_health_analytics_custom_modules: MutableSequence[effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListSecurityHealthAnalyticsCustomModulesRequest(proto.Message): - r"""Request message for listing Security Health Analytics custom - modules. - - Attributes: - parent (str): - Required. Name of parent to list custom modules. Its format - is - ``organizations/{organization}/securityHealthAnalyticsSettings``, - ``folders/{folder}/securityHealthAnalyticsSettings``, or - ``projects/{project}/securityHealthAnalyticsSettings`` - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - page_token (str): - The value returned by the last call - indicating a continuation - """ - - 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 ListSecurityHealthAnalyticsCustomModulesResponse(proto.Message): - r"""Response message for listing Security Health Analytics custom - modules. - - Attributes: - security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule]): - Custom modules belonging to the requested - parent. - next_page_token (str): - If not empty, indicates that there may be - more custom modules to be returned. - """ - - @property - def raw_page(self): - return self - - security_health_analytics_custom_modules: MutableSequence[gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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=7, - ) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - - Attributes: - sources (MutableSequence[google.cloud.securitycenter_v1.types.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListAssetsRequest(proto.Message): - r"""Request message for listing assets. - - Attributes: - parent (str): - Required. The name of the parent resource that contains the - assets. The value that you can specify on parent depends on - the method in which you specify parent. You can specify one - of the following values: - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following are the allowed field and operator - combinations: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, - ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,resource_properties.a_property". - Redundant space characters in the syntax are insignificant. - "name desc,resource_properties.a_property" and " name desc , - resource_properties.a_property " are equivalent. - - The following fields are supported: name update_time - resource_properties security_marks.marks - security_center_properties.resource_name - security_center_properties.resource_display_name - security_center_properties.resource_parent - security_center_properties.resource_parent_display_name - security_center_properties.resource_project - security_center_properties.resource_project_display_name - security_center_properties.resource_type - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListAssetsResult's - "state_change" attribute is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at read_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at read_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the ListAssetsResult - fields to be listed in the response. - An empty field mask will list all fields. - page_token (str): - The value returned by the last ``ListAssetsResponse``; - indicates that this is a continuation of a prior - ``ListAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=8, - ) - page_size: int = proto.Field( - proto.INT32, - number=9, - ) - - -class ListAssetsResponse(proto.Message): - r"""Response message for listing assets. - - Attributes: - list_assets_results (MutableSequence[google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult]): - Assets matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of assets matching the - query. - """ - - class ListAssetsResult(proto.Message): - r"""Result containing the Asset and its State. - - Attributes: - asset (google.cloud.securitycenter_v1.types.Asset): - Asset matching the search request. - state_change (google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult.StateChange): - State change of the asset between the points - in time. - """ - class StateChange(proto.Enum): - r"""The change in state of the asset. - - When querying across two points in time this describes the change - between the two points: ADDED, REMOVED, or ACTIVE. If there was no - compare_duration supplied in the request the state change will be: - UNUSED - - Values: - UNUSED (0): - State change is unused, this is the canonical - default for this enum. - ADDED (1): - Asset was added between the points in time. - REMOVED (2): - Asset was removed between the points in time. - ACTIVE (3): - Asset was present at both point(s) in time. - """ - UNUSED = 0 - ADDED = 1 - REMOVED = 2 - ACTIVE = 3 - - asset: gcs_asset.Asset = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_asset.Asset, - ) - state_change: 'ListAssetsResponse.ListAssetsResult.StateChange' = proto.Field( - proto.ENUM, - number=2, - enum='ListAssetsResponse.ListAssetsResult.StateChange', - ) - - @property - def raw_page(self): - return self - - list_assets_results: MutableSequence[ListAssetsResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListAssetsResult, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - - Attributes: - parent (str): - Required. Name of the source the findings belong to. Its - format is - ``organizations/[organization_id]/sources/[source_id]``, - ``folders/[folder_id]/sources/[source_id]``, or - ``projects/[project_id]/sources/[source_id]``. To list - across all sources provide a source_id of ``-``. For - example: ``organizations/{organization_id}/sources/-``, - ``folders/{folder_id}/sources/-`` or - ``projects/{projects_id}/sources/-`` - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - severity: ``=``, ``:`` - - - workflow_state: ``=``, ``:`` - - - security_marks.marks: ``=``, ``:`` - - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based - on a property existing: - ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - - - resource: - - - resource.name: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - - resource.folders.resource_folder: ``=``, ``:`` - - resource.display_name: ``=``, ``:`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,source_properties.a_property". Redundant - space characters in the syntax are insignificant. "name - desc,source_properties.a_property" and " name desc , - source_properties.a_property " are equivalent. - - The following fields are supported: name parent state - category resource_name event_time source_properties - security_marks.marks - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListFindingsResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added in any state during - the compare_duration period of time that precedes the - read_time. This is the time between (read_time - - compare_duration) and read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the Finding fields to - be listed in the response. An empty field mask - will list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=8, - ) - page_size: int = proto.Field( - proto.INT32, - number=9, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - - Attributes: - list_findings_results (MutableSequence[google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult]): - Findings matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - class ListFindingsResult(proto.Message): - r"""Result containing the Finding and its StateChange. - - Attributes: - finding (google.cloud.securitycenter_v1.types.Finding): - Finding matching the search request. - state_change (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.StateChange): - State change of the finding between the - points in time. - resource (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.Resource): - Output only. Resource that is associated with - this finding. - """ - class StateChange(proto.Enum): - r"""The change in state of the finding. - - When querying across two points in time this describes the change in - the finding between the two points: CHANGED, UNCHANGED, ADDED, or - REMOVED. Findings can not be deleted, so REMOVED implies that the - finding at timestamp does not match the filter specified, but it did - at timestamp - compare_duration. If there was no compare_duration - supplied in the request the state change will be: UNUSED - - Values: - UNUSED (0): - State change is unused, this is the canonical - default for this enum. - CHANGED (1): - The finding has changed state in some way - between the points in time and existed at both - points. - UNCHANGED (2): - The finding has not changed state between the - points in time and existed at both points. - ADDED (3): - The finding was created between the points in - time. - REMOVED (4): - The finding at timestamp does not match the filter - specified, but it did at timestamp - compare_duration. - """ - UNUSED = 0 - CHANGED = 1 - UNCHANGED = 2 - ADDED = 3 - REMOVED = 4 - - class Resource(proto.Message): - r"""Information related to the Google Cloud resource that is - associated with this finding. - - 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): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - display_name (str): - The human readable name of the resource. - type_ (str): - The full resource type of the resource. - project_name (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The project ID that the resource belongs to. - parent_name (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (MutableSequence[google.cloud.securitycenter_v1.types.Folder]): - Contains a Folder message for each folder in - the assets ancestry. The first folder is the - deepest nested folder, and the last folder is - the folder directly under the Organization. - cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): - Indicates which cloud provider the finding is - from. - organization (str): - Indicates which organization / tenant the - finding is for. - service (str): - The service or resource provider associated - with the resource. - location (str): - The region or location of the service (if - applicable). - aws_metadata (google.cloud.securitycenter_v1.types.AwsMetadata): - The AWS metadata associated with the finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - azure_metadata (google.cloud.securitycenter_v1.types.AzureMetadata): - The Azure metadata associated with the - finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - resource_path (google.cloud.securitycenter_v1.types.ResourcePath): - Provides the path to the resource within the - resource hierarchy. - resource_path_string (str): - A string representation of the resource path. For Google - Cloud, it has the format of - ``org/{organization_id}/folder/{folder_id}/folder/{folder_id}/project/{project_id}`` - where there can be any number of folders. For AWS, it has - the format of - ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` - where there can be any number of organizational units. For - Azure, it has the format of - ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` - where there can be any number of management groups. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=8, - ) - type_: str = proto.Field( - proto.STRING, - number=6, - ) - project_name: str = proto.Field( - proto.STRING, - number=2, - ) - project_display_name: str = proto.Field( - proto.STRING, - number=3, - ) - parent_name: str = proto.Field( - proto.STRING, - number=4, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=5, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=folder.Folder, - ) - cloud_provider: gcs_resource.CloudProvider = proto.Field( - proto.ENUM, - number=9, - enum=gcs_resource.CloudProvider, - ) - organization: str = proto.Field( - proto.STRING, - number=10, - ) - service: str = proto.Field( - proto.STRING, - number=11, - ) - location: str = proto.Field( - proto.STRING, - number=12, - ) - aws_metadata: gcs_resource.AwsMetadata = proto.Field( - proto.MESSAGE, - number=16, - oneof='cloud_provider_metadata', - message=gcs_resource.AwsMetadata, - ) - azure_metadata: gcs_resource.AzureMetadata = proto.Field( - proto.MESSAGE, - number=17, - oneof='cloud_provider_metadata', - message=gcs_resource.AzureMetadata, - ) - resource_path: gcs_resource.ResourcePath = proto.Field( - proto.MESSAGE, - number=18, - message=gcs_resource.ResourcePath, - ) - resource_path_string: str = proto.Field( - proto.STRING, - number=19, - ) - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - state_change: 'ListFindingsResponse.ListFindingsResult.StateChange' = proto.Field( - proto.ENUM, - number=2, - enum='ListFindingsResponse.ListFindingsResult.StateChange', - ) - resource: 'ListFindingsResponse.ListFindingsResult.Resource' = proto.Field( - proto.MESSAGE, - number=3, - message='ListFindingsResponse.ListFindingsResult.Resource', - ) - - @property - def raw_page(self): - return self - - list_findings_results: MutableSequence[ListFindingsResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListFindingsResult, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - - Attributes: - name (str): - Required. The `relative resource - name `__ - of the finding. Example: - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. - state (google.cloud.securitycenter_v1.types.Finding.State): - Required. The desired State of the finding. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the updated state - takes effect. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: gcs_finding.Finding.State = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.State, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class SetMuteRequest(proto.Message): - r"""Request message for updating a finding's mute status. - - Attributes: - name (str): - Required. The `relative resource - name `__ - of the finding. Example: - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. - mute (google.cloud.securitycenter_v1.types.Finding.Mute): - Required. The desired state of the Mute. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - mute: gcs_finding.Finding.Mute = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.Mute, - ) - - -class RunAssetDiscoveryRequest(proto.Message): - r"""Request message for running asset discovery for an - organization. - - Attributes: - parent (str): - Required. Name of the organization to run asset discovery - for. Its format is ``organizations/[organization_id]``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class SimulateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Request message to simulate a CustomConfig against a given - test resource. Maximum size of the request is 4 MB by default. - - Attributes: - parent (str): - Required. The relative resource name of the organization, - project, or folder. For more information about relative - resource names, see `Relative Resource - Name `__ - Example: ``organizations/{organization_id}`` - custom_config (google.cloud.securitycenter_v1.types.CustomConfig): - Required. The custom configuration that you - need to test. - resource (google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource): - Required. Resource data to simulate custom - module against. - """ - - class SimulatedResource(proto.Message): - r"""Manually constructed resource name. If the custom module evaluates - against only the resource data, you can omit the ``iam_policy_data`` - field. If it evaluates only the ``iam_policy_data`` field, you can - omit the resource data. - - Attributes: - resource_type (str): - Required. The type of the resource, for example, - ``compute.googleapis.com/Disk``. - resource_data (google.protobuf.struct_pb2.Struct): - Optional. A representation of the Google - Cloud resource. Should match the Google Cloud - resource JSON format. - iam_policy_data (google.iam.v1.policy_pb2.Policy): - Optional. A representation of the IAM policy. - """ - - resource_type: str = proto.Field( - proto.STRING, - number=1, - ) - resource_data: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - iam_policy_data: policy_pb2.Policy = proto.Field( - proto.MESSAGE, - number=3, - message=policy_pb2.Policy, - ) - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - custom_config: security_health_analytics_custom_config.CustomConfig = proto.Field( - proto.MESSAGE, - number=2, - message=security_health_analytics_custom_config.CustomConfig, - ) - resource: SimulatedResource = proto.Field( - proto.MESSAGE, - number=3, - message=SimulatedResource, - ) - - -class SimulateSecurityHealthAnalyticsCustomModuleResponse(proto.Message): - r"""Response message for simulating a - ``SecurityHealthAnalyticsCustomModule`` against a given resource. - - Attributes: - result (google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse.SimulatedResult): - Result for test case in the corresponding - request. - """ - - class SimulatedResult(proto.Message): - r"""Possible test 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: - finding (google.cloud.securitycenter_v1.types.Finding): - Finding that would be published for the test - case, if a violation is detected. - - This field is a member of `oneof`_ ``result``. - no_violation (google.protobuf.empty_pb2.Empty): - Indicates that the test case does not trigger - any violation. - - This field is a member of `oneof`_ ``result``. - error (google.rpc.status_pb2.Status): - Error encountered during the test. - - This field is a member of `oneof`_ ``result``. - """ - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - oneof='result', - message=gcs_finding.Finding, - ) - no_violation: empty_pb2.Empty = proto.Field( - proto.MESSAGE, - number=2, - oneof='result', - message=empty_pb2.Empty, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - oneof='result', - message=status_pb2.Status, - ) - - result: SimulatedResult = proto.Field( - proto.MESSAGE, - number=1, - message=SimulatedResult, - ) - - -class UpdateExternalSystemRequest(proto.Message): - r"""Request message for updating a ExternalSystem resource. - - Attributes: - external_system (google.cloud.securitycenter_v1.types.ExternalSystem): - Required. The external system resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - external system resource. - If empty all mutable fields will be updated. - """ - - external_system: gcs_external_system.ExternalSystem = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_external_system.ExternalSystem, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - - Attributes: - finding (google.cloud.securitycenter_v1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must be alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing source_properties. - Individual source_properties can be added/updated by using - "source_properties." in the field mask. - """ - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateMuteConfigRequest(proto.Message): - r"""Request message for updating a mute config. - - Attributes: - mute_config (google.cloud.securitycenter_v1.types.MuteConfig): - Required. The mute config being updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - If empty all mutable fields will be updated. - """ - - mute_config: gcs_mute_config.MuteConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_mute_config.MuteConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateNotificationConfigRequest(proto.Message): - r"""Request message for updating a notification config. - - Attributes: - notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): - Required. The notification config to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - notification config. - If empty all mutable fields will be updated. - """ - - notification_config: gcs_notification_config.NotificationConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateOrganizationSettingsRequest(proto.Message): - r"""Request message for updating an organization's settings. - - Attributes: - organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): - Required. The organization settings resource - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - settings resource. - If empty all mutable fields will be updated. - """ - - organization_settings: gcs_organization_settings.OrganizationSettings = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_organization_settings.OrganizationSettings, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Request message for updating Security Health Analytics custom - modules. - - Attributes: - security_health_analytics_custom_module (google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule): - Required. The SecurityHealthAnalytics custom - module to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. The only fields that can - be updated are ``enablement_state`` and ``custom_config``. - If empty or set to the wildcard value ``*``, both - ``enablement_state`` and ``custom_config`` are updated. - """ - - security_health_analytics_custom_module: gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - - Attributes: - source (google.cloud.securitycenter_v1.types.Source): - Required. The source resource to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the source - resource. - If empty all mutable fields will be updated. - """ - - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - - Attributes: - security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): - Required. The security marks resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If empty - or set to "marks", all marks will be replaced. Individual - marks can be updated using "marks.". - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the updated SecurityMarks - take effect. If not set uses current server - time. Updates will be applied to the - SecurityMarks that are active immediately - preceding this time. Must be earlier or equal to - the server time. - """ - - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_security_marks.SecurityMarks, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class CreateBigQueryExportRequest(proto.Message): - r"""Request message for creating a BigQuery export. - - Attributes: - parent (str): - Required. The name of the parent resource of the new - BigQuery export. Its format is - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): - Required. The BigQuery export being created. - big_query_export_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must consist - of only lowercase letters, numbers, and hyphens, - must start with a letter, must end with either a - letter or a number, and must be 63 characters or - less. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - big_query_export: bigquery_export.BigQueryExport = proto.Field( - proto.MESSAGE, - number=2, - message=bigquery_export.BigQueryExport, - ) - big_query_export_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateBigQueryExportRequest(proto.Message): - r"""Request message for updating a BigQuery export. - - Attributes: - big_query_export (google.cloud.securitycenter_v1.types.BigQueryExport): - Required. The BigQuery export being updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - If empty all mutable fields will be updated. - """ - - big_query_export: bigquery_export.BigQueryExport = proto.Field( - proto.MESSAGE, - number=1, - message=bigquery_export.BigQueryExport, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ListBigQueryExportsRequest(proto.Message): - r"""Request message for listing BigQuery exports at a given scope - e.g. organization, folder or project. - - Attributes: - parent (str): - Required. The parent, which owns the collection of BigQuery - exports. Its format is ``organizations/[organization_id]``, - ``folders/[folder_id]``, ``projects/[project_id]``. - page_size (int): - The maximum number of configs to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - A page token, received from a previous - ``ListBigQueryExports`` call. Provide this to retrieve the - subsequent page. When paginating, all other parameters - provided to ``ListBigQueryExports`` 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 ListBigQueryExportsResponse(proto.Message): - r"""Response message for listing BigQuery exports. - - Attributes: - big_query_exports (MutableSequence[google.cloud.securitycenter_v1.types.BigQueryExport]): - The BigQuery exports from the specified - parent. - 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 - - big_query_exports: MutableSequence[bigquery_export.BigQueryExport] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=bigquery_export.BigQueryExport, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteBigQueryExportRequest(proto.Message): - r"""Request message for deleting a BigQuery export. - - Attributes: - name (str): - Required. The name of the BigQuery export to delete. Its - format is - ``organizations/{organization}/bigQueryExports/{export_id}``, - ``folders/{folder}/bigQueryExports/{export_id}``, or - ``projects/{project}/bigQueryExports/{export_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Request to create an Event Threat Detection custom module. - - Attributes: - parent (str): - Required. The new custom module's parent. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): - Required. The module to create. The - event_threat_detection_custom_module.name will be ignored - and server generated. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - event_threat_detection_custom_module: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, - ) - - -class ValidateEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Request to validate an Event Threat Detection custom module. - - Attributes: - parent (str): - Required. Resource name of the parent to validate the Custom - Module under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - raw_text (str): - Required. The raw text of the module's - contents. Used to generate error messages. - type_ (str): - Required. The type of the module (e.g. CONFIGURABLE_BAD_IP). - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - raw_text: str = proto.Field( - proto.STRING, - number=2, - ) - type_: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ValidateEventThreatDetectionCustomModuleResponse(proto.Message): - r"""Response to validating an Event Threat Detection custom - module. - - Attributes: - errors (google.cloud.securitycenter_v1.types.CustomModuleValidationErrors): - A list of errors returned by the validator. - If the list is empty, there were no errors. - """ - - errors: event_threat_detection_custom_module_validation_errors.CustomModuleValidationErrors = proto.Field( - proto.MESSAGE, - number=2, - message=event_threat_detection_custom_module_validation_errors.CustomModuleValidationErrors, - ) - - -class DeleteEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Request to delete an Event Threat Detection custom module. - - Attributes: - name (str): - Required. Name of the custom module to delete. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Request to get an Event Threat Detection custom module. - - Attributes: - name (str): - Required. Name of the custom module to get. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDescendantEventThreatDetectionCustomModulesRequest(proto.Message): - r"""Request to list current and descendant resident Event Threat - Detection custom modules. - - Attributes: - parent (str): - Required. Name of the parent to list custom modules under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - page_token (str): - A page token, received from a previous - ``ListDescendantEventThreatDetectionCustomModules`` call. - Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListDescendantEventThreatDetectionCustomModules`` must - match the call that provided the page token. - page_size (int): - The maximum number of modules to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - """ - - 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 ListDescendantEventThreatDetectionCustomModulesResponse(proto.Message): - r"""Response for listing current and descendant resident - Event Threat Detection custom modules. - - Attributes: - event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule]): - Custom modules belonging to the requested - parent. - 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 - - event_threat_detection_custom_modules: MutableSequence[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListEventThreatDetectionCustomModulesRequest(proto.Message): - r"""Request to list Event Threat Detection custom modules. - - Attributes: - parent (str): - Required. Name of the parent to list custom modules under. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - page_token (str): - A page token, received from a previous - ``ListEventThreatDetectionCustomModules`` call. Provide this - to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListEventThreatDetectionCustomModules`` must match the - call that provided the page token. - page_size (int): - The maximum number of modules to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - """ - - 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 ListEventThreatDetectionCustomModulesResponse(proto.Message): - r"""Response for listing Event Threat Detection custom modules. - - Attributes: - event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule]): - Custom modules belonging to the requested - parent. - 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 - - event_threat_detection_custom_modules: MutableSequence[gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Request to update an Event Threat Detection custom module. - - Attributes: - event_threat_detection_custom_module (google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule): - Required. The module being updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - If empty all mutable fields will be updated. - """ - - event_threat_detection_custom_module: gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetEffectiveEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Request to get an EffectiveEventThreatDetectionCustomModule. - - Attributes: - name (str): - Required. The resource name of the effective Event Threat - Detection custom module. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``folders/{folder}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - - ``projects/{project}/eventThreatDetectionSettings/effectiveCustomModules/{module}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListEffectiveEventThreatDetectionCustomModulesRequest(proto.Message): - r"""Request to list effective Event Threat Detection custom - modules. - - Attributes: - parent (str): - Required. Name of the parent to list custom modules for. - - Its format is: - - - ``organizations/{organization}/eventThreatDetectionSettings``. - - ``folders/{folder}/eventThreatDetectionSettings``. - - ``projects/{project}/eventThreatDetectionSettings``. - page_token (str): - A page token, received from a previous - ``ListEffectiveEventThreatDetectionCustomModules`` call. - Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListEffectiveEventThreatDetectionCustomModules`` must - match the call that provided the page token. - page_size (int): - The maximum number of modules to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - """ - - 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 ListEffectiveEventThreatDetectionCustomModulesResponse(proto.Message): - r"""Response for listing - EffectiveEventThreatDetectionCustomModules. - - Attributes: - effective_event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule]): - Effective custom modules belonging to the - requested parent. - 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 - - effective_event_threat_detection_custom_modules: MutableSequence[effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py deleted file mode 100644 index 941b7452d7e0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/simulation.py +++ /dev/null @@ -1,73 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1.types import resource -from google.cloud.securitycenter_v1.types import valued_resource -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Simulation', - }, -) - - -class Simulation(proto.Message): - r"""Attack path simulation - - Attributes: - name (str): - Full resource name of the Simulation: - ``organizations/123/simulations/456`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time simulation was created - resource_value_configs_metadata (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfigMetadata]): - Resource value configurations' metadata used - in this simulation. Maximum of 100. - cloud_provider (google.cloud.securitycenter_v1.types.CloudProvider): - Indicates which cloud provider was used in - this simulation. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - resource_value_configs_metadata: MutableSequence[valued_resource.ResourceValueConfigMetadata] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=valued_resource.ResourceValueConfigMetadata, - ) - cloud_provider: resource.CloudProvider = proto.Field( - proto.ENUM, - number=4, - enum=resource.CloudProvider, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.py deleted file mode 100644 index e1c53a7c05a9..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/source.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Source', - }, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, and other tools. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and outdated or - insecure libraries.". - canonical_name (str): - The canonical name of the finding source. It's either - "organizations/{organization_id}/sources/{source_id}", - "folders/{folder_id}/sources/{source_id}", or - "projects/{project_number}/sources/{source_id}", depending - on the closest CRM ancestor of the resource associated with - the finding. - """ - - 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, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=14, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.py deleted file mode 100644 index 77f790f8d5f6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/toxic_combination.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'ToxicCombination', - }, -) - - -class ToxicCombination(proto.Message): - r"""Contains details about a group of security issues that, when - the issues occur together, represent a greater risk than when - the issues occur independently. A group of such issues is - referred to as a toxic combination. - - Attributes: - attack_exposure_score (float): - The `Attack exposure - score `__ - of this toxic combination. The score is a measure of how - much this toxic combination exposes one or more high-value - resources to potential attack. - related_findings (MutableSequence[str]): - List of resource names of findings associated with this - toxic combination. For example, - ``organizations/123/sources/456/findings/789``. - """ - - attack_exposure_score: float = proto.Field( - proto.DOUBLE, - number=1, - ) - related_findings: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.py deleted file mode 100644 index 5d48f6fabfa1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/valued_resource.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'ValuedResource', - 'ResourceValueConfigMetadata', - }, -) - - -class ValuedResource(proto.Message): - r"""A resource that is determined to have value to a user's - system - - Attributes: - name (str): - Valued resource name, for example, e.g.: - ``organizations/123/simulations/456/valuedResources/789`` - resource (str): - The `full resource - name `__ - of the valued resource. - resource_type (str): - The `resource - type `__ - of the valued resource. - display_name (str): - Human-readable name of the valued resource. - resource_value (google.cloud.securitycenter_v1.types.ValuedResource.ResourceValue): - How valuable this resource is. - exposed_score (float): - Exposed score for this valued resource. A - value of 0 means no exposure was detected - exposure. - resource_value_configs_used (MutableSequence[google.cloud.securitycenter_v1.types.ResourceValueConfigMetadata]): - List of resource value configurations' - metadata used to determine the value of this - resource. Maximum of 100. - """ - class ResourceValue(proto.Enum): - r"""How valuable the resource is. - - Values: - RESOURCE_VALUE_UNSPECIFIED (0): - The resource value isn't specified. - RESOURCE_VALUE_LOW (1): - This is a low-value resource. - RESOURCE_VALUE_MEDIUM (2): - This is a medium-value resource. - RESOURCE_VALUE_HIGH (3): - This is a high-value resource. - """ - RESOURCE_VALUE_UNSPECIFIED = 0 - RESOURCE_VALUE_LOW = 1 - RESOURCE_VALUE_MEDIUM = 2 - RESOURCE_VALUE_HIGH = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - resource: str = proto.Field( - proto.STRING, - number=2, - ) - resource_type: str = proto.Field( - proto.STRING, - number=3, - ) - display_name: str = proto.Field( - proto.STRING, - number=4, - ) - resource_value: ResourceValue = proto.Field( - proto.ENUM, - number=5, - enum=ResourceValue, - ) - exposed_score: float = proto.Field( - proto.DOUBLE, - number=6, - ) - resource_value_configs_used: MutableSequence['ResourceValueConfigMetadata'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='ResourceValueConfigMetadata', - ) - - -class ResourceValueConfigMetadata(proto.Message): - r"""Metadata about a ResourceValueConfig. For example, id and - name. - - Attributes: - name (str): - Resource value config name - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py b/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.py deleted file mode 100644 index bfe2bd588b69..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/google/cloud/securitycenter_v1/types/vulnerability.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. -# -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.securitycenter.v1', - manifest={ - 'Vulnerability', - 'Cve', - 'Reference', - 'Cvssv3', - 'Package', - 'SecurityBulletin', - }, -) - - -class Vulnerability(proto.Message): - r"""Refers to common vulnerability fields e.g. cve, cvss, cwe - etc. - - Attributes: - cve (google.cloud.securitycenter_v1.types.Cve): - CVE stands for Common Vulnerabilities and - Exposures (https://cve.mitre.org/about/) - offending_package (google.cloud.securitycenter_v1.types.Package): - The offending package is relevant to the - finding. - fixed_package (google.cloud.securitycenter_v1.types.Package): - The fixed package is relevant to the finding. - security_bulletin (google.cloud.securitycenter_v1.types.SecurityBulletin): - The security bulletin is relevant to this - finding. - """ - - cve: 'Cve' = proto.Field( - proto.MESSAGE, - number=1, - message='Cve', - ) - offending_package: 'Package' = proto.Field( - proto.MESSAGE, - number=2, - message='Package', - ) - fixed_package: 'Package' = proto.Field( - proto.MESSAGE, - number=3, - message='Package', - ) - security_bulletin: 'SecurityBulletin' = proto.Field( - proto.MESSAGE, - number=4, - message='SecurityBulletin', - ) - - -class Cve(proto.Message): - r"""CVE stands for Common Vulnerabilities and Exposures. Information - from the `CVE - record `__ that - describes this vulnerability. - - Attributes: - id (str): - The unique identifier for the vulnerability. - e.g. CVE-2021-34527 - references (MutableSequence[google.cloud.securitycenter_v1.types.Reference]): - Additional information about the CVE. - e.g. - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527 - cvssv3 (google.cloud.securitycenter_v1.types.Cvssv3): - Describe Common Vulnerability Scoring System - specified at - https://www.first.org/cvss/v3.1/specification-document - upstream_fix_available (bool): - Whether upstream fix is available for the - CVE. - impact (google.cloud.securitycenter_v1.types.Cve.RiskRating): - The potential impact of the vulnerability if - it was to be exploited. - exploitation_activity (google.cloud.securitycenter_v1.types.Cve.ExploitationActivity): - The exploitation activity of the - vulnerability in the wild. - observed_in_the_wild (bool): - Whether or not the vulnerability has been - observed in the wild. - zero_day (bool): - Whether or not the vulnerability was zero day - when the finding was published. - exploit_release_date (google.protobuf.timestamp_pb2.Timestamp): - Date the first publicly available exploit or - PoC was released. - """ - class RiskRating(proto.Enum): - r"""The possible values of impact of the vulnerability if it was - to be exploited. - - Values: - RISK_RATING_UNSPECIFIED (0): - Invalid or empty value. - LOW (1): - Exploitation would have little to no security - impact. - MEDIUM (2): - Exploitation would enable attackers to - perform activities, or could allow attackers to - have a direct impact, but would require - additional steps. - HIGH (3): - Exploitation would enable attackers to have a - notable direct impact without needing to - overcome any major mitigating factors. - CRITICAL (4): - Exploitation would fundamentally undermine - the security of affected systems, enable actors - to perform significant attacks with minimal - effort, with little to no mitigating factors to - overcome. - """ - RISK_RATING_UNSPECIFIED = 0 - LOW = 1 - MEDIUM = 2 - HIGH = 3 - CRITICAL = 4 - - class ExploitationActivity(proto.Enum): - r"""The possible values of exploitation activity of the - vulnerability in the wild. - - Values: - EXPLOITATION_ACTIVITY_UNSPECIFIED (0): - Invalid or empty value. - WIDE (1): - Exploitation has been reported or confirmed - to widely occur. - CONFIRMED (2): - Limited reported or confirmed exploitation - activities. - AVAILABLE (3): - Exploit is publicly available. - ANTICIPATED (4): - No known exploitation activity, but has a - high potential for exploitation. - NO_KNOWN (5): - No known exploitation activity. - """ - EXPLOITATION_ACTIVITY_UNSPECIFIED = 0 - WIDE = 1 - CONFIRMED = 2 - AVAILABLE = 3 - ANTICIPATED = 4 - NO_KNOWN = 5 - - id: str = proto.Field( - proto.STRING, - number=1, - ) - references: MutableSequence['Reference'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Reference', - ) - cvssv3: 'Cvssv3' = proto.Field( - proto.MESSAGE, - number=3, - message='Cvssv3', - ) - upstream_fix_available: bool = proto.Field( - proto.BOOL, - number=4, - ) - impact: RiskRating = proto.Field( - proto.ENUM, - number=5, - enum=RiskRating, - ) - exploitation_activity: ExploitationActivity = proto.Field( - proto.ENUM, - number=6, - enum=ExploitationActivity, - ) - observed_in_the_wild: bool = proto.Field( - proto.BOOL, - number=7, - ) - zero_day: bool = proto.Field( - proto.BOOL, - number=8, - ) - exploit_release_date: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - - -class Reference(proto.Message): - r"""Additional Links - - Attributes: - source (str): - Source of the reference e.g. NVD - uri (str): - Uri for the mentioned source e.g. - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527. - """ - - source: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Cvssv3(proto.Message): - r"""Common Vulnerability Scoring System version 3. - - Attributes: - base_score (float): - The base score is a function of the base - metric scores. - attack_vector (google.cloud.securitycenter_v1.types.Cvssv3.AttackVector): - Base Metrics - Represents the intrinsic characteristics of a - vulnerability that are constant over time and - across user environments. This metric reflects - the context by which vulnerability exploitation - is possible. - attack_complexity (google.cloud.securitycenter_v1.types.Cvssv3.AttackComplexity): - This metric describes the conditions beyond - the attacker's control that must exist in order - to exploit the vulnerability. - privileges_required (google.cloud.securitycenter_v1.types.Cvssv3.PrivilegesRequired): - This metric describes the level of privileges - an attacker must possess before successfully - exploiting the vulnerability. - user_interaction (google.cloud.securitycenter_v1.types.Cvssv3.UserInteraction): - This metric captures the requirement for a - human user, other than the attacker, to - participate in the successful compromise of the - vulnerable component. - scope (google.cloud.securitycenter_v1.types.Cvssv3.Scope): - The Scope metric captures whether a - vulnerability in one vulnerable component - impacts resources in components beyond its - security scope. - confidentiality_impact (google.cloud.securitycenter_v1.types.Cvssv3.Impact): - This metric measures the impact to the - confidentiality of the information resources - managed by a software component due to a - successfully exploited vulnerability. - integrity_impact (google.cloud.securitycenter_v1.types.Cvssv3.Impact): - This metric measures the impact to integrity - of a successfully exploited vulnerability. - availability_impact (google.cloud.securitycenter_v1.types.Cvssv3.Impact): - This metric measures the impact to the - availability of the impacted component resulting - from a successfully exploited vulnerability. - """ - class AttackVector(proto.Enum): - r"""This metric reflects the context by which vulnerability - exploitation is possible. - - Values: - ATTACK_VECTOR_UNSPECIFIED (0): - Invalid value. - ATTACK_VECTOR_NETWORK (1): - The vulnerable component is bound to the - network stack and the set of possible attackers - extends beyond the other options listed below, - up to and including the entire Internet. - ATTACK_VECTOR_ADJACENT (2): - The vulnerable component is bound to the - network stack, but the attack is limited at the - protocol level to a logically adjacent topology. - ATTACK_VECTOR_LOCAL (3): - The vulnerable component is not bound to the - network stack and the attacker's path is via - read/write/execute capabilities. - ATTACK_VECTOR_PHYSICAL (4): - The attack requires the attacker to - physically touch or manipulate the vulnerable - component. - """ - ATTACK_VECTOR_UNSPECIFIED = 0 - ATTACK_VECTOR_NETWORK = 1 - ATTACK_VECTOR_ADJACENT = 2 - ATTACK_VECTOR_LOCAL = 3 - ATTACK_VECTOR_PHYSICAL = 4 - - class AttackComplexity(proto.Enum): - r"""This metric describes the conditions beyond the attacker's - control that must exist in order to exploit the vulnerability. - - Values: - ATTACK_COMPLEXITY_UNSPECIFIED (0): - Invalid value. - ATTACK_COMPLEXITY_LOW (1): - Specialized access conditions or extenuating - circumstances do not exist. An attacker can - expect repeatable success when attacking the - vulnerable component. - ATTACK_COMPLEXITY_HIGH (2): - A successful attack depends on conditions - beyond the attacker's control. That is, a - successful attack cannot be accomplished at - will, but requires the attacker to invest in - some measurable amount of effort in preparation - or execution against the vulnerable component - before a successful attack can be expected. - """ - ATTACK_COMPLEXITY_UNSPECIFIED = 0 - ATTACK_COMPLEXITY_LOW = 1 - ATTACK_COMPLEXITY_HIGH = 2 - - class PrivilegesRequired(proto.Enum): - r"""This metric describes the level of privileges an attacker - must possess before successfully exploiting the vulnerability. - - Values: - PRIVILEGES_REQUIRED_UNSPECIFIED (0): - Invalid value. - PRIVILEGES_REQUIRED_NONE (1): - The attacker is unauthorized prior to attack, - and therefore does not require any access to - settings or files of the vulnerable system to - carry out an attack. - PRIVILEGES_REQUIRED_LOW (2): - The attacker requires privileges that provide - basic user capabilities that could normally - affect only settings and files owned by a user. - Alternatively, an attacker with Low privileges - has the ability to access only non-sensitive - resources. - PRIVILEGES_REQUIRED_HIGH (3): - The attacker requires privileges that provide - significant (e.g., administrative) control over - the vulnerable component allowing access to - component-wide settings and files. - """ - PRIVILEGES_REQUIRED_UNSPECIFIED = 0 - PRIVILEGES_REQUIRED_NONE = 1 - PRIVILEGES_REQUIRED_LOW = 2 - PRIVILEGES_REQUIRED_HIGH = 3 - - class UserInteraction(proto.Enum): - r"""This metric captures the requirement for a human user, other - than the attacker, to participate in the successful compromise - of the vulnerable component. - - Values: - USER_INTERACTION_UNSPECIFIED (0): - Invalid value. - USER_INTERACTION_NONE (1): - The vulnerable system can be exploited - without interaction from any user. - USER_INTERACTION_REQUIRED (2): - Successful exploitation of this vulnerability - requires a user to take some action before the - vulnerability can be exploited. - """ - USER_INTERACTION_UNSPECIFIED = 0 - USER_INTERACTION_NONE = 1 - USER_INTERACTION_REQUIRED = 2 - - class Scope(proto.Enum): - r"""The Scope metric captures whether a vulnerability in one - vulnerable component impacts resources in components beyond its - security scope. - - Values: - SCOPE_UNSPECIFIED (0): - Invalid value. - SCOPE_UNCHANGED (1): - An exploited vulnerability can only affect - resources managed by the same security - authority. - SCOPE_CHANGED (2): - An exploited vulnerability can affect - resources beyond the security scope managed by - the security authority of the vulnerable - component. - """ - SCOPE_UNSPECIFIED = 0 - SCOPE_UNCHANGED = 1 - SCOPE_CHANGED = 2 - - class Impact(proto.Enum): - r"""The Impact metrics capture the effects of a successfully - exploited vulnerability on the component that suffers the worst - outcome that is most directly and predictably associated with - the attack. - - Values: - IMPACT_UNSPECIFIED (0): - Invalid value. - IMPACT_HIGH (1): - High impact. - IMPACT_LOW (2): - Low impact. - IMPACT_NONE (3): - No impact. - """ - IMPACT_UNSPECIFIED = 0 - IMPACT_HIGH = 1 - IMPACT_LOW = 2 - IMPACT_NONE = 3 - - base_score: float = proto.Field( - proto.DOUBLE, - number=1, - ) - attack_vector: AttackVector = proto.Field( - proto.ENUM, - number=5, - enum=AttackVector, - ) - attack_complexity: AttackComplexity = proto.Field( - proto.ENUM, - number=6, - enum=AttackComplexity, - ) - privileges_required: PrivilegesRequired = proto.Field( - proto.ENUM, - number=7, - enum=PrivilegesRequired, - ) - user_interaction: UserInteraction = proto.Field( - proto.ENUM, - number=8, - enum=UserInteraction, - ) - scope: Scope = proto.Field( - proto.ENUM, - number=9, - enum=Scope, - ) - confidentiality_impact: Impact = proto.Field( - proto.ENUM, - number=10, - enum=Impact, - ) - integrity_impact: Impact = proto.Field( - proto.ENUM, - number=11, - enum=Impact, - ) - availability_impact: Impact = proto.Field( - proto.ENUM, - number=12, - enum=Impact, - ) - - -class Package(proto.Message): - r"""Package is a generic definition of a package. - - Attributes: - package_name (str): - The name of the package where the - vulnerability was detected. - cpe_uri (str): - The CPE URI where the vulnerability was - detected. - package_type (str): - Type of package, for example, os, maven, or - go. - package_version (str): - The version of the package. - """ - - package_name: str = proto.Field( - proto.STRING, - number=1, - ) - cpe_uri: str = proto.Field( - proto.STRING, - number=2, - ) - package_type: str = proto.Field( - proto.STRING, - number=3, - ) - package_version: str = proto.Field( - proto.STRING, - number=4, - ) - - -class SecurityBulletin(proto.Message): - r"""SecurityBulletin are notifications of vulnerabilities of - Google products. - - Attributes: - bulletin_id (str): - ID of the bulletin corresponding to the - vulnerability. - submission_time (google.protobuf.timestamp_pb2.Timestamp): - Submission time of this Security Bulletin. - suggested_upgrade_version (str): - This represents a version that the cluster - receiving this notification should be upgraded - to, based on its current version. For example, - 1.15.0 - """ - - bulletin_id: str = proto.Field( - proto.STRING, - number=1, - ) - submission_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - suggested_upgrade_version: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v1/noxfile.py deleted file mode 100644 index c30f405f3ad8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-securitycenter' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -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"): - 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/securitycenter_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"): - 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", - "grpcio", - "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/securitycenter_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( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): - # Ignore release of mypy 1.11.0 which may have a regression - 'mypy!=1.11.0', - '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-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py deleted file mode 100644 index e404756019e2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - requests = securitycenter_v1.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - requests.resource_value_config.resource_value = "NONE" - requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py deleted file mode 100644 index 3723f44be2cb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - requests = securitycenter_v1.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - requests.resource_value_config.resource_value = "NONE" - requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_async.py deleted file mode 100644 index c0d550405cbd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_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 BulkMuteFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py deleted file mode 100644 index 39611042828f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_bulk_mute_findings_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 BulkMuteFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_async.py deleted file mode 100644 index 6f27ee2174b6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_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 CreateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = await client.create_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_sync.py deleted file mode 100644 index 48ddbf103dea..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_big_query_export_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 CreateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = client.create_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py deleted file mode 100644 index 196255a15a29..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_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 CreateEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py deleted file mode 100644 index 2544f1d14706..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_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 CreateEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_async.py deleted file mode 100644 index 84c10d4bf3f8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_sync.py deleted file mode 100644 index 3c594dcc28cb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_async.py deleted file mode 100644 index aa47e9565150..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_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 CreateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = await client.create_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_config_sync.py deleted file mode 100644 index aa64e4c92f71..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_mute_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 CreateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = client.create_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_async.py deleted file mode 100644 index c1e37d27979b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_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 CreateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.create_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_sync.py deleted file mode 100644 index f313379f2bda..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_notification_config_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 CreateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = client.create_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py deleted file mode 100644 index 20431387d14e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_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 CreateSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py deleted file mode 100644 index cc70b8c77485..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_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 CreateSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_async.py deleted file mode 100644 index 5a9938f4f606..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_create_source(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_source_sync.py deleted file mode 100644 index d79924fc941f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_CreateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_create_source(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_async.py deleted file mode 100644 index 990cd91d3f2f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - await client.delete_big_query_export(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_sync.py deleted file mode 100644 index 7b8a0710a6b6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - client.delete_big_query_export(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py deleted file mode 100644 index 6fd5fad55d83..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_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 DeleteEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_delete_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - await client.delete_event_threat_detection_custom_module(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py deleted file mode 100644 index 4126fb7da0d3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_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 DeleteEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_delete_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - client.delete_event_threat_detection_custom_module(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_async.py deleted file mode 100644 index c4f1c8484a6e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_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 DeleteMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_delete_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_mute_config(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_config_sync.py deleted file mode 100644 index 04a1241d4610..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_mute_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 DeleteMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_delete_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_mute_config(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_async.py deleted file mode 100644 index a2ea5ed9a93d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_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 DeleteNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_config(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_config_sync.py deleted file mode 100644 index bb408a4637e4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_notification_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 DeleteNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_config(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_async.py deleted file mode 100644 index 42d63c083d6a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_resource_value_config(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py deleted file mode 100644 index a84b69405090..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_resource_value_config(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py deleted file mode 100644 index 9e2c550b018b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_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 DeleteSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_delete_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - await client.delete_security_health_analytics_custom_module(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py deleted file mode 100644 index 44d1b7765a20..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_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 DeleteSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_delete_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.DeleteSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - client.delete_security_health_analytics_custom_module(request=request) - - -# [END securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_async.py deleted file mode 100644 index 2d3a4e11966a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_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 GetBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = await client.get_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_sync.py deleted file mode 100644 index f3754570b866..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_big_query_export_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 GetBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = client.get_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py deleted file mode 100644 index fe81fc63fb30..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_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 GetEffectiveEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_effective_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_effective_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py deleted file mode 100644 index 1d4d49fff5bd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_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 GetEffectiveEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_effective_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_effective_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py deleted file mode 100644 index fe87fa09b31f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_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 GetEffectiveSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_effective_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_effective_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py deleted file mode 100644 index bfa2f6f00642..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_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 GetEffectiveSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_effective_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_effective_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py deleted file mode 100644 index 62c809c57f6f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_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 GetEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py deleted file mode 100644 index cbde7132fb16..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_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 GetEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetEventThreatDetectionCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_async.py deleted file mode 100644 index 3884cd78982e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_sync.py deleted file mode 100644 index 04461d2bd874..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_async.py deleted file mode 100644 index cd5077ce53bb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_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 GetMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_config_sync.py deleted file mode 100644 index 0794d6d0a981..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_mute_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 GetMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_async.py deleted file mode 100644 index 4ca94a312da4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_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 GetNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_config_sync.py deleted file mode 100644 index a9fdde5359f3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_notification_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 GetNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_async.py deleted file mode 100644 index 5cf5ce3a26d2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_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 GetOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_settings_sync.py deleted file mode 100644 index fb45a62aeafa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_organization_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 GetOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_async.py deleted file mode 100644 index 30fb9d9c366b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_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 GetResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_config_sync.py deleted file mode 100644 index 0b453f060803..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_resource_value_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 GetResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py deleted file mode 100644 index 4f3caf3a11bd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_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 GetSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py deleted file mode 100644 index 55bae4951d45..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_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 GetSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSecurityHealthAnalyticsCustomModuleRequest( - name="name_value", - ) - - # Make the request - response = client.get_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_async.py deleted file mode 100644 index 1b99150b7442..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_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 GetSimulation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetSimulation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_simulation(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_simulation(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetSimulation_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_sync.py deleted file mode 100644 index 083acba19009..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_simulation_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 GetSimulation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetSimulation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_simulation(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = client.get_simulation(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetSimulation_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_async.py deleted file mode 100644 index 3b09eb27dfef..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_source(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_source_sync.py deleted file mode 100644 index ae5d605951c4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_source(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_async.py deleted file mode 100644 index ba715be17d9c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_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 GetValuedResource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetValuedResource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_get_valued_resource(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_valued_resource(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetValuedResource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_sync.py deleted file mode 100644 index b3aa5036453d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_get_valued_resource_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 GetValuedResource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GetValuedResource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_get_valued_resource(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_valued_resource(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GetValuedResource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_async.py deleted file mode 100644 index 972ab2a30dc1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_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 GroupAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GroupAssets_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_group_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GroupAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_sync.py deleted file mode 100644 index 85fa08c63683..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_assets_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 GroupAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GroupAssets_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_group_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GroupAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_async.py deleted file mode 100644 index 8277a2723cc7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GroupFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_group_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_findings_sync.py deleted file mode 100644 index 501397bb2a26..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_GroupFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_group_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_async.py deleted file mode 100644 index d7eb57f6976c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_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 ListAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListAssets_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_sync.py deleted file mode 100644 index 129d168899aa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_assets_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 ListAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListAssets_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_assets(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_async.py deleted file mode 100644 index 1fd2c65f76c6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_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 ListAttackPaths -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListAttackPaths_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_attack_paths(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListAttackPaths_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_sync.py deleted file mode 100644 index ceea93417e1d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_attack_paths_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 ListAttackPaths -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListAttackPaths_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_attack_paths(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListAttackPaths_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_async.py deleted file mode 100644 index 438df71d9c0c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_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 ListBigQueryExports -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_sync.py deleted file mode 100644 index b967f0a3cc2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_big_query_exports_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 ListBigQueryExports -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py deleted file mode 100644 index 7b214a5e3786..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_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 ListDescendantEventThreatDetectionCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_descendant_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py deleted file mode 100644 index 764f1cbe9905..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_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 ListDescendantEventThreatDetectionCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_descendant_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_event_threat_detection_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py deleted file mode 100644 index 4f577cf8f0e1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_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 ListDescendantSecurityHealthAnalyticsCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_descendant_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py deleted file mode 100644 index 44aacf778aaa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_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 ListDescendantSecurityHealthAnalyticsCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_descendant_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_descendant_security_health_analytics_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py deleted file mode 100644 index 40ac4b1fae7f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_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 ListEffectiveEventThreatDetectionCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_effective_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_event_threat_detection_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py deleted file mode 100644 index d339fb184b9f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_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 ListEffectiveEventThreatDetectionCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_effective_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_event_threat_detection_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py deleted file mode 100644 index 2ddb1fdf50a9..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_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 ListEffectiveSecurityHealthAnalyticsCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_effective_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_security_health_analytics_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py deleted file mode 100644 index a6d1e35fe7a4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_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 ListEffectiveSecurityHealthAnalyticsCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_effective_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_effective_security_health_analytics_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py deleted file mode 100644 index 053e3047b38a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_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 ListEventThreatDetectionCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_event_threat_detection_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py deleted file mode 100644 index 8216523320e3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_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 ListEventThreatDetectionCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_event_threat_detection_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListEventThreatDetectionCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_event_threat_detection_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_async.py deleted file mode 100644 index f2fc2cc4e0e4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_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 securitycenter_v1 - - -async def sample_list_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_sync.py deleted file mode 100644 index 574c0709c259..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_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 securitycenter_v1 - - -def sample_list_findings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_async.py deleted file mode 100644 index b4984b693810..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_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 ListMuteConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_mute_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_configs_sync.py deleted file mode 100644 index 451cf050e43b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_mute_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 ListMuteConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_mute_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_async.py deleted file mode 100644 index 9b8132cda94b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_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 ListNotificationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_configs_sync.py deleted file mode 100644 index 27e3721c377d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_notification_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 ListNotificationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_async.py deleted file mode 100644 index 6d2ebd0e1a1e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_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 ListResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py deleted file mode 100644 index a34c9520517f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_resource_value_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 ListResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py deleted file mode 100644 index b6d94d40eb3e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_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 ListSecurityHealthAnalyticsCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_security_health_analytics_custom_modules(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py deleted file mode 100644 index d352446e7eed..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_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 ListSecurityHealthAnalyticsCustomModules -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_security_health_analytics_custom_modules(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSecurityHealthAnalyticsCustomModulesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_security_health_analytics_custom_modules(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_async.py deleted file mode 100644 index 6e653789098a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListSources_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_sources(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_sources_sync.py deleted file mode 100644 index 3d73c443003d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListSources_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_sources(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_async.py deleted file mode 100644 index 09db5a4658e4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_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 ListValuedResources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListValuedResources_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_list_valued_resources(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListValuedResources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_sync.py deleted file mode 100644 index 0c4289dd7f65..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_list_valued_resources_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 ListValuedResources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ListValuedResources_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_list_valued_resources(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ListValuedResources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_async.py deleted file mode 100644 index 3e126713c3e2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_sync.py deleted file mode 100644 index de045eb9e950..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_async.py deleted file mode 100644 index 83c439f5e761..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SetFindingState_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_set_finding_state(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_sync.py deleted file mode 100644 index b6c47c7d5405..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SetFindingState_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_set_finding_state(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_async.py deleted file mode 100644 index d0828598e4ea..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_sync.py deleted file mode 100644 index 9592707e3a59..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_async.py deleted file mode 100644 index 1d2631a20453..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_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 SetMute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SetMute_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_set_mute(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = await client.set_mute(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SetMute_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_sync.py deleted file mode 100644 index 10b240d03f92..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_set_mute_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 SetMute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SetMute_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_set_mute(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = client.set_mute(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SetMute_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py deleted file mode 100644 index 8f323db2f936..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_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 SimulateSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_simulate_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - resource = securitycenter_v1.SimulatedResource() - resource.resource_type = "resource_type_value" - - request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - resource=resource, - ) - - # Make the request - response = await client.simulate_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py deleted file mode 100644 index 81d436d78385..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_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 SimulateSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_simulate_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - resource = securitycenter_v1.SimulatedResource() - resource.resource_type = "resource_type_value" - - request = securitycenter_v1.SimulateSecurityHealthAnalyticsCustomModuleRequest( - parent="parent_value", - resource=resource, - ) - - # Make the request - response = client.simulate_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_async.py deleted file mode 100644 index 479364cbe039..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_sync.py deleted file mode 100644 index d39b8072621c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_async.py deleted file mode 100644 index e07c6c16bb47..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_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 UpdateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateBigQueryExportRequest( - ) - - # Make the request - response = await client.update_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_sync.py deleted file mode 100644 index 0569a012c3bc..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_big_query_export_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 UpdateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_big_query_export(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateBigQueryExportRequest( - ) - - # Make the request - response = client.update_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py deleted file mode 100644 index fd503424dd75..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_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 UpdateEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( - ) - - # Make the request - response = await client.update_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py deleted file mode 100644 index 05ca8e32603f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_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 UpdateEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateEventThreatDetectionCustomModuleRequest( - ) - - # Make the request - response = client.update_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_async.py deleted file mode 100644 index dd917f4ac903..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_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 UpdateExternalSystem -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_external_system(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateExternalSystemRequest( - ) - - # Make the request - response = await client.update_external_system(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_sync.py deleted file mode 100644 index fc184d7026aa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_external_system_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 UpdateExternalSystem -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_external_system(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateExternalSystemRequest( - ) - - # Make the request - response = client.update_external_system(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_async.py deleted file mode 100644 index fb05f8e20bdf..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_finding_sync.py deleted file mode 100644 index 3c4fe5bc7ec5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_finding(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_async.py deleted file mode 100644 index 39d5f038be44..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_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 UpdateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = await client.update_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_sync.py deleted file mode 100644 index 245f3c802a09..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_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 UpdateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_mute_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v1.MuteConfig() - mute_config.filter = "filter_value" - - request = securitycenter_v1.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = client.update_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_async.py deleted file mode 100644 index 6dfffbef6f93..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_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 UpdateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = await client.update_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_config_sync.py deleted file mode 100644 index a8ca94d09985..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_notification_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 UpdateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_notification_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = client.update_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_async.py deleted file mode 100644 index b88b1aa0af5e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = await client.update_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_sync.py deleted file mode 100644 index c897ad8cdba4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = client.update_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_async.py deleted file mode 100644 index 2b7526207b34..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_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 UpdateResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - resource_value_config = securitycenter_v1.ResourceValueConfig() - resource_value_config.resource_value = "NONE" - resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.UpdateResourceValueConfigRequest( - resource_value_config=resource_value_config, - ) - - # Make the request - response = await client.update_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_config_sync.py deleted file mode 100644 index fe7fb7c93f87..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_resource_value_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 UpdateResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - resource_value_config = securitycenter_v1.ResourceValueConfig() - resource_value_config.resource_value = "NONE" - resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] - - request = securitycenter_v1.UpdateResourceValueConfigRequest( - resource_value_config=resource_value_config, - ) - - # Make the request - response = client.update_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py deleted file mode 100644 index 66f5cd744979..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_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 UpdateSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( - ) - - # Make the request - response = await client.update_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py deleted file mode 100644 index ed56eba54e03..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_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 UpdateSecurityHealthAnalyticsCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_security_health_analytics_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityHealthAnalyticsCustomModuleRequest( - ) - - # Make the request - response = client.update_security_health_analytics_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_async.py deleted file mode 100644 index 1b69e29a2d37..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_security_marks(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_sync.py deleted file mode 100644 index b0c6a29d705b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_security_marks(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_async.py deleted file mode 100644 index 659495e1c73f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_update_source(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_sync.py deleted file mode 100644 index 80ac8afaabd7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_UpdateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_update_source(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py deleted file mode 100644 index 38c6309258a8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_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 ValidateEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -async def sample_validate_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - raw_text="raw_text_value", - type_="type__value", - ) - - # Make the request - response = await client.validate_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py deleted file mode 100644 index dbcc6d5f0f5c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_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 ValidateEventThreatDetectionCustomModule -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1 - - -def sample_validate_event_threat_detection_custom_module(): - # Create a client - client = securitycenter_v1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1.ValidateEventThreatDetectionCustomModuleRequest( - parent="parent_value", - raw_text="raw_text_value", - type_="type__value", - ) - - # Make the request - response = client.validate_event_threat_detection_custom_module(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json b/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json deleted file mode 100644 index 176395462f39..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json +++ /dev/null @@ -1,10298 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.securitycenter.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-securitycenter", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.batch_create_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BatchCreateResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BatchCreateResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "requests", - "type": "MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse", - "shortName": "batch_create_resource_value_configs" - }, - "description": "Sample for BatchCreateResourceValueConfigs", - "file": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.batch_create_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BatchCreateResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BatchCreateResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "requests", - "type": "MutableSequence[google.cloud.securitycenter_v1.types.CreateResourceValueConfigRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.BatchCreateResourceValueConfigsResponse", - "shortName": "batch_create_resource_value_configs" - }, - "description": "Sample for BatchCreateResourceValueConfigs", - "file": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v1_generated_security_center_batch_create_resource_value_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.bulk_mute_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BulkMuteFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BulkMuteFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "bulk_mute_findings" - }, - "description": "Sample for BulkMuteFindings", - "file": "securitycenter_v1_generated_security_center_bulk_mute_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v1_generated_security_center_bulk_mute_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.bulk_mute_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.BulkMuteFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BulkMuteFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "bulk_mute_findings" - }, - "description": "Sample for BulkMuteFindings", - "file": "securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v1_generated_security_center_bulk_mute_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v1.types.BigQueryExport" - }, - { - "name": "big_query_export_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.BigQueryExport", - "shortName": "create_big_query_export" - }, - "description": "Sample for CreateBigQueryExport", - "file": "securitycenter_v1_generated_security_center_create_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v1_generated_security_center_create_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateBigQueryExportRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v1.types.BigQueryExport" - }, - { - "name": "big_query_export_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.BigQueryExport", - "shortName": "create_big_query_export" - }, - "description": "Sample for CreateBigQueryExport", - "file": "securitycenter_v1_generated_security_center_create_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v1_generated_security_center_create_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "event_threat_detection_custom_module", - "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule", - "shortName": "create_event_threat_detection_custom_module" - }, - "description": "Sample for CreateEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateEventThreatDetectionCustomModuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "event_threat_detection_custom_module", - "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule", - "shortName": "create_event_threat_detection_custom_module" - }, - "description": "Sample for CreateEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateEventThreatDetectionCustomModule_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_create_event_threat_detection_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v1_generated_security_center_create_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1_generated_security_center_create_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v1_generated_security_center_create_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1_generated_security_center_create_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateMuteConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v1.types.MuteConfig" - }, - { - "name": "mute_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.cloud.securitycenter_v1.types.MuteConfig", - "shortName": "create_mute_config" - }, - "description": "Sample for CreateMuteConfig", - "file": "securitycenter_v1_generated_security_center_create_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v1_generated_security_center_create_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateMuteConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v1.types.MuteConfig" - }, - { - "name": "mute_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.cloud.securitycenter_v1.types.MuteConfig", - "shortName": "create_mute_config" - }, - "description": "Sample for CreateMuteConfig", - "file": "securitycenter_v1_generated_security_center_create_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v1_generated_security_center_create_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "config_id", - "type": "str" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1.types.NotificationConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.NotificationConfig", - "shortName": "create_notification_config" - }, - "description": "Sample for CreateNotificationConfig", - "file": "securitycenter_v1_generated_security_center_create_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1_generated_security_center_create_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "config_id", - "type": "str" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1.types.NotificationConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.NotificationConfig", - "shortName": "create_notification_config" - }, - "description": "Sample for CreateNotificationConfig", - "file": "securitycenter_v1_generated_security_center_create_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1_generated_security_center_create_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "security_health_analytics_custom_module", - "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", - "shortName": "create_security_health_analytics_custom_module" - }, - "description": "Sample for CreateSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "security_health_analytics_custom_module", - "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", - "shortName": "create_security_health_analytics_custom_module" - }, - "description": "Sample for CreateSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSecurityHealthAnalyticsCustomModule_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_create_security_health_analytics_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v1_generated_security_center_create_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_create_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v1_generated_security_center_create_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_CreateSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_create_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest" - }, - { - "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_big_query_export" - }, - "description": "Sample for DeleteBigQueryExport", - "file": "securitycenter_v1_generated_security_center_delete_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v1_generated_security_center_delete_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteBigQueryExportRequest" - }, - { - "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_big_query_export" - }, - "description": "Sample for DeleteBigQueryExport", - "file": "securitycenter_v1_generated_security_center_delete_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v1_generated_security_center_delete_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest" - }, - { - "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_event_threat_detection_custom_module" - }, - "description": "Sample for DeleteEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteEventThreatDetectionCustomModuleRequest" - }, - { - "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_event_threat_detection_custom_module" - }, - "description": "Sample for DeleteEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_delete_event_threat_detection_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest" - }, - { - "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_mute_config" - }, - "description": "Sample for DeleteMuteConfig", - "file": "securitycenter_v1_generated_security_center_delete_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v1_generated_security_center_delete_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteMuteConfigRequest" - }, - { - "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_mute_config" - }, - "description": "Sample for DeleteMuteConfig", - "file": "securitycenter_v1_generated_security_center_delete_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v1_generated_security_center_delete_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest" - }, - { - "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_config" - }, - "description": "Sample for DeleteNotificationConfig", - "file": "securitycenter_v1_generated_security_center_delete_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1_generated_security_center_delete_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest" - }, - { - "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_config" - }, - "description": "Sample for DeleteNotificationConfig", - "file": "securitycenter_v1_generated_security_center_delete_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1_generated_security_center_delete_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest" - }, - { - "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_resource_value_config" - }, - "description": "Sample for DeleteResourceValueConfig", - "file": "securitycenter_v1_generated_security_center_delete_resource_value_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v1_generated_security_center_delete_resource_value_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteResourceValueConfigRequest" - }, - { - "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_resource_value_config" - }, - "description": "Sample for DeleteResourceValueConfig", - "file": "securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v1_generated_security_center_delete_resource_value_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.delete_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "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_security_health_analytics_custom_module" - }, - "description": "Sample for DeleteSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.delete_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.DeleteSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "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_security_health_analytics_custom_module" - }, - "description": "Sample for DeleteSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_DeleteSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_delete_security_health_analytics_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetBigQueryExportRequest" - }, - { - "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.securitycenter_v1.types.BigQueryExport", - "shortName": "get_big_query_export" - }, - "description": "Sample for GetBigQueryExport", - "file": "securitycenter_v1_generated_security_center_get_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetBigQueryExportRequest" - }, - { - "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.securitycenter_v1.types.BigQueryExport", - "shortName": "get_big_query_export" - }, - "description": "Sample for GetBigQueryExport", - "file": "securitycenter_v1_generated_security_center_get_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetBigQueryExport_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_effective_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetEffectiveEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule", - "shortName": "get_effective_event_threat_detection_custom_module" - }, - "description": "Sample for GetEffectiveEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_effective_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetEffectiveEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.EffectiveEventThreatDetectionCustomModule", - "shortName": "get_effective_event_threat_detection_custom_module" - }, - "description": "Sample for GetEffectiveEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveEventThreatDetectionCustomModule_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_effective_event_threat_detection_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_effective_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetEffectiveSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule", - "shortName": "get_effective_security_health_analytics_custom_module" - }, - "description": "Sample for GetEffectiveSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_effective_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEffectiveSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetEffectiveSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.EffectiveSecurityHealthAnalyticsCustomModule", - "shortName": "get_effective_security_health_analytics_custom_module" - }, - "description": "Sample for GetEffectiveSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEffectiveSecurityHealthAnalyticsCustomModule_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_effective_security_health_analytics_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.EventThreatDetectionCustomModule", - "shortName": "get_event_threat_detection_custom_module" - }, - "description": "Sample for GetEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetEventThreatDetectionCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.EventThreatDetectionCustomModule", - "shortName": "get_event_threat_detection_custom_module" - }, - "description": "Sample for GetEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetEventThreatDetectionCustomModule_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_event_threat_detection_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v1_generated_security_center_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v1_generated_security_center_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetMuteConfigRequest" - }, - { - "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.securitycenter_v1.types.MuteConfig", - "shortName": "get_mute_config" - }, - "description": "Sample for GetMuteConfig", - "file": "securitycenter_v1_generated_security_center_get_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetMuteConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetMuteConfigRequest" - }, - { - "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.securitycenter_v1.types.MuteConfig", - "shortName": "get_mute_config" - }, - "description": "Sample for GetMuteConfig", - "file": "securitycenter_v1_generated_security_center_get_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetMuteConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetNotificationConfigRequest" - }, - { - "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.securitycenter_v1.types.NotificationConfig", - "shortName": "get_notification_config" - }, - "description": "Sample for GetNotificationConfig", - "file": "securitycenter_v1_generated_security_center_get_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetNotificationConfigRequest" - }, - { - "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.securitycenter_v1.types.NotificationConfig", - "shortName": "get_notification_config" - }, - "description": "Sample for GetNotificationConfig", - "file": "securitycenter_v1_generated_security_center_get_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetNotificationConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest" - }, - { - "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.securitycenter_v1.types.OrganizationSettings", - "shortName": "get_organization_settings" - }, - "description": "Sample for GetOrganizationSettings", - "file": "securitycenter_v1_generated_security_center_get_organization_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_organization_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest" - }, - { - "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.securitycenter_v1.types.OrganizationSettings", - "shortName": "get_organization_settings" - }, - "description": "Sample for GetOrganizationSettings", - "file": "securitycenter_v1_generated_security_center_get_organization_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetOrganizationSettings_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_organization_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest" - }, - { - "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.securitycenter_v1.types.ResourceValueConfig", - "shortName": "get_resource_value_config" - }, - "description": "Sample for GetResourceValueConfig", - "file": "securitycenter_v1_generated_security_center_get_resource_value_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_resource_value_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetResourceValueConfigRequest" - }, - { - "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.securitycenter_v1.types.ResourceValueConfig", - "shortName": "get_resource_value_config" - }, - "description": "Sample for GetResourceValueConfig", - "file": "securitycenter_v1_generated_security_center_get_resource_value_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetResourceValueConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_resource_value_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", - "shortName": "get_security_health_analytics_custom_module" - }, - "description": "Sample for GetSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", - "shortName": "get_security_health_analytics_custom_module" - }, - "description": "Sample for GetSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSecurityHealthAnalyticsCustomModule_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_security_health_analytics_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_simulation", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSimulation", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSimulation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetSimulationRequest" - }, - { - "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.securitycenter_v1.types.Simulation", - "shortName": "get_simulation" - }, - "description": "Sample for GetSimulation", - "file": "securitycenter_v1_generated_security_center_get_simulation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSimulation_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_simulation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_simulation", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSimulation", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSimulation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetSimulationRequest" - }, - { - "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.securitycenter_v1.types.Simulation", - "shortName": "get_simulation" - }, - "description": "Sample for GetSimulation", - "file": "securitycenter_v1_generated_security_center_get_simulation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSimulation_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_simulation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetSourceRequest" - }, - { - "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.securitycenter_v1.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v1_generated_security_center_get_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetSourceRequest" - }, - { - "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.securitycenter_v1.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v1_generated_security_center_get_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.get_valued_resource", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetValuedResource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetValuedResource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetValuedResourceRequest" - }, - { - "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.securitycenter_v1.types.ValuedResource", - "shortName": "get_valued_resource" - }, - "description": "Sample for GetValuedResource", - "file": "securitycenter_v1_generated_security_center_get_valued_resource_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetValuedResource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_valued_resource_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.get_valued_resource", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GetValuedResource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetValuedResource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GetValuedResourceRequest" - }, - { - "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.securitycenter_v1.types.ValuedResource", - "shortName": "get_valued_resource" - }, - "description": "Sample for GetValuedResource", - "file": "securitycenter_v1_generated_security_center_get_valued_resource_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GetValuedResource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_get_valued_resource_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.group_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GroupAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsAsyncPager", - "shortName": "group_assets" - }, - "description": "Sample for GroupAssets", - "file": "securitycenter_v1_generated_security_center_group_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1_generated_security_center_group_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.group_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GroupAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsPager", - "shortName": "group_assets" - }, - "description": "Sample for GroupAssets", - "file": "securitycenter_v1_generated_security_center_group_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1_generated_security_center_group_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsAsyncPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v1_generated_security_center_group_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1_generated_security_center_group_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v1_generated_security_center_group_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1_generated_security_center_group_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsAsyncPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "securitycenter_v1_generated_security_center_list_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1_generated_security_center_list_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "securitycenter_v1_generated_security_center_list_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1_generated_security_center_list_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_attack_paths", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAttackPaths", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAttackPaths" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListAttackPathsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListAttackPathsAsyncPager", - "shortName": "list_attack_paths" - }, - "description": "Sample for ListAttackPaths", - "file": "securitycenter_v1_generated_security_center_list_attack_paths_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v1_generated_security_center_list_attack_paths_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_attack_paths", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListAttackPaths", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAttackPaths" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListAttackPathsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListAttackPathsPager", - "shortName": "list_attack_paths" - }, - "description": "Sample for ListAttackPaths", - "file": "securitycenter_v1_generated_security_center_list_attack_paths_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v1_generated_security_center_list_attack_paths_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_big_query_exports", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListBigQueryExports", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListBigQueryExports" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsAsyncPager", - "shortName": "list_big_query_exports" - }, - "description": "Sample for ListBigQueryExports", - "file": "securitycenter_v1_generated_security_center_list_big_query_exports_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v1_generated_security_center_list_big_query_exports_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_big_query_exports", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListBigQueryExports", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListBigQueryExports" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListBigQueryExportsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListBigQueryExportsPager", - "shortName": "list_big_query_exports" - }, - "description": "Sample for ListBigQueryExports", - "file": "securitycenter_v1_generated_security_center_list_big_query_exports_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v1_generated_security_center_list_big_query_exports_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_descendant_event_threat_detection_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantEventThreatDetectionCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListDescendantEventThreatDetectionCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager", - "shortName": "list_descendant_event_threat_detection_custom_modules" - }, - "description": "Sample for ListDescendantEventThreatDetectionCustomModules", - "file": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_descendant_event_threat_detection_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantEventThreatDetectionCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListDescendantEventThreatDetectionCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListDescendantEventThreatDetectionCustomModulesPager", - "shortName": "list_descendant_event_threat_detection_custom_modules" - }, - "description": "Sample for ListDescendantEventThreatDetectionCustomModules", - "file": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_event_threat_detection_custom_modules_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_descendant_security_health_analytics_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantSecurityHealthAnalyticsCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListDescendantSecurityHealthAnalyticsCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager", - "shortName": "list_descendant_security_health_analytics_custom_modules" - }, - "description": "Sample for ListDescendantSecurityHealthAnalyticsCustomModules", - "file": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_descendant_security_health_analytics_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListDescendantSecurityHealthAnalyticsCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListDescendantSecurityHealthAnalyticsCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager", - "shortName": "list_descendant_security_health_analytics_custom_modules" - }, - "description": "Sample for ListDescendantSecurityHealthAnalyticsCustomModules", - "file": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListDescendantSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_descendant_security_health_analytics_custom_modules_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_effective_event_threat_detection_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveEventThreatDetectionCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListEffectiveEventThreatDetectionCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesAsyncPager", - "shortName": "list_effective_event_threat_detection_custom_modules" - }, - "description": "Sample for ListEffectiveEventThreatDetectionCustomModules", - "file": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_effective_event_threat_detection_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveEventThreatDetectionCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListEffectiveEventThreatDetectionCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListEffectiveEventThreatDetectionCustomModulesPager", - "shortName": "list_effective_event_threat_detection_custom_modules" - }, - "description": "Sample for ListEffectiveEventThreatDetectionCustomModules", - "file": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_event_threat_detection_custom_modules_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_effective_security_health_analytics_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveSecurityHealthAnalyticsCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListEffectiveSecurityHealthAnalyticsCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager", - "shortName": "list_effective_security_health_analytics_custom_modules" - }, - "description": "Sample for ListEffectiveSecurityHealthAnalyticsCustomModules", - "file": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_effective_security_health_analytics_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEffectiveSecurityHealthAnalyticsCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListEffectiveSecurityHealthAnalyticsCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager", - "shortName": "list_effective_security_health_analytics_custom_modules" - }, - "description": "Sample for ListEffectiveSecurityHealthAnalyticsCustomModules", - "file": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEffectiveSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_effective_security_health_analytics_custom_modules_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_event_threat_detection_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEventThreatDetectionCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListEventThreatDetectionCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesAsyncPager", - "shortName": "list_event_threat_detection_custom_modules" - }, - "description": "Sample for ListEventThreatDetectionCustomModules", - "file": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_event_threat_detection_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListEventThreatDetectionCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListEventThreatDetectionCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListEventThreatDetectionCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListEventThreatDetectionCustomModulesPager", - "shortName": "list_event_threat_detection_custom_modules" - }, - "description": "Sample for ListEventThreatDetectionCustomModules", - "file": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListEventThreatDetectionCustomModules_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": "securitycenter_v1_generated_security_center_list_event_threat_detection_custom_modules_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_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.securitycenter_v1.services.security_center.pagers.ListFindingsAsyncPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v1_generated_security_center_list_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1_generated_security_center_list_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_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.securitycenter_v1.services.security_center.pagers.ListFindingsPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v1_generated_security_center_list_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1_generated_security_center_list_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_mute_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListMuteConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListMuteConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListMuteConfigsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsAsyncPager", - "shortName": "list_mute_configs" - }, - "description": "Sample for ListMuteConfigs", - "file": "securitycenter_v1_generated_security_center_list_mute_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v1_generated_security_center_list_mute_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_mute_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListMuteConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListMuteConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListMuteConfigsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListMuteConfigsPager", - "shortName": "list_mute_configs" - }, - "description": "Sample for ListMuteConfigs", - "file": "securitycenter_v1_generated_security_center_list_mute_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v1_generated_security_center_list_mute_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_notification_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListNotificationConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListNotificationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsAsyncPager", - "shortName": "list_notification_configs" - }, - "description": "Sample for ListNotificationConfigs", - "file": "securitycenter_v1_generated_security_center_list_notification_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1_generated_security_center_list_notification_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_notification_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListNotificationConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListNotificationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsPager", - "shortName": "list_notification_configs" - }, - "description": "Sample for ListNotificationConfigs", - "file": "securitycenter_v1_generated_security_center_list_notification_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1_generated_security_center_list_notification_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsAsyncPager", - "shortName": "list_resource_value_configs" - }, - "description": "Sample for ListResourceValueConfigs", - "file": "securitycenter_v1_generated_security_center_list_resource_value_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v1_generated_security_center_list_resource_value_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListResourceValueConfigsRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListResourceValueConfigsPager", - "shortName": "list_resource_value_configs" - }, - "description": "Sample for ListResourceValueConfigs", - "file": "securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v1_generated_security_center_list_resource_value_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_security_health_analytics_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSecurityHealthAnalyticsCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSecurityHealthAnalyticsCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager", - "shortName": "list_security_health_analytics_custom_modules" - }, - "description": "Sample for ListSecurityHealthAnalyticsCustomModules", - "file": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_security_health_analytics_custom_modules", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSecurityHealthAnalyticsCustomModules", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSecurityHealthAnalyticsCustomModules" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListSecurityHealthAnalyticsCustomModulesPager", - "shortName": "list_security_health_analytics_custom_modules" - }, - "description": "Sample for ListSecurityHealthAnalyticsCustomModules", - "file": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSecurityHealthAnalyticsCustomModules_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": "securitycenter_v1_generated_security_center_list_security_health_analytics_custom_modules_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListSourcesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListSourcesAsyncPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v1_generated_security_center_list_sources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSources_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": "securitycenter_v1_generated_security_center_list_sources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListSourcesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListSourcesPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v1_generated_security_center_list_sources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListSources_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": "securitycenter_v1_generated_security_center_list_sources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.list_valued_resources", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListValuedResources", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListValuedResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListValuedResourcesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesAsyncPager", - "shortName": "list_valued_resources" - }, - "description": "Sample for ListValuedResources", - "file": "securitycenter_v1_generated_security_center_list_valued_resources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v1_generated_security_center_list_valued_resources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.list_valued_resources", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ListValuedResources", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListValuedResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ListValuedResourcesRequest" - }, - { - "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.securitycenter_v1.services.security_center.pagers.ListValuedResourcesPager", - "shortName": "list_valued_resources" - }, - "description": "Sample for ListValuedResources", - "file": "securitycenter_v1_generated_security_center_list_valued_resources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v1_generated_security_center_list_valued_resources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.run_asset_discovery", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.RunAssetDiscovery", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "RunAssetDiscovery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "run_asset_discovery" - }, - "description": "Sample for RunAssetDiscovery", - "file": "securitycenter_v1_generated_security_center_run_asset_discovery_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1_generated_security_center_run_asset_discovery_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.run_asset_discovery", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.RunAssetDiscovery", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "RunAssetDiscovery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "run_asset_discovery" - }, - "description": "Sample for RunAssetDiscovery", - "file": "securitycenter_v1_generated_security_center_run_asset_discovery_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1_generated_security_center_run_asset_discovery_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v1.types.Finding.State" - }, - { - "name": "start_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v1_generated_security_center_set_finding_state_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1_generated_security_center_set_finding_state_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v1.types.Finding.State" - }, - { - "name": "start_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v1_generated_security_center_set_finding_state_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1_generated_security_center_set_finding_state_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v1_generated_security_center_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v1_generated_security_center_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.set_mute", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetMute", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetMute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.SetMuteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "mute", - "type": "google.cloud.securitycenter_v1.types.Finding.Mute" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "set_mute" - }, - "description": "Sample for SetMute", - "file": "securitycenter_v1_generated_security_center_set_mute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SetMute_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": "securitycenter_v1_generated_security_center_set_mute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.set_mute", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SetMute", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetMute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.SetMuteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "mute", - "type": "google.cloud.securitycenter_v1.types.Finding.Mute" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "set_mute" - }, - "description": "Sample for SetMute", - "file": "securitycenter_v1_generated_security_center_set_mute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SetMute_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": "securitycenter_v1_generated_security_center_set_mute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.simulate_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SimulateSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SimulateSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "custom_config", - "type": "google.cloud.securitycenter_v1.types.CustomConfig" - }, - { - "name": "resource", - "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse", - "shortName": "simulate_security_health_analytics_custom_module" - }, - "description": "Sample for SimulateSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.simulate_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.SimulateSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SimulateSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "custom_config", - "type": "google.cloud.securitycenter_v1.types.CustomConfig" - }, - { - "name": "resource", - "type": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse", - "shortName": "simulate_security_health_analytics_custom_module" - }, - "description": "Sample for SimulateSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_SimulateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_simulate_security_health_analytics_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v1_generated_security_center_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v1_generated_security_center_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v1.types.BigQueryExport" - }, - { - "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.securitycenter_v1.types.BigQueryExport", - "shortName": "update_big_query_export" - }, - "description": "Sample for UpdateBigQueryExport", - "file": "securitycenter_v1_generated_security_center_update_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v1_generated_security_center_update_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateBigQueryExportRequest" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v1.types.BigQueryExport" - }, - { - "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.securitycenter_v1.types.BigQueryExport", - "shortName": "update_big_query_export" - }, - "description": "Sample for UpdateBigQueryExport", - "file": "securitycenter_v1_generated_security_center_update_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v1_generated_security_center_update_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest" - }, - { - "name": "event_threat_detection_custom_module", - "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" - }, - { - "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.securitycenter_v1.types.EventThreatDetectionCustomModule", - "shortName": "update_event_threat_detection_custom_module" - }, - "description": "Sample for UpdateEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateEventThreatDetectionCustomModuleRequest" - }, - { - "name": "event_threat_detection_custom_module", - "type": "google.cloud.securitycenter_v1.types.EventThreatDetectionCustomModule" - }, - { - "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.securitycenter_v1.types.EventThreatDetectionCustomModule", - "shortName": "update_event_threat_detection_custom_module" - }, - "description": "Sample for UpdateEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateEventThreatDetectionCustomModule_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": "securitycenter_v1_generated_security_center_update_event_threat_detection_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_external_system", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateExternalSystem", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateExternalSystem" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest" - }, - { - "name": "external_system", - "type": "google.cloud.securitycenter_v1.types.ExternalSystem" - }, - { - "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.securitycenter_v1.types.ExternalSystem", - "shortName": "update_external_system" - }, - "description": "Sample for UpdateExternalSystem", - "file": "securitycenter_v1_generated_security_center_update_external_system_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v1_generated_security_center_update_external_system_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_external_system", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateExternalSystem", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateExternalSystem" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateExternalSystemRequest" - }, - { - "name": "external_system", - "type": "google.cloud.securitycenter_v1.types.ExternalSystem" - }, - { - "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.securitycenter_v1.types.ExternalSystem", - "shortName": "update_external_system" - }, - "description": "Sample for UpdateExternalSystem", - "file": "securitycenter_v1_generated_security_center_update_external_system_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v1_generated_security_center_update_external_system_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v1_generated_security_center_update_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1_generated_security_center_update_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v1_generated_security_center_update_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1_generated_security_center_update_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v1.types.MuteConfig" - }, - { - "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.securitycenter_v1.types.MuteConfig", - "shortName": "update_mute_config" - }, - "description": "Sample for UpdateMuteConfig", - "file": "securitycenter_v1_generated_security_center_update_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v1_generated_security_center_update_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateMuteConfigRequest" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v1.types.MuteConfig" - }, - { - "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.securitycenter_v1.types.MuteConfig", - "shortName": "update_mute_config" - }, - "description": "Sample for UpdateMuteConfig", - "file": "securitycenter_v1_generated_security_center_update_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v1_generated_security_center_update_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1.types.NotificationConfig" - }, - { - "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.securitycenter_v1.types.NotificationConfig", - "shortName": "update_notification_config" - }, - "description": "Sample for UpdateNotificationConfig", - "file": "securitycenter_v1_generated_security_center_update_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1_generated_security_center_update_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1.types.NotificationConfig" - }, - { - "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.securitycenter_v1.types.NotificationConfig", - "shortName": "update_notification_config" - }, - "description": "Sample for UpdateNotificationConfig", - "file": "securitycenter_v1_generated_security_center_update_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1_generated_security_center_update_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest" - }, - { - "name": "organization_settings", - "type": "google.cloud.securitycenter_v1.types.OrganizationSettings" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.OrganizationSettings", - "shortName": "update_organization_settings" - }, - "description": "Sample for UpdateOrganizationSettings", - "file": "securitycenter_v1_generated_security_center_update_organization_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1_generated_security_center_update_organization_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest" - }, - { - "name": "organization_settings", - "type": "google.cloud.securitycenter_v1.types.OrganizationSettings" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.OrganizationSettings", - "shortName": "update_organization_settings" - }, - "description": "Sample for UpdateOrganizationSettings", - "file": "securitycenter_v1_generated_security_center_update_organization_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1_generated_security_center_update_organization_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest" - }, - { - "name": "resource_value_config", - "type": "google.cloud.securitycenter_v1.types.ResourceValueConfig" - }, - { - "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.securitycenter_v1.types.ResourceValueConfig", - "shortName": "update_resource_value_config" - }, - "description": "Sample for UpdateResourceValueConfig", - "file": "securitycenter_v1_generated_security_center_update_resource_value_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v1_generated_security_center_update_resource_value_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateResourceValueConfigRequest" - }, - { - "name": "resource_value_config", - "type": "google.cloud.securitycenter_v1.types.ResourceValueConfig" - }, - { - "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.securitycenter_v1.types.ResourceValueConfig", - "shortName": "update_resource_value_config" - }, - "description": "Sample for UpdateResourceValueConfig", - "file": "securitycenter_v1_generated_security_center_update_resource_value_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v1_generated_security_center_update_resource_value_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "name": "security_health_analytics_custom_module", - "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" - }, - { - "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", - "shortName": "update_security_health_analytics_custom_module" - }, - "description": "Sample for UpdateSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_security_health_analytics_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityHealthAnalyticsCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityHealthAnalyticsCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest" - }, - { - "name": "security_health_analytics_custom_module", - "type": "google.cloud.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule" - }, - { - "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.securitycenter_v1.types.SecurityHealthAnalyticsCustomModule", - "shortName": "update_security_health_analytics_custom_module" - }, - "description": "Sample for UpdateSecurityHealthAnalyticsCustomModule", - "file": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityHealthAnalyticsCustomModule_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": "securitycenter_v1_generated_security_center_update_security_health_analytics_custom_module_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v1.types.SecurityMarks" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v1_generated_security_center_update_security_marks_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1_generated_security_center_update_security_marks_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v1.types.SecurityMarks" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v1_generated_security_center_update_security_marks_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1_generated_security_center_update_security_marks_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v1_generated_security_center_update_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1_generated_security_center_update_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v1_generated_security_center_update_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1_generated_security_center_update_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterAsyncClient.validate_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ValidateEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ValidateEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse", - "shortName": "validate_event_threat_detection_custom_module" - }, - "description": "Sample for ValidateEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1.SecurityCenterClient.validate_event_threat_detection_custom_module", - "method": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter.ValidateEventThreatDetectionCustomModule", - "service": { - "fullName": "google.cloud.securitycenter.v1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ValidateEventThreatDetectionCustomModule" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1.types.ValidateEventThreatDetectionCustomModuleResponse", - "shortName": "validate_event_threat_detection_custom_module" - }, - "description": "Sample for ValidateEventThreatDetectionCustomModule", - "file": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1_generated_SecurityCenter_ValidateEventThreatDetectionCustomModule_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1_generated_security_center_validate_event_threat_detection_custom_module_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py deleted file mode 100644 index 077baab9f5d2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/scripts/fixup_securitycenter_v1_keywords.py +++ /dev/null @@ -1,238 +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 securitycenterCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_create_resource_value_configs': ('parent', 'requests', ), - 'bulk_mute_findings': ('parent', 'filter', 'mute_annotation', 'mute_state', ), - 'create_big_query_export': ('parent', 'big_query_export', 'big_query_export_id', ), - 'create_event_threat_detection_custom_module': ('parent', 'event_threat_detection_custom_module', ), - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_mute_config': ('parent', 'mute_config', 'mute_config_id', ), - 'create_notification_config': ('parent', 'config_id', 'notification_config', ), - 'create_security_health_analytics_custom_module': ('parent', 'security_health_analytics_custom_module', ), - 'create_source': ('parent', 'source', ), - 'delete_big_query_export': ('name', ), - 'delete_event_threat_detection_custom_module': ('name', ), - 'delete_mute_config': ('name', ), - 'delete_notification_config': ('name', ), - 'delete_resource_value_config': ('name', ), - 'delete_security_health_analytics_custom_module': ('name', ), - 'get_big_query_export': ('name', ), - 'get_effective_event_threat_detection_custom_module': ('name', ), - 'get_effective_security_health_analytics_custom_module': ('name', ), - 'get_event_threat_detection_custom_module': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_mute_config': ('name', ), - 'get_notification_config': ('name', ), - 'get_organization_settings': ('name', ), - 'get_resource_value_config': ('name', ), - 'get_security_health_analytics_custom_module': ('name', ), - 'get_simulation': ('name', ), - 'get_source': ('name', ), - 'get_valued_resource': ('name', ), - 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), - 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), - 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_attack_paths': ('parent', 'filter', 'page_token', 'page_size', ), - 'list_big_query_exports': ('parent', 'page_size', 'page_token', ), - 'list_descendant_event_threat_detection_custom_modules': ('parent', 'page_token', 'page_size', ), - 'list_descendant_security_health_analytics_custom_modules': ('parent', 'page_size', 'page_token', ), - 'list_effective_event_threat_detection_custom_modules': ('parent', 'page_token', 'page_size', ), - 'list_effective_security_health_analytics_custom_modules': ('parent', 'page_size', 'page_token', ), - 'list_event_threat_detection_custom_modules': ('parent', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_mute_configs': ('parent', 'page_size', 'page_token', ), - 'list_notification_configs': ('parent', 'page_token', 'page_size', ), - 'list_resource_value_configs': ('parent', 'page_size', 'page_token', ), - 'list_security_health_analytics_custom_modules': ('parent', 'page_size', 'page_token', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'list_valued_resources': ('parent', 'filter', 'page_token', 'page_size', 'order_by', ), - 'run_asset_discovery': ('parent', ), - 'set_finding_state': ('name', 'state', 'start_time', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'set_mute': ('name', 'mute', ), - 'simulate_security_health_analytics_custom_module': ('parent', 'custom_config', 'resource', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_big_query_export': ('big_query_export', 'update_mask', ), - 'update_event_threat_detection_custom_module': ('event_threat_detection_custom_module', 'update_mask', ), - 'update_external_system': ('external_system', 'update_mask', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_mute_config': ('mute_config', 'update_mask', ), - 'update_notification_config': ('notification_config', 'update_mask', ), - 'update_organization_settings': ('organization_settings', 'update_mask', ), - 'update_resource_value_config': ('resource_value_config', 'update_mask', ), - 'update_security_health_analytics_custom_module': ('security_health_analytics_custom_module', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), - 'update_source': ('source', 'update_mask', ), - 'validate_event_threat_detection_custom_module': ('parent', 'raw_text', 'type_', ), - } - - 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=securitycenterCallTransformer(), -): - """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 securitycenter 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-securitycenter/v1/setup.py b/owl-bot-staging/google-cloud-securitycenter/v1/setup.py deleted file mode 100644 index c4538ec101f3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/setup.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. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-securitycenter' - - -description = "Google Cloud Securitycenter API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/securitycenter/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", - "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", -] -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" - -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-securitycenter/v1/tests/unit/gapic/securitycenter_v1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_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-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py deleted file mode 100644 index 534cd268c159..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py +++ /dev/null @@ -1,48271 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -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 - -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.securitycenter_v1.services.security_center import SecurityCenterAsyncClient -from google.cloud.securitycenter_v1.services.security_center import SecurityCenterClient -from google.cloud.securitycenter_v1.services.security_center import pagers -from google.cloud.securitycenter_v1.services.security_center import transports -from google.cloud.securitycenter_v1.types import access -from google.cloud.securitycenter_v1.types import application -from google.cloud.securitycenter_v1.types import attack_exposure -from google.cloud.securitycenter_v1.types import attack_path -from google.cloud.securitycenter_v1.types import backup_disaster_recovery -from google.cloud.securitycenter_v1.types import bigquery_export -from google.cloud.securitycenter_v1.types import cloud_armor -from google.cloud.securitycenter_v1.types import cloud_dlp_data_profile -from google.cloud.securitycenter_v1.types import cloud_dlp_inspection -from google.cloud.securitycenter_v1.types import compliance -from google.cloud.securitycenter_v1.types import connection -from google.cloud.securitycenter_v1.types import contact_details -from google.cloud.securitycenter_v1.types import container -from google.cloud.securitycenter_v1.types import database -from google.cloud.securitycenter_v1.types import effective_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import effective_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module as gcs_event_threat_detection_custom_module -from google.cloud.securitycenter_v1.types import event_threat_detection_custom_module_validation_errors -from google.cloud.securitycenter_v1.types import exfiltration -from google.cloud.securitycenter_v1.types import external_system -from google.cloud.securitycenter_v1.types import external_system as gcs_external_system -from google.cloud.securitycenter_v1.types import file -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import group_membership -from google.cloud.securitycenter_v1.types import iam_binding -from google.cloud.securitycenter_v1.types import indicator -from google.cloud.securitycenter_v1.types import kernel_rootkit -from google.cloud.securitycenter_v1.types import kubernetes -from google.cloud.securitycenter_v1.types import label -from google.cloud.securitycenter_v1.types import load_balancer -from google.cloud.securitycenter_v1.types import log_entry -from google.cloud.securitycenter_v1.types import mitre_attack -from google.cloud.securitycenter_v1.types import mute_config -from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v1.types import notebook -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import org_policy -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import process -from google.cloud.securitycenter_v1.types import resource -from google.cloud.securitycenter_v1.types import resource_value_config -from google.cloud.securitycenter_v1.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_config -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_health_analytics_custom_module as gcs_security_health_analytics_custom_module -from google.cloud.securitycenter_v1.types import security_marks -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import security_posture -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import simulation -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.cloud.securitycenter_v1.types import toxic_combination -from google.cloud.securitycenter_v1.types import valued_resource -from google.cloud.securitycenter_v1.types import vulnerability -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 duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None - assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert SecurityCenterClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SecurityCenterGrpcTransport, "grpc"), - (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - 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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -def test_security_center_client_get_transport_class(): - transport = SecurityCenterClient.get_transport_class() - available_transports = [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterRestTransport, - ] - assert transport in available_transports - - transport = SecurityCenterClient.get_transport_class("grpc") - assert transport == transports.SecurityCenterGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, 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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), -]) -def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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_security_center_client_client_options_from_dict(): - with mock.patch('google.cloud.securitycenter_v1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.BulkMuteFindingsRequest, - dict, -]) -def test_bulk_mute_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.bulk_mute_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BulkMuteFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_bulk_mute_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.bulk_mute_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BulkMuteFindingsRequest() - - -def test_bulk_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.BulkMuteFindingsRequest( - parent='parent_value', - filter='filter_value', - mute_annotation='mute_annotation_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.bulk_mute_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BulkMuteFindingsRequest( - parent='parent_value', - filter='filter_value', - mute_annotation='mute_annotation_value', - ) - -def test_bulk_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc - request = {} - client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BulkMuteFindingsRequest() - -@pytest.mark.asyncio -async def test_bulk_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.bulk_mute_findings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.bulk_mute_findings] = mock_object - - request = {} - await client.bulk_mute_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.bulk_mute_findings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_bulk_mute_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BulkMuteFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BulkMuteFindingsRequest() - 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_bulk_mute_findings_async_from_dict(): - await test_bulk_mute_findings_async(request_type=dict) - - -def test_bulk_mute_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BulkMuteFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.bulk_mute_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_bulk_mute_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BulkMuteFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.bulk_mute_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_bulk_mute_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings( - 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_bulk_mute_findings_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.bulk_mute_findings( - securitycenter_service.BulkMuteFindingsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_bulk_mute_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings( - 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_bulk_mute_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.bulk_mute_findings( - securitycenter_service.BulkMuteFindingsRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_create_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - ) - response = client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - - -def test_create_security_health_analytics_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - - -def test_create_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_security_health_analytics_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest( - parent='parent_value', - ) - -def test_create_security_health_analytics_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc - request = {} - client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_security_health_analytics_custom_module(request) - - # Establish that a new wrapper 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_security_health_analytics_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - )) - response = await client.create_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - -@pytest.mark.asyncio -async def test_create_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_security_health_analytics_custom_module] = mock_object - - request = {} - await client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - )) - response = await client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - - -@pytest.mark.asyncio -async def test_create_security_health_analytics_custom_module_async_from_dict(): - await test_create_security_health_analytics_custom_module_async(request_type=dict) - - -def test_create_security_health_analytics_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_security_health_analytics_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - await client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_security_health_analytics_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_security_health_analytics_custom_module( - parent='parent_value', - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - ) - - # Establish that the 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].security_health_analytics_custom_module - mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value') - assert arg == mock_val - - -def test_create_security_health_analytics_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_health_analytics_custom_module( - securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(), - parent='parent_value', - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_security_health_analytics_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_security_health_analytics_custom_module( - parent='parent_value', - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - ) - - # Establish that 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].security_health_analytics_custom_module - mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_security_health_analytics_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_security_health_analytics_custom_module( - securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(), - parent='parent_value', - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_create_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object - - request = {} - await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_create_source_async_from_dict(): - await test_create_source_async(request_type=dict) - - -def test_create_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.create_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - - -def test_create_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_create_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.create_finding] = mock_rpc - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object - - request = {} - await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_create_finding_async_from_dict(): - await test_create_finding_async(request_type=dict) - - -def test_create_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - arg = args[0].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - - -def test_create_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - arg = args[0].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateMuteConfigRequest, - dict, -]) -def test_create_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - ) - response = client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - - -def test_create_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateMuteConfigRequest() - - -def test_create_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateMuteConfigRequest( - parent='parent_value', - mute_config_id='mute_config_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateMuteConfigRequest( - parent='parent_value', - mute_config_id='mute_config_id_value', - ) - -def test_create_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - request = {} - client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.create_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateMuteConfigRequest() - -@pytest.mark.asyncio -async def test_create_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_mute_config] = mock_object - - request = {} - await client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - - -@pytest.mark.asyncio -async def test_create_mute_config_async_from_dict(): - await test_create_mute_config_async(request_type=dict) - - -def test_create_mute_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateMuteConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.create_mute_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_mute_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateMuteConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) - await client.create_mute_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_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_mute_config( - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_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].mute_config - mock_val = gcs_mute_config.MuteConfig(name='name_value') - assert arg == mock_val - arg = args[0].mute_config_id - mock_val = 'mute_config_id_value' - assert arg == mock_val - - -def test_create_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.CreateMuteConfigRequest(), - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_mute_config( - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_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].mute_config - mock_val = gcs_mute_config.MuteConfig(name='name_value') - assert arg == mock_val - arg = args[0].mute_config_id - mock_val = 'mute_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_mute_config( - securitycenter_service.CreateMuteConfigRequest(), - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateNotificationConfigRequest, - dict, -]) -def test_create_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_create_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateNotificationConfigRequest( - parent='parent_value', - config_id='config_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest( - parent='parent_value', - config_id='config_id_value', - ) - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_create_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_notification_config] = mock_object - - request = {} - await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_create_notification_config_async_from_dict(): - await test_create_notification_config_async(request_type=dict) - - -def test_create_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.create_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.create_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_notification_config( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - # Establish that the 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].config_id - mock_val = 'config_id_value' - assert arg == mock_val - arg = args[0].notification_config - mock_val = gcs_notification_config.NotificationConfig(name='name_value') - assert arg == mock_val - - -def test_create_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_notification_config( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - # Establish that 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].config_id - mock_val = 'config_id_value' - assert arg == mock_val - arg = args[0].notification_config - mock_val = gcs_notification_config.NotificationConfig(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_notification_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteMuteConfigRequest, - dict, -]) -def test_delete_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteMuteConfigRequest() - - -def test_delete_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteMuteConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteMuteConfigRequest( - name='name_value', - ) - -def test_delete_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - request = {} - client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteMuteConfigRequest() - -@pytest.mark.asyncio -async def test_delete_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_mute_config] = mock_object - - request = {} - await client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteMuteConfigRequest() - 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_mute_config_async_from_dict(): - await test_delete_mute_config_async(request_type=dict) - - -def test_delete_mute_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteMuteConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value = None - client.delete_mute_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_mute_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteMuteConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_mute_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_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.DeleteMuteConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_mute_config( - securitycenter_service.DeleteMuteConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteNotificationConfigRequest, - dict, -]) -def test_delete_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteNotificationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest( - name='name_value', - ) - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_delete_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_notification_config] = mock_object - - request = {} - await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteNotificationConfigRequest() - 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_config_async_from_dict(): - await test_delete_notification_config_async(request_type=dict) - - -def test_delete_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = None - client.delete_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_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_notification_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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_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_notification_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_notification_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_delete_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_security_health_analytics_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - - -def test_delete_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_security_health_analytics_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest( - name='name_value', - ) - -def test_delete_security_health_analytics_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc - request = {} - client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_security_health_analytics_custom_module(request) - - # Establish that a new wrapper 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_security_health_analytics_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - -@pytest.mark.asyncio -async def test_delete_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_security_health_analytics_custom_module] = mock_object - - request = {} - await client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - 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_security_health_analytics_custom_module_async_from_dict(): - await test_delete_security_health_analytics_custom_module_async(request_type=dict) - - -def test_delete_security_health_analytics_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = None - client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_security_health_analytics_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_security_health_analytics_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__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_security_health_analytics_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_security_health_analytics_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_health_analytics_custom_module( - securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_security_health_analytics_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_health_analytics_custom_module), - '__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_security_health_analytics_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_security_health_analytics_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_security_health_analytics_custom_module( - securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSimulationRequest, - dict, -]) -def test_get_simulation(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - response = client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSimulationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, simulation.Simulation) - assert response.name == 'name_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -def test_get_simulation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_simulation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSimulationRequest() - - -def test_get_simulation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSimulationRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_simulation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSimulationRequest( - name='name_value', - ) - -def test_get_simulation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_simulation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc - request = {} - client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_simulation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_simulation_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_simulation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSimulationRequest() - -@pytest.mark.asyncio -async def test_get_simulation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_simulation in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_simulation] = mock_object - - request = {} - await client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_simulation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_simulation_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSimulationRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSimulationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, simulation.Simulation) - assert response.name == 'name_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -@pytest.mark.asyncio -async def test_get_simulation_async_from_dict(): - await test_get_simulation_async(request_type=dict) - - -def test_get_simulation_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSimulationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value = simulation.Simulation() - client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_simulation_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSimulationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) - await client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_simulation_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = simulation.Simulation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_simulation( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_simulation_flattened_error(): - client = SecurityCenterClient( - credentials=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_simulation( - securitycenter_service.GetSimulationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_simulation_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = simulation.Simulation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_simulation( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_simulation_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_simulation( - securitycenter_service.GetSimulationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetValuedResourceRequest, - dict, -]) -def test_get_valued_resource(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - ) - response = client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetValuedResourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, valued_resource.ValuedResource) - assert response.name == 'name_value' - assert response.resource == 'resource_value' - assert response.resource_type == 'resource_type_value' - assert response.display_name == 'display_name_value' - assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW - assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) - - -def test_get_valued_resource_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_valued_resource() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetValuedResourceRequest() - - -def test_get_valued_resource_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetValuedResourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_valued_resource(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetValuedResourceRequest( - name='name_value', - ) - -def test_get_valued_resource_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_valued_resource in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc - request = {} - client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_valued_resource(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_valued_resource_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - )) - response = await client.get_valued_resource() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetValuedResourceRequest() - -@pytest.mark.asyncio -async def test_get_valued_resource_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_valued_resource in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_valued_resource] = mock_object - - request = {} - await client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_valued_resource(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_valued_resource_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetValuedResourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - )) - response = await client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetValuedResourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, valued_resource.ValuedResource) - assert response.name == 'name_value' - assert response.resource == 'resource_value' - assert response.resource_type == 'resource_type_value' - assert response.display_name == 'display_name_value' - assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW - assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) - - -@pytest.mark.asyncio -async def test_get_valued_resource_async_from_dict(): - await test_get_valued_resource_async(request_type=dict) - - -def test_get_valued_resource_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetValuedResourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value = valued_resource.ValuedResource() - client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_valued_resource_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetValuedResourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) - await client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_valued_resource_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = valued_resource.ValuedResource() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_valued_resource( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_valued_resource_flattened_error(): - client = SecurityCenterClient( - credentials=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_valued_resource( - securitycenter_service.GetValuedResourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_valued_resource_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = valued_resource.ValuedResource() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_valued_resource( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_valued_resource_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_valued_resource( - securitycenter_service.GetValuedResourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetBigQueryExportRequest, - dict, -]) -def test_get_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - response = client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -def test_get_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetBigQueryExportRequest() - - -def test_get_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetBigQueryExportRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetBigQueryExportRequest( - name='name_value', - ) - -def test_get_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc - request = {} - client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.get_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_get_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_big_query_export] = mock_object - - request = {} - await client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -@pytest.mark.asyncio -async def test_get_big_query_export_async_from_dict(): - await test_get_big_query_export_async(request_type=dict) - - -def test_get_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value = bigquery_export.BigQueryExport() - client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - await client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.GetBigQueryExportRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_big_query_export( - securitycenter_service.GetBigQueryExportRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.GetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest( - resource='resource_value', - ) - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object - - request = {} - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_get_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetMuteConfigRequest, - dict, -]) -def test_get_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=mute_config.MuteConfig.MuteConfigType.STATIC, - ) - response = client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC - - -def test_get_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetMuteConfigRequest() - - -def test_get_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetMuteConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetMuteConfigRequest( - name='name_value', - ) - -def test_get_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_mute_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_mute_config] = mock_rpc - request = {} - client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.get_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetMuteConfigRequest() - -@pytest.mark.asyncio -async def test_get_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_mute_config] = mock_object - - request = {} - await client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC - - -@pytest.mark.asyncio -async def test_get_mute_config_async_from_dict(): - await test_get_mute_config_async(request_type=dict) - - -def test_get_mute_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetMuteConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value = mute_config.MuteConfig() - client.get_mute_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_mute_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetMuteConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig()) - await client.get_mute_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_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mute_config.MuteConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_mute_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_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.GetMuteConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mute_config.MuteConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_mute_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_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_mute_config( - securitycenter_service.GetMuteConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetNotificationConfigRequest, - dict, -]) -def test_get_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_get_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetNotificationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest( - name='name_value', - ) - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_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_notification_config] = mock_rpc - request = {} - client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_get_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_notification_config] = mock_object - - request = {} - await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_get_notification_config_async_from_dict(): - await test_get_notification_config_async(request_type=dict) - - -def test_get_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = notification_config.NotificationConfig() - client.get_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - await client.get_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_notification_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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_notification_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_notification_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetOrganizationSettingsRequest, - dict, -]) -def test_get_organization_settings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_get_organization_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetOrganizationSettingsRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_organization_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest( - name='name_value', - ) - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_organization_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_organization_settings] = mock_rpc - request = {} - client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_organization_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_organization_settings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - -@pytest.mark.asyncio -async def test_get_organization_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_organization_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_organization_settings] = mock_object - - request = {} - await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_organization_settings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_get_organization_settings_async_from_dict(): - await test_get_organization_settings_async(request_type=dict) - - -def test_get_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = organization_settings.OrganizationSettings() - client.get_organization_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_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - await client.get_organization_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_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_organization_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_organization_settings_flattened_error(): - client = SecurityCenterClient( - credentials=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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_organization_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_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_get_effective_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( - name='name_value', - enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - display_name='display_name_value', - ) - response = client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.enablement_state == effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.display_name == 'display_name_value' - - -def test_get_effective_security_health_analytics_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_effective_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - - -def test_get_effective_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_effective_security_health_analytics_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest( - name='name_value', - ) - -def test_get_effective_security_health_analytics_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_effective_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_effective_security_health_analytics_custom_module] = mock_rpc - request = {} - client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_effective_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_effective_security_health_analytics_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( - name='name_value', - enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - display_name='display_name_value', - )) - response = await client.get_effective_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - -@pytest.mark.asyncio -async def test_get_effective_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_effective_security_health_analytics_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_effective_security_health_analytics_custom_module] = mock_object - - request = {} - await client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_effective_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_effective_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( - name='name_value', - enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - display_name='display_name_value', - )) - response = await client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.enablement_state == effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_get_effective_security_health_analytics_custom_module_async_from_dict(): - await test_get_effective_security_health_analytics_custom_module_async(request_type=dict) - - -def test_get_effective_security_health_analytics_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_effective_security_health_analytics_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule()) - await client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_effective_security_health_analytics_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_effective_security_health_analytics_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_effective_security_health_analytics_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_effective_security_health_analytics_custom_module( - securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_effective_security_health_analytics_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_effective_security_health_analytics_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_effective_security_health_analytics_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_effective_security_health_analytics_custom_module( - securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_get_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - ) - response = client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - - -def test_get_security_health_analytics_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - - -def test_get_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_security_health_analytics_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest( - name='name_value', - ) - -def test_get_security_health_analytics_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_security_health_analytics_custom_module] = mock_rpc - request = {} - client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_security_health_analytics_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - )) - response = await client.get_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - -@pytest.mark.asyncio -async def test_get_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_security_health_analytics_custom_module] = mock_object - - request = {} - await client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - )) - response = await client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - - -@pytest.mark.asyncio -async def test_get_security_health_analytics_custom_module_async_from_dict(): - await test_get_security_health_analytics_custom_module_async(request_type=dict) - - -def test_get_security_health_analytics_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_security_health_analytics_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - await client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_security_health_analytics_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_security_health_analytics_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_security_health_analytics_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_health_analytics_custom_module( - securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_security_health_analytics_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_security_health_analytics_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_security_health_analytics_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_security_health_analytics_custom_module( - securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_get_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest( - name='name_value', - ) - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - -@pytest.mark.asyncio -async def test_get_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object - - request = {} - await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_get_source_async_from_dict(): - await test_get_source_async(request_type=dict) - - -def test_get_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = source.Source() - client.get_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_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_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_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_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupAssetsRequest, - dict, -]) -def test_group_assets(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_assets_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - -def test_group_assets_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupAssetsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_assets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_assets_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc - request = {} - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_group_assets_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - -@pytest.mark.asyncio -async def test_group_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_assets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_assets] = mock_object - - request = {} - await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_assets_async_from_dict(): - await test_group_assets_async(request_type=dict) - - -def test_group_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = securitycenter_service.GroupAssetsResponse() - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_group_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) - await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_group_assets_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_assets(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, securitycenter_service.GroupResult) - for i in results) -def test_group_assets_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_assets(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_group_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_assets(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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_assets(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", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - -@pytest.mark.asyncio -async def test_group_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_findings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object - - request = {} - await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_findings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_findings_async_from_dict(): - await test_group_findings_async(request_type=dict) - - -def test_group_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_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_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - await client.group_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_group_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that the 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - - -def test_group_findings_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - -@pytest.mark.asyncio -async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_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, securitycenter_service.GroupResult) - for i in results) -def test_group_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_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_group_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_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", [ - securitycenter_service.ListAssetsRequest, - dict, -]) -def test_list_assets(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_assets_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - -def test_list_assets_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListAssetsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_assets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_value', - page_token='page_token_value', - ) - -def test_list_assets_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc - request = {} - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_assets_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - -@pytest.mark.asyncio -async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_assets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object - - request = {} - await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_assets_async_from_dict(): - await test_list_assets_async(request_type=dict) - - -def test_list_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = securitycenter_service.ListAssetsResponse() - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) - await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_assets_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) -def test_list_assets_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_assets(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_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - 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_assets(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", [ - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, - dict, -]) -def test_list_descendant_security_health_analytics_custom_modules(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_descendant_security_health_analytics_custom_modules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_descendant_security_health_analytics_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - - -def test_list_descendant_security_health_analytics_custom_modules_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( - 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_descendant_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_descendant_security_health_analytics_custom_modules(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_descendant_security_health_analytics_custom_modules_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_descendant_security_health_analytics_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_descendant_security_health_analytics_custom_modules] = mock_rpc - request = {} - client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_descendant_security_health_analytics_custom_modules_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_descendant_security_health_analytics_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - -@pytest.mark.asyncio -async def test_list_descendant_security_health_analytics_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_descendant_security_health_analytics_custom_modules in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_descendant_security_health_analytics_custom_modules] = mock_object - - request = {} - await client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_descendant_security_health_analytics_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_descendant_security_health_analytics_custom_modules_async_from_dict(): - await test_list_descendant_security_health_analytics_custom_modules_async(request_type=dict) - - -def test_list_descendant_security_health_analytics_custom_modules_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_descendant_security_health_analytics_custom_modules_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse()) - await client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_descendant_security_health_analytics_custom_modules_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_descendant_security_health_analytics_custom_modules( - 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_descendant_security_health_analytics_custom_modules_flattened_error(): - client = SecurityCenterClient( - credentials=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_descendant_security_health_analytics_custom_modules( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_descendant_security_health_analytics_custom_modules_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_descendant_security_health_analytics_custom_modules( - 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_descendant_security_health_analytics_custom_modules_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_descendant_security_health_analytics_custom_modules( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_descendant_security_health_analytics_custom_modules_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_descendant_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - for i in results) -def test_list_descendant_security_health_analytics_custom_modules_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_descendant_security_health_analytics_custom_modules(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_descendant_security_health_analytics_custom_modules_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_descendant_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_descendant_security_health_analytics_custom_modules_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_security_health_analytics_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - 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_descendant_security_health_analytics_custom_modules(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", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -def test_list_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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] == securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - -@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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object - - request = {} - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -@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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in results) -def test_list_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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 = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_findings_async_pages(): - client = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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", [ - securitycenter_service.ListMuteConfigsRequest, - dict, -]) -def test_list_mute_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListMuteConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMuteConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_mute_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_mute_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListMuteConfigsRequest() - - -def test_list_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListMuteConfigsRequest( - 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_mute_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_mute_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListMuteConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_mute_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_mute_configs] = mock_rpc - request = {} - client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_mute_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_mute_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_mute_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListMuteConfigsRequest() - -@pytest.mark.asyncio -async def test_list_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_mute_configs] = mock_object - - request = {} - await client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_mute_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_mute_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListMuteConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListMuteConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMuteConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_mute_configs_async_from_dict(): - await test_list_mute_configs_async(request_type=dict) - - -def test_list_mute_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListMuteConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListMuteConfigsResponse() - client.list_mute_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_mute_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListMuteConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse()) - await client.list_mute_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_mute_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListMuteConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_mute_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_mute_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_configs( - securitycenter_service.ListMuteConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_mute_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListMuteConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_mute_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_mute_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_mute_configs( - securitycenter_service.ListMuteConfigsRequest(), - parent='parent_value', - ) - - -def test_list_mute_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_mute_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, mute_config.MuteConfig) - for i in results) -def test_list_mute_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_mute_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_mute_configs_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_mute_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, mute_config.MuteConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_mute_configs_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - 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_mute_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", [ - securitycenter_service.ListNotificationConfigsRequest, - dict, -]) -def test_list_notification_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListNotificationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_notification_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListNotificationConfigsRequest( - 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_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notification_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_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_notification_configs] = mock_rpc - request = {} - client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_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_notification_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - -@pytest.mark.asyncio -async def test_list_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_notification_configs] = mock_object - - request = {} - await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_notification_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListNotificationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_from_dict(): - await test_list_notification_configs_async(request_type=dict) - - -def test_list_notification_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - 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_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - client.list_notification_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_notification_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - 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_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - await client.list_notification_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_notification_configs_flattened(): - client = SecurityCenterClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_notification_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_notification_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_notification_configs_flattened_async(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_notification_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_notification_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_notification_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - 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_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, notification_config.NotificationConfig) - for i in results) -def test_list_notification_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_notification_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_notification_configs_async_pager(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_notification_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, notification_config.NotificationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_pages(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - 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_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", [ - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, - dict, -]) -def test_list_effective_security_health_analytics_custom_modules(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_effective_security_health_analytics_custom_modules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_effective_security_health_analytics_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - - -def test_list_effective_security_health_analytics_custom_modules_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( - 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_effective_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_effective_security_health_analytics_custom_modules(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_effective_security_health_analytics_custom_modules_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_effective_security_health_analytics_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_effective_security_health_analytics_custom_modules] = mock_rpc - request = {} - client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_effective_security_health_analytics_custom_modules_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_effective_security_health_analytics_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - -@pytest.mark.asyncio -async def test_list_effective_security_health_analytics_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_effective_security_health_analytics_custom_modules in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_effective_security_health_analytics_custom_modules] = mock_object - - request = {} - await client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_effective_security_health_analytics_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_effective_security_health_analytics_custom_modules_async_from_dict(): - await test_list_effective_security_health_analytics_custom_modules_async(request_type=dict) - - -def test_list_effective_security_health_analytics_custom_modules_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_effective_security_health_analytics_custom_modules_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse()) - await client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_effective_security_health_analytics_custom_modules_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_effective_security_health_analytics_custom_modules( - 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_effective_security_health_analytics_custom_modules_flattened_error(): - client = SecurityCenterClient( - credentials=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_effective_security_health_analytics_custom_modules( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_effective_security_health_analytics_custom_modules_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_effective_security_health_analytics_custom_modules( - 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_effective_security_health_analytics_custom_modules_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_effective_security_health_analytics_custom_modules( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_effective_security_health_analytics_custom_modules_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_effective_security_health_analytics_custom_modules(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, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) - for i in results) -def test_list_effective_security_health_analytics_custom_modules_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_effective_security_health_analytics_custom_modules(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_effective_security_health_analytics_custom_modules_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_effective_security_health_analytics_custom_modules(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, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_effective_security_health_analytics_custom_modules_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_security_health_analytics_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - ), - 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_effective_security_health_analytics_custom_modules(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", [ - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, - dict, -]) -def test_list_security_health_analytics_custom_modules(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSecurityHealthAnalyticsCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_security_health_analytics_custom_modules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_security_health_analytics_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - - -def test_list_security_health_analytics_custom_modules_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest( - 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_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_security_health_analytics_custom_modules(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_security_health_analytics_custom_modules_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_security_health_analytics_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_security_health_analytics_custom_modules] = mock_rpc - request = {} - client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_security_health_analytics_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_security_health_analytics_custom_modules_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_security_health_analytics_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - -@pytest.mark.asyncio -async def test_list_security_health_analytics_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_health_analytics_custom_modules in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_security_health_analytics_custom_modules] = mock_object - - request = {} - await client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_security_health_analytics_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_security_health_analytics_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_security_health_analytics_custom_modules_async_from_dict(): - await test_list_security_health_analytics_custom_modules_async(request_type=dict) - - -def test_list_security_health_analytics_custom_modules_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_security_health_analytics_custom_modules_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse()) - await client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_security_health_analytics_custom_modules_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_security_health_analytics_custom_modules( - 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_security_health_analytics_custom_modules_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_health_analytics_custom_modules( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_security_health_analytics_custom_modules_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_security_health_analytics_custom_modules( - 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_security_health_analytics_custom_modules_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_security_health_analytics_custom_modules( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_security_health_analytics_custom_modules_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - for i in results) -def test_list_security_health_analytics_custom_modules_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_security_health_analytics_custom_modules(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_security_health_analytics_custom_modules_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_security_health_analytics_custom_modules(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, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_security_health_analytics_custom_modules_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_health_analytics_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - 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_security_health_analytics_custom_modules(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", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_sources_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListSourcesRequest( - 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_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - -@pytest.mark.asyncio -async def test_list_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_sources in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object - - request = {} - await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_sources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_sources_async_from_dict(): - await test_list_sources_async(request_type=dict) - - -def test_list_sources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = securitycenter_service.ListSourcesResponse() - client.list_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_sources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - await client.list_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_sources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_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_sources_flattened_error(): - client = SecurityCenterClient( - credentials=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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_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_sources_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_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, source.Source) - for i in results) -def test_list_sources_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = list(client.list_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_sources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_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, source.Source) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - 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_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", [ - securitycenter_service.RunAssetDiscoveryRequest, - dict, -]) -def test_run_asset_discovery(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.RunAssetDiscoveryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_run_asset_discovery_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - -def test_run_asset_discovery_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.RunAssetDiscoveryRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.run_asset_discovery(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest( - parent='parent_value', - ) - -def test_run_asset_discovery_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.run_asset_discovery in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc - request = {} - client.run_asset_discovery(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.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_run_asset_discovery_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - -@pytest.mark.asyncio -async def test_run_asset_discovery_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.run_asset_discovery in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.run_asset_discovery] = mock_object - - request = {} - await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.RunAssetDiscoveryRequest() - 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_run_asset_discovery_async_from_dict(): - await test_run_asset_discovery_async(request_type=dict) - - -def test_run_asset_discovery_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_run_asset_discovery_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_run_asset_discovery_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery( - 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_run_asset_discovery_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_run_asset_discovery_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery( - 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_run_asset_discovery_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_set_finding_state_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - -@pytest.mark.asyncio -async def test_set_finding_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object - - request = {} - await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_finding_state(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_set_finding_state_async_from_dict(): - await test_set_finding_state_async(request_type=dict) - - -def test_set_finding_state_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = finding.Finding() - client.set_finding_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_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_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_set_finding_state_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - - -def test_set_finding_state_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetMuteRequest, - dict, -]) -def test_set_mute(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetMuteRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_set_mute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_mute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetMuteRequest() - - -def test_set_mute_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SetMuteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_mute(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetMuteRequest( - name='name_value', - ) - -def test_set_mute_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_mute in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc - request = {} - client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_mute(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_set_mute_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_mute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetMuteRequest() - -@pytest.mark.asyncio -async def test_set_mute_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_mute in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_mute] = mock_object - - request = {} - await client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_mute(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_mute_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetMuteRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetMuteRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_set_mute_async_from_dict(): - await test_set_mute_async(request_type=dict) - - -def test_set_mute_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetMuteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value = finding.Finding() - client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_mute_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetMuteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_set_mute_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__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.set_mute( - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].mute - mock_val = finding.Finding.Mute.MUTED - assert arg == mock_val - - -def test_set_mute_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_mute( - securitycenter_service.SetMuteRequest(), - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - -@pytest.mark.asyncio -async def test_set_mute_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__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.set_mute( - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].mute - mock_val = finding.Finding.Mute.MUTED - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_mute_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_mute( - securitycenter_service.SetMuteRequest(), - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.SetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest( - resource='resource_value', - ) - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object - - request = {} - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = SecurityCenterClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.TestIamPermissionsRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( - resource='resource_value', - ) - -def test_test_iam_permissions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object - - request = {} - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_simulate_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( - ) - response = client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) - - -def test_simulate_security_health_analytics_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.simulate_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - - -def test_simulate_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.simulate_security_health_analytics_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest( - parent='parent_value', - ) - -def test_simulate_security_health_analytics_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.simulate_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.simulate_security_health_analytics_custom_module] = mock_rpc - request = {} - client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.simulate_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( - )) - response = await client.simulate_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.simulate_security_health_analytics_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.simulate_security_health_analytics_custom_module] = mock_object - - request = {} - await client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.simulate_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( - )) - response = await client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) - - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_async_from_dict(): - await test_simulate_security_health_analytics_custom_module_async(request_type=dict) - - -def test_simulate_security_health_analytics_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse()) - await client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_simulate_security_health_analytics_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.simulate_security_health_analytics_custom_module( - parent='parent_value', - custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), - resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), - ) - - # Establish that the 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].custom_config - mock_val = security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')) - assert arg == mock_val - arg = args[0].resource - mock_val = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value') - assert arg == mock_val - - -def test_simulate_security_health_analytics_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.simulate_security_health_analytics_custom_module( - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(), - parent='parent_value', - custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), - resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), - ) - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.simulate_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.simulate_security_health_analytics_custom_module( - parent='parent_value', - custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), - resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), - ) - - # Establish that 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].custom_config - mock_val = security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')) - assert arg == mock_val - arg = args[0].resource - mock_val = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_simulate_security_health_analytics_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.simulate_security_health_analytics_custom_module( - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(), - parent='parent_value', - custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), - resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateExternalSystemRequest, - dict, -]) -def test_update_external_system(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - ) - response = client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateExternalSystemRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_external_system.ExternalSystem) - assert response.name == 'name_value' - assert response.assignees == ['assignees_value'] - assert response.external_uid == 'external_uid_value' - assert response.status == 'status_value' - assert response.case_uri == 'case_uri_value' - assert response.case_priority == 'case_priority_value' - - -def test_update_external_system_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_external_system() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateExternalSystemRequest() - - -def test_update_external_system_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateExternalSystemRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_external_system(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateExternalSystemRequest( - ) - -def test_update_external_system_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_external_system in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc - request = {} - client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_external_system(request) - - # Establish that a new wrapper 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_external_system_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - )) - response = await client.update_external_system() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateExternalSystemRequest() - -@pytest.mark.asyncio -async def test_update_external_system_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_external_system in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_external_system] = mock_object - - request = {} - await client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_external_system(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_external_system_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateExternalSystemRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - )) - response = await client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateExternalSystemRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_external_system.ExternalSystem) - assert response.name == 'name_value' - assert response.assignees == ['assignees_value'] - assert response.external_uid == 'external_uid_value' - assert response.status == 'status_value' - assert response.case_uri == 'case_uri_value' - assert response.case_priority == 'case_priority_value' - - -@pytest.mark.asyncio -async def test_update_external_system_async_from_dict(): - await test_update_external_system_async(request_type=dict) - - -def test_update_external_system_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateExternalSystemRequest() - - request.external_system.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value = gcs_external_system.ExternalSystem() - client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'external_system.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_external_system_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateExternalSystemRequest() - - request.external_system.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) - await client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'external_system.name=name_value', - ) in kw['metadata'] - - -def test_update_external_system_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_external_system.ExternalSystem() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_external_system( - external_system=gcs_external_system.ExternalSystem(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].external_system - mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error(): - client = SecurityCenterClient( - credentials=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_external_system( - securitycenter_service.UpdateExternalSystemRequest(), - external_system=gcs_external_system.ExternalSystem(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_external_system_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_external_system.ExternalSystem() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_external_system( - external_system=gcs_external_system.ExternalSystem(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].external_system - mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_external_system( - securitycenter_service.UpdateExternalSystemRequest(), - external_system=gcs_external_system.ExternalSystem(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_update_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateFindingRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.update_finding] = mock_rpc - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object - - request = {} - await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_update_finding_async_from_dict(): - await test_update_finding_async(request_type=dict) - - -def test_update_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -def test_update_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_finding( - finding=gcs_finding.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].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - - -def test_update_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_finding( - finding=gcs_finding.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].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateMuteConfigRequest, - dict, -]) -def test_update_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - ) - response = client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - - -def test_update_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateMuteConfigRequest() - - -def test_update_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateMuteConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateMuteConfigRequest( - ) - -def test_update_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - request = {} - client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.update_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateMuteConfigRequest() - -@pytest.mark.asyncio -async def test_update_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_mute_config] = mock_object - - request = {} - await client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - - -@pytest.mark.asyncio -async def test_update_mute_config_async_from_dict(): - await test_update_mute_config_async(request_type=dict) - - -def test_update_mute_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateMuteConfigRequest() - - request.mute_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.update_mute_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', - 'mute_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_mute_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateMuteConfigRequest() - - request.mute_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) - await client.update_mute_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', - 'mute_config.name=name_value', - ) in kw['metadata'] - - -def test_update_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_mute_config( - mute_config=gcs_mute_config.MuteConfig(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].mute_config - mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.UpdateMuteConfigRequest(), - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_mute_config( - mute_config=gcs_mute_config.MuteConfig(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].mute_config - mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_mute_config( - securitycenter_service.UpdateMuteConfigRequest(), - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateNotificationConfigRequest, - dict, -]) -def test_update_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_update_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateNotificationConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest( - ) - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_update_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_notification_config] = mock_object - - request = {} - await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_update_notification_config_async_from_dict(): - await test_update_notification_config_async(request_type=dict) - - -def test_update_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.update_notification_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', - 'notification_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.update_notification_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', - 'notification_config.name=name_value', - ) in kw['metadata'] - - -def test_update_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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].notification_config - mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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].notification_config - mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_notification_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateOrganizationSettingsRequest, - dict, -]) -def test_update_organization_settings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_update_organization_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateOrganizationSettingsRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_organization_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest( - ) - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_organization_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_organization_settings] = mock_rpc - request = {} - client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_organization_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_organization_settings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - -@pytest.mark.asyncio -async def test_update_organization_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_organization_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_organization_settings] = mock_object - - request = {} - await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_organization_settings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_update_organization_settings_async_from_dict(): - await test_update_organization_settings_async(request_type=dict) - - -def test_update_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = gcs_organization_settings.OrganizationSettings() - client.update_organization_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', - 'organization_settings.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - await client.update_organization_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', - 'organization_settings.name=name_value', - ) in kw['metadata'] - - -def test_update_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].organization_settings - mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') - assert arg == mock_val - - -def test_update_organization_settings_flattened_error(): - client = SecurityCenterClient( - credentials=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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].organization_settings - mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_update_security_health_analytics_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - ) - response = client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - - -def test_update_security_health_analytics_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - - -def test_update_security_health_analytics_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_health_analytics_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest( - ) - -def test_update_security_health_analytics_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_health_analytics_custom_module] = mock_rpc - request = {} - client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_health_analytics_custom_module(request) - - # Establish that a new wrapper 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_security_health_analytics_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - )) - response = await client.update_security_health_analytics_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - -@pytest.mark.asyncio -async def test_update_security_health_analytics_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_health_analytics_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_security_health_analytics_custom_module] = mock_object - - request = {} - await client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_security_health_analytics_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - )) - response = await client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - - -@pytest.mark.asyncio -async def test_update_security_health_analytics_custom_module_async_from_dict(): - await test_update_security_health_analytics_custom_module_async(request_type=dict) - - -def test_update_security_health_analytics_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - - request.security_health_analytics_custom_module.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_health_analytics_custom_module.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_health_analytics_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - - request.security_health_analytics_custom_module.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - await client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_health_analytics_custom_module.name=name_value', - ) in kw['metadata'] - - -def test_update_security_health_analytics_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_health_analytics_custom_module( - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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].security_health_analytics_custom_module - mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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_security_health_analytics_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_health_analytics_custom_module( - securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(), - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_security_health_analytics_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_health_analytics_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_health_analytics_custom_module( - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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].security_health_analytics_custom_module - mock_val = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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_security_health_analytics_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_security_health_analytics_custom_module( - securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(), - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSourceRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object - - request = {} - await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_source_async_from_dict(): - await test_update_source_async(request_type=dict) - - -def test_update_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -def test_update_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_source( - source=gcs_source.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].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - - -def test_update_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_source( - source=gcs_source.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].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - response = client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_security_marks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - -def test_update_security_marks_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSecurityMarksRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( - ) - -def test_update_security_marks_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish that a new wrapper 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_security_marks_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - -@pytest.mark.asyncio -async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_marks in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object - - request = {} - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_security_marks(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_security_marks_async_from_dict(): - await test_update_security_marks_async(request_type=dict) - - -def test_update_security_marks_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -def test_update_security_marks_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].security_marks - mock_val = gcs_security_marks.SecurityMarks(name='name_value') - assert arg == mock_val - - -def test_update_security_marks_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].security_marks - mock_val = gcs_security_marks.SecurityMarks(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateBigQueryExportRequest, - dict, -]) -def test_create_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - response = client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -def test_create_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateBigQueryExportRequest() - - -def test_create_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateBigQueryExportRequest( - parent='parent_value', - big_query_export_id='big_query_export_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateBigQueryExportRequest( - parent='parent_value', - big_query_export_id='big_query_export_id_value', - ) - -def test_create_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - request = {} - client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_big_query_export(request) - - # Establish that a new wrapper 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_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.create_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_create_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_big_query_export] = mock_object - - request = {} - await client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -@pytest.mark.asyncio -async def test_create_big_query_export_async_from_dict(): - await test_create_big_query_export_async(request_type=dict) - - -def test_create_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateBigQueryExportRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value = bigquery_export.BigQueryExport() - client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateBigQueryExportRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - await client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_big_query_export( - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_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].big_query_export - mock_val = bigquery_export.BigQueryExport(name='name_value') - assert arg == mock_val - arg = args[0].big_query_export_id - mock_val = 'big_query_export_id_value' - assert arg == mock_val - - -def test_create_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.CreateBigQueryExportRequest(), - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_id_value', - ) - -@pytest.mark.asyncio -async def test_create_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_big_query_export( - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_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].big_query_export - mock_val = bigquery_export.BigQueryExport(name='name_value') - assert arg == mock_val - arg = args[0].big_query_export_id - mock_val = 'big_query_export_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_big_query_export( - securitycenter_service.CreateBigQueryExportRequest(), - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteBigQueryExportRequest, - dict, -]) -def test_delete_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() - - -def test_delete_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteBigQueryExportRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteBigQueryExportRequest( - name='name_value', - ) - -def test_delete_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - request = {} - client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_big_query_export(request) - - # Establish that a new wrapper 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_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_delete_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_big_query_export] = mock_object - - request = {} - await client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteBigQueryExportRequest() - 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_big_query_export_async_from_dict(): - await test_delete_big_query_export_async(request_type=dict) - - -def test_delete_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value = None - client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__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_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.DeleteBigQueryExportRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__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_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_big_query_export( - securitycenter_service.DeleteBigQueryExportRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateBigQueryExportRequest, - dict, -]) -def test_update_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - response = client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -def test_update_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() - - -def test_update_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateBigQueryExportRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateBigQueryExportRequest( - ) - -def test_update_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc - request = {} - client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_big_query_export(request) - - # Establish that a new wrapper 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_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.update_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_update_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_big_query_export] = mock_object - - request = {} - await client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -@pytest.mark.asyncio -async def test_update_big_query_export_async_from_dict(): - await test_update_big_query_export_async(request_type=dict) - - -def test_update_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateBigQueryExportRequest() - - request.big_query_export.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value = bigquery_export.BigQueryExport() - client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'big_query_export.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateBigQueryExportRequest() - - request.big_query_export.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - await client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'big_query_export.name=name_value', - ) in kw['metadata'] - - -def test_update_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_big_query_export( - big_query_export=bigquery_export.BigQueryExport(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].big_query_export - mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.UpdateBigQueryExportRequest(), - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_big_query_export( - big_query_export=bigquery_export.BigQueryExport(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].big_query_export - mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_big_query_export( - securitycenter_service.UpdateBigQueryExportRequest(), - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListBigQueryExportsRequest, - dict, -]) -def test_list_big_query_exports(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListBigQueryExportsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryExportsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_big_query_exports_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_big_query_exports() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListBigQueryExportsRequest() - - -def test_list_big_query_exports_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListBigQueryExportsRequest( - 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_big_query_exports), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_big_query_exports(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListBigQueryExportsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_big_query_exports_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_big_query_exports in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc - request = {} - client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_big_query_exports(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_big_query_exports_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_big_query_exports() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListBigQueryExportsRequest() - -@pytest.mark.asyncio -async def test_list_big_query_exports_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_exports in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_big_query_exports] = mock_object - - request = {} - await client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_big_query_exports(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_big_query_exports_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListBigQueryExportsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListBigQueryExportsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryExportsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_big_query_exports_async_from_dict(): - await test_list_big_query_exports_async(request_type=dict) - - -def test_list_big_query_exports_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListBigQueryExportsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - call.return_value = securitycenter_service.ListBigQueryExportsResponse() - client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_exports_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListBigQueryExportsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) - await client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_exports_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListBigQueryExportsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_big_query_exports( - 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_big_query_exports_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_exports( - securitycenter_service.ListBigQueryExportsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_big_query_exports_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListBigQueryExportsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_big_query_exports( - 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_big_query_exports_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_big_query_exports( - securitycenter_service.ListBigQueryExportsRequest(), - parent='parent_value', - ) - - -def test_list_big_query_exports_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_big_query_exports(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, bigquery_export.BigQueryExport) - for i in results) -def test_list_big_query_exports_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - RuntimeError, - ) - pages = list(client.list_big_query_exports(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_big_query_exports_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_big_query_exports(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, bigquery_export.BigQueryExport) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_big_query_exports_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - 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_big_query_exports(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", [ - securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_create_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - ) - response = client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - - -def test_create_event_threat_detection_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - - -def test_create_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_event_threat_detection_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateEventThreatDetectionCustomModuleRequest( - parent='parent_value', - ) - -def test_create_event_threat_detection_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc - request = {} - client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_event_threat_detection_custom_module(request) - - # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - )) - response = await client.create_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - -@pytest.mark.asyncio -async def test_create_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_event_threat_detection_custom_module] = mock_object - - request = {} - await client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - )) - response = await client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - - -@pytest.mark.asyncio -async def test_create_event_threat_detection_custom_module_async_from_dict(): - await test_create_event_threat_detection_custom_module_async(request_type=dict) - - -def test_create_event_threat_detection_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_event_threat_detection_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - await client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_event_threat_detection_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_event_threat_detection_custom_module( - parent='parent_value', - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - ) - - # Establish that the 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].event_threat_detection_custom_module - mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value') - assert arg == mock_val - - -def test_create_event_threat_detection_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_event_threat_detection_custom_module( - securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(), - parent='parent_value', - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_event_threat_detection_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_event_threat_detection_custom_module( - parent='parent_value', - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - ) - - # Establish that 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].event_threat_detection_custom_module - mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_event_threat_detection_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_event_threat_detection_custom_module( - securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(), - parent='parent_value', - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_delete_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_event_threat_detection_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - - -def test_delete_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_event_threat_detection_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest( - name='name_value', - ) - -def test_delete_event_threat_detection_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc - request = {} - client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_event_threat_detection_custom_module(request) - - # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - -@pytest.mark.asyncio -async def test_delete_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_event_threat_detection_custom_module] = mock_object - - request = {} - await client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - 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_event_threat_detection_custom_module_async_from_dict(): - await test_delete_event_threat_detection_custom_module_async(request_type=dict) - - -def test_delete_event_threat_detection_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = None - client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_event_threat_detection_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_event_threat_detection_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__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_event_threat_detection_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_event_threat_detection_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_event_threat_detection_custom_module( - securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_event_threat_detection_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_threat_detection_custom_module), - '__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_event_threat_detection_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_event_threat_detection_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_event_threat_detection_custom_module( - securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_get_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - ) - response = client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - - -def test_get_event_threat_detection_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - - -def test_get_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_event_threat_detection_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEventThreatDetectionCustomModuleRequest( - name='name_value', - ) - -def test_get_event_threat_detection_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_event_threat_detection_custom_module] = mock_rpc - request = {} - client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_event_threat_detection_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - )) - response = await client.get_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - -@pytest.mark.asyncio -async def test_get_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_event_threat_detection_custom_module] = mock_object - - request = {} - await client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetEventThreatDetectionCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - )) - response = await client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - - -@pytest.mark.asyncio -async def test_get_event_threat_detection_custom_module_async_from_dict(): - await test_get_event_threat_detection_custom_module_async(request_type=dict) - - -def test_get_event_threat_detection_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_event_threat_detection_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - await client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_event_threat_detection_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_event_threat_detection_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_event_threat_detection_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_event_threat_detection_custom_module( - securitycenter_service.GetEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_event_threat_detection_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_event_threat_detection_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_event_threat_detection_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_event_threat_detection_custom_module( - securitycenter_service.GetEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, - dict, -]) -def test_list_descendant_event_threat_detection_custom_modules(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDescendantEventThreatDetectionCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_descendant_event_threat_detection_custom_modules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_descendant_event_threat_detection_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - - -def test_list_descendant_event_threat_detection_custom_modules_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest( - 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_descendant_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_descendant_event_threat_detection_custom_modules(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_descendant_event_threat_detection_custom_modules_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_descendant_event_threat_detection_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_descendant_event_threat_detection_custom_modules] = mock_rpc - request = {} - client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_descendant_event_threat_detection_custom_modules_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_descendant_event_threat_detection_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - -@pytest.mark.asyncio -async def test_list_descendant_event_threat_detection_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_descendant_event_threat_detection_custom_modules in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_descendant_event_threat_detection_custom_modules] = mock_object - - request = {} - await client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_descendant_event_threat_detection_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_descendant_event_threat_detection_custom_modules_async_from_dict(): - await test_list_descendant_event_threat_detection_custom_modules_async(request_type=dict) - - -def test_list_descendant_event_threat_detection_custom_modules_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_descendant_event_threat_detection_custom_modules_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse()) - await client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_descendant_event_threat_detection_custom_modules_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_descendant_event_threat_detection_custom_modules( - 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_descendant_event_threat_detection_custom_modules_flattened_error(): - client = SecurityCenterClient( - credentials=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_descendant_event_threat_detection_custom_modules( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_descendant_event_threat_detection_custom_modules_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_descendant_event_threat_detection_custom_modules( - 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_descendant_event_threat_detection_custom_modules_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_descendant_event_threat_detection_custom_modules( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_descendant_event_threat_detection_custom_modules_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_descendant_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - for i in results) -def test_list_descendant_event_threat_detection_custom_modules_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_descendant_event_threat_detection_custom_modules(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_descendant_event_threat_detection_custom_modules_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_descendant_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_descendant_event_threat_detection_custom_modules_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_descendant_event_threat_detection_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - 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_descendant_event_threat_detection_custom_modules(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", [ - securitycenter_service.ListEventThreatDetectionCustomModulesRequest, - dict, -]) -def test_list_event_threat_detection_custom_modules(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEventThreatDetectionCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_event_threat_detection_custom_modules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_event_threat_detection_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - - -def test_list_event_threat_detection_custom_modules_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest( - 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_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_event_threat_detection_custom_modules(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEventThreatDetectionCustomModulesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_event_threat_detection_custom_modules_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_event_threat_detection_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_event_threat_detection_custom_modules] = mock_rpc - request = {} - client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_event_threat_detection_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_event_threat_detection_custom_modules_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_event_threat_detection_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - -@pytest.mark.asyncio -async def test_list_event_threat_detection_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_event_threat_detection_custom_modules in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_event_threat_detection_custom_modules] = mock_object - - request = {} - await client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_event_threat_detection_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_event_threat_detection_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListEventThreatDetectionCustomModulesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEventThreatDetectionCustomModulesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_event_threat_detection_custom_modules_async_from_dict(): - await test_list_event_threat_detection_custom_modules_async(request_type=dict) - - -def test_list_event_threat_detection_custom_modules_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_event_threat_detection_custom_modules_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse()) - await client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_event_threat_detection_custom_modules_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_event_threat_detection_custom_modules( - 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_event_threat_detection_custom_modules_flattened_error(): - client = SecurityCenterClient( - credentials=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_event_threat_detection_custom_modules( - securitycenter_service.ListEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_event_threat_detection_custom_modules_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEventThreatDetectionCustomModulesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_event_threat_detection_custom_modules( - 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_event_threat_detection_custom_modules_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_event_threat_detection_custom_modules( - securitycenter_service.ListEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_event_threat_detection_custom_modules_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - for i in results) -def test_list_event_threat_detection_custom_modules_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_event_threat_detection_custom_modules(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_event_threat_detection_custom_modules_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_event_threat_detection_custom_modules(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, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_event_threat_detection_custom_modules_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_threat_detection_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - 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_event_threat_detection_custom_modules(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", [ - securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_update_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - ) - response = client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - - -def test_update_event_threat_detection_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - - -def test_update_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_event_threat_detection_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest( - ) - -def test_update_event_threat_detection_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_event_threat_detection_custom_module] = mock_rpc - request = {} - client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_event_threat_detection_custom_module(request) - - # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - )) - response = await client.update_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - -@pytest.mark.asyncio -async def test_update_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_event_threat_detection_custom_module] = mock_object - - request = {} - await client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - )) - response = await client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - - -@pytest.mark.asyncio -async def test_update_event_threat_detection_custom_module_async_from_dict(): - await test_update_event_threat_detection_custom_module_async(request_type=dict) - - -def test_update_event_threat_detection_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - - request.event_threat_detection_custom_module.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'event_threat_detection_custom_module.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_event_threat_detection_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - - request.event_threat_detection_custom_module.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - await client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'event_threat_detection_custom_module.name=name_value', - ) in kw['metadata'] - - -def test_update_event_threat_detection_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_event_threat_detection_custom_module( - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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].event_threat_detection_custom_module - mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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_event_threat_detection_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_event_threat_detection_custom_module( - securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(), - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_event_threat_detection_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_event_threat_detection_custom_module( - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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].event_threat_detection_custom_module - mock_val = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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_event_threat_detection_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_event_threat_detection_custom_module( - securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(), - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_validate_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( - ) - response = client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) - - -def test_validate_event_threat_detection_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.validate_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - - -def test_validate_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest( - parent='parent_value', - raw_text='raw_text_value', - type_='type__value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.validate_event_threat_detection_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest( - parent='parent_value', - raw_text='raw_text_value', - type_='type__value', - ) - -def test_validate_event_threat_detection_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc - request = {} - client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.validate_event_threat_detection_custom_module(request) - - # Establish that a new wrapper 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_event_threat_detection_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( - )) - response = await client.validate_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - -@pytest.mark.asyncio -async def test_validate_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_event_threat_detection_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.validate_event_threat_detection_custom_module] = mock_object - - request = {} - await client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.validate_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_validate_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( - )) - response = await client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) - - -@pytest.mark.asyncio -async def test_validate_event_threat_detection_custom_module_async_from_dict(): - await test_validate_event_threat_detection_custom_module_async(request_type=dict) - - -def test_validate_event_threat_detection_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() - client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_validate_event_threat_detection_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse()) - await client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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", [ - securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_get_effective_event_threat_detection_custom_module(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( - name='name_value', - enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - ) - response = client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.enablement_state == effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_get_effective_event_threat_detection_custom_module_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_effective_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - - -def test_get_effective_event_threat_detection_custom_module_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_effective_event_threat_detection_custom_module(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest( - name='name_value', - ) - -def test_get_effective_event_threat_detection_custom_module_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_effective_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_effective_event_threat_detection_custom_module] = mock_rpc - request = {} - client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_effective_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_effective_event_threat_detection_custom_module_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( - name='name_value', - enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_effective_event_threat_detection_custom_module() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - -@pytest.mark.asyncio -async def test_get_effective_event_threat_detection_custom_module_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_effective_event_threat_detection_custom_module in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_effective_event_threat_detection_custom_module] = mock_object - - request = {} - await client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_effective_event_threat_detection_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_effective_event_threat_detection_custom_module_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( - name='name_value', - enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.enablement_state == effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_get_effective_event_threat_detection_custom_module_async_from_dict(): - await test_get_effective_event_threat_detection_custom_module_async(request_type=dict) - - -def test_get_effective_event_threat_detection_custom_module_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_effective_event_threat_detection_custom_module_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule()) - await client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_effective_event_threat_detection_custom_module_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_effective_event_threat_detection_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_effective_event_threat_detection_custom_module_flattened_error(): - client = SecurityCenterClient( - credentials=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_effective_event_threat_detection_custom_module( - securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_effective_event_threat_detection_custom_module_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_effective_event_threat_detection_custom_module), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_effective_event_threat_detection_custom_module( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_effective_event_threat_detection_custom_module_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_effective_event_threat_detection_custom_module( - securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, - dict, -]) -def test_list_effective_event_threat_detection_custom_modules(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEffectiveEventThreatDetectionCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_effective_event_threat_detection_custom_modules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_effective_event_threat_detection_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - - -def test_list_effective_event_threat_detection_custom_modules_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest( - 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_effective_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_effective_event_threat_detection_custom_modules(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_effective_event_threat_detection_custom_modules_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_effective_event_threat_detection_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_effective_event_threat_detection_custom_modules] = mock_rpc - request = {} - client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_effective_event_threat_detection_custom_modules_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_effective_event_threat_detection_custom_modules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - -@pytest.mark.asyncio -async def test_list_effective_event_threat_detection_custom_modules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_effective_event_threat_detection_custom_modules in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_effective_event_threat_detection_custom_modules] = mock_object - - request = {} - await client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_effective_event_threat_detection_custom_modules_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEffectiveEventThreatDetectionCustomModulesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_effective_event_threat_detection_custom_modules_async_from_dict(): - await test_list_effective_event_threat_detection_custom_modules_async(request_type=dict) - - -def test_list_effective_event_threat_detection_custom_modules_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_effective_event_threat_detection_custom_modules_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse()) - await client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_effective_event_threat_detection_custom_modules_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_effective_event_threat_detection_custom_modules( - 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_effective_event_threat_detection_custom_modules_flattened_error(): - client = SecurityCenterClient( - credentials=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_effective_event_threat_detection_custom_modules( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_effective_event_threat_detection_custom_modules_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_effective_event_threat_detection_custom_modules( - 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_effective_event_threat_detection_custom_modules_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_effective_event_threat_detection_custom_modules( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_effective_event_threat_detection_custom_modules_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_effective_event_threat_detection_custom_modules(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, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) - for i in results) -def test_list_effective_event_threat_detection_custom_modules_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_effective_event_threat_detection_custom_modules(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_effective_event_threat_detection_custom_modules_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_effective_event_threat_detection_custom_modules(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, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_effective_event_threat_detection_custom_modules_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_event_threat_detection_custom_modules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - ), - 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_effective_event_threat_detection_custom_modules(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", [ - securitycenter_service.BatchCreateResourceValueConfigsRequest, - dict, -]) -def test_batch_create_resource_value_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse( - ) - response = client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) - - -def test_batch_create_resource_value_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_create_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() - - -def test_batch_create_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.BatchCreateResourceValueConfigsRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_create_resource_value_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest( - parent='parent_value', - ) - -def test_batch_create_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc - request = {} - client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_resource_value_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_batch_create_resource_value_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( - )) - response = await client.batch_create_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() - -@pytest.mark.asyncio -async def test_batch_create_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.batch_create_resource_value_configs] = mock_object - - request = {} - await client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.batch_create_resource_value_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( - )) - response = await client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) - - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_async_from_dict(): - await test_batch_create_resource_value_configs_async(request_type=dict) - - -def test_batch_create_resource_value_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - client.batch_create_resource_value_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_batch_create_resource_value_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) - await client.batch_create_resource_value_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_batch_create_resource_value_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.batch_create_resource_value_configs( - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(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 - arg = args[0].requests - mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] - assert arg == mock_val - - -def test_batch_create_resource_value_configs_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_create_resource_value_configs( - securitycenter_service.BatchCreateResourceValueConfigsRequest(), - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], - ) - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_create_resource_value_configs( - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(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 - arg = args[0].requests - mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.batch_create_resource_value_configs( - securitycenter_service.BatchCreateResourceValueConfigsRequest(), - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteResourceValueConfigRequest, - dict, -]) -def test_delete_resource_value_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_resource_value_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() - - -def test_delete_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteResourceValueConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_resource_value_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest( - name='name_value', - ) - -def test_delete_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - request = {} - client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_resource_value_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_resource_value_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() - -@pytest.mark.asyncio -async def test_delete_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_resource_value_config] = mock_object - - request = {} - await client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_resource_value_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteResourceValueConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteResourceValueConfigRequest() - 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_resource_value_config_async_from_dict(): - await test_delete_resource_value_config_async(request_type=dict) - - -def test_delete_resource_value_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value = None - client.delete_resource_value_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_resource_value_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_resource_value_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_resource_value_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_config( - securitycenter_service.DeleteResourceValueConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_resource_value_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_resource_value_config( - securitycenter_service.DeleteResourceValueConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetResourceValueConfigRequest, - dict, -]) -def test_get_resource_value_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - response = client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -def test_get_resource_value_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetResourceValueConfigRequest() - - -def test_get_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetResourceValueConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_resource_value_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetResourceValueConfigRequest( - name='name_value', - ) - -def test_get_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc - request = {} - client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_resource_value_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_resource_value_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetResourceValueConfigRequest() - -@pytest.mark.asyncio -async def test_get_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_resource_value_config] = mock_object - - request = {} - await client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_resource_value_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetResourceValueConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -@pytest.mark.asyncio -async def test_get_resource_value_config_async_from_dict(): - await test_get_resource_value_config_async(request_type=dict) - - -def test_get_resource_value_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value = resource_value_config.ResourceValueConfig() - client.get_resource_value_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_resource_value_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) - await client.get_resource_value_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_resource_value_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resource_value_config.ResourceValueConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_resource_value_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_resource_value_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_config( - securitycenter_service.GetResourceValueConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_resource_value_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resource_value_config.ResourceValueConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_resource_value_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_resource_value_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_resource_value_config( - securitycenter_service.GetResourceValueConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListResourceValueConfigsRequest, - dict, -]) -def test_list_resource_value_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceValueConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_resource_value_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() - - -def test_list_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListResourceValueConfigsRequest( - 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_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_resource_value_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListResourceValueConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc - request = {} - client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_resource_value_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_resource_value_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() - -@pytest.mark.asyncio -async def test_list_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_resource_value_configs] = mock_object - - request = {} - await client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_resource_value_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListResourceValueConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceValueConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_resource_value_configs_async_from_dict(): - await test_list_resource_value_configs_async(request_type=dict) - - -def test_list_resource_value_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListResourceValueConfigsResponse() - client.list_resource_value_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_resource_value_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) - await client.list_resource_value_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_resource_value_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListResourceValueConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_resource_value_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_resource_value_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_configs( - securitycenter_service.ListResourceValueConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_resource_value_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListResourceValueConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_resource_value_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_resource_value_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_resource_value_configs( - securitycenter_service.ListResourceValueConfigsRequest(), - parent='parent_value', - ) - - -def test_list_resource_value_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_resource_value_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, resource_value_config.ResourceValueConfig) - for i in results) -def test_list_resource_value_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_resource_value_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_resource_value_configs_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_resource_value_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, resource_value_config.ResourceValueConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_resource_value_configs_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - 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_resource_value_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", [ - securitycenter_service.UpdateResourceValueConfigRequest, - dict, -]) -def test_update_resource_value_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - response = client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -def test_update_resource_value_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() - - -def test_update_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateResourceValueConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_resource_value_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest( - ) - -def test_update_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - request = {} - client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_resource_value_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_resource_value_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.update_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() - -@pytest.mark.asyncio -async def test_update_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_resource_value_config] = mock_object - - request = {} - await client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_resource_value_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateResourceValueConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -@pytest.mark.asyncio -async def test_update_resource_value_config_async_from_dict(): - await test_update_resource_value_config_async(request_type=dict) - - -def test_update_resource_value_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateResourceValueConfigRequest() - - request.resource_value_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value = gcs_resource_value_config.ResourceValueConfig() - client.update_resource_value_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', - 'resource_value_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_resource_value_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateResourceValueConfigRequest() - - request.resource_value_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) - await client.update_resource_value_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', - 'resource_value_config.name=name_value', - ) in kw['metadata'] - - -def test_update_resource_value_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_resource_value_config.ResourceValueConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_resource_value_config( - resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config - mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_config( - securitycenter_service.UpdateResourceValueConfigRequest(), - resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_resource_value_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_resource_value_config.ResourceValueConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_resource_value_config( - resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config - mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_resource_value_config( - securitycenter_service.UpdateResourceValueConfigRequest(), - resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListValuedResourcesRequest, - dict, -]) -def test_list_valued_resources(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListValuedResourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListValuedResourcesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_valued_resources_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_valued_resources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListValuedResourcesRequest() - - -def test_list_valued_resources_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListValuedResourcesRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_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_valued_resources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_valued_resources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListValuedResourcesRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_value', - order_by='order_by_value', - ) - -def test_list_valued_resources_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_valued_resources in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc - request = {} - client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_valued_resources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_valued_resources_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_valued_resources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListValuedResourcesRequest() - -@pytest.mark.asyncio -async def test_list_valued_resources_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_valued_resources in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_valued_resources] = mock_object - - request = {} - await client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_valued_resources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_valued_resources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListValuedResourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListValuedResourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListValuedResourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_valued_resources_async_from_dict(): - await test_list_valued_resources_async(request_type=dict) - - -def test_list_valued_resources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListValuedResourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - call.return_value = securitycenter_service.ListValuedResourcesResponse() - client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_valued_resources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListValuedResourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) - await client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_valued_resources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListValuedResourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_valued_resources( - 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_valued_resources_flattened_error(): - client = SecurityCenterClient( - credentials=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_valued_resources( - securitycenter_service.ListValuedResourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_valued_resources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListValuedResourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_valued_resources( - 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_valued_resources_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_valued_resources( - securitycenter_service.ListValuedResourcesRequest(), - parent='parent_value', - ) - - -def test_list_valued_resources_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_valued_resources(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, valued_resource.ValuedResource) - for i in results) -def test_list_valued_resources_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - RuntimeError, - ) - pages = list(client.list_valued_resources(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_valued_resources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_valued_resources(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, valued_resource.ValuedResource) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_valued_resources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - 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_valued_resources(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", [ - securitycenter_service.ListAttackPathsRequest, - dict, -]) -def test_list_attack_paths(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAttackPathsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttackPathsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_attack_paths_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_attack_paths() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAttackPathsRequest() - - -def test_list_attack_paths_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListAttackPathsRequest( - 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_attack_paths), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_attack_paths(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAttackPathsRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_value', - ) - -def test_list_attack_paths_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_attack_paths in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc - request = {} - client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_attack_paths(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_attack_paths_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_attack_paths() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAttackPathsRequest() - -@pytest.mark.asyncio -async def test_list_attack_paths_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_attack_paths in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_attack_paths] = mock_object - - request = {} - await client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_attack_paths(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_attack_paths_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAttackPathsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAttackPathsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttackPathsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_attack_paths_async_from_dict(): - await test_list_attack_paths_async(request_type=dict) - - -def test_list_attack_paths_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAttackPathsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - call.return_value = securitycenter_service.ListAttackPathsResponse() - client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_attack_paths_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAttackPathsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) - await client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_attack_paths_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAttackPathsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_attack_paths( - 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_attack_paths_flattened_error(): - client = SecurityCenterClient( - credentials=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_attack_paths( - securitycenter_service.ListAttackPathsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_attack_paths_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAttackPathsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_attack_paths( - 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_attack_paths_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_attack_paths( - securitycenter_service.ListAttackPathsRequest(), - parent='parent_value', - ) - - -def test_list_attack_paths_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_attack_paths(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, attack_path.AttackPath) - for i in results) -def test_list_attack_paths_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - RuntimeError, - ) - pages = list(client.list_attack_paths(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_attack_paths_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_attack_paths(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, attack_path.AttackPath) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_attack_paths_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - 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_attack_paths(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", [ - securitycenter_service.BulkMuteFindingsRequest, - dict, -]) -def test_bulk_mute_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') - - # 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 - response = client.bulk_mute_findings(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_bulk_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc - - request = {} - client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_rest_required_fields(request_type=securitycenter_service.BulkMuteFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).bulk_mute_findings._get_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()).bulk_mute_findings._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 = SecurityCenterClient( - 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.bulk_mute_findings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_bulk_mute_findings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.bulk_mute_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_bulk_mute_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_bulk_mute_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_bulk_mute_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.BulkMuteFindingsRequest.pb(securitycenter_service.BulkMuteFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = securitycenter_service.BulkMuteFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.bulk_mute_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_bulk_mute_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BulkMuteFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.bulk_mute_findings(request) - - -def test_bulk_mute_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.bulk_mute_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/v1/{parent=organizations/*}/findings:bulkMute" % client.transport._host, args[1]) - - -def test_bulk_mute_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.bulk_mute_findings( - securitycenter_service.BulkMuteFindingsRequest(), - parent='parent_value', - ) - - -def test_bulk_mute_findings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_create_security_health_analytics_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request_init["security_health_analytics_custom_module"] = {'name': 'name_value', 'display_name': 'display_name_value', 'enablement_state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_value', 'ancestor_module': 'ancestor_module_value', 'custom_config': {'predicate': {'expression': 'expression_value', 'title': 'title_value', 'description': 'description_value', 'location': 'location_value'}, 'custom_output': {'properties': [{'name': 'name_value', 'value_expression': {}}]}, 'resource_selector': {'resource_types': ['resource_types_value1', 'resource_types_value2']}, 'severity': 1, 'description': 'description_value', 'recommendation': 'recommendation_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 = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.meta.fields["security_health_analytics_custom_module"] - - 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["security_health_analytics_custom_module"].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["security_health_analytics_custom_module"][field])): - del request_init["security_health_analytics_custom_module"][field][i][subfield] - else: - del request_init["security_health_analytics_custom_module"][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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) - 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_security_health_analytics_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - -def test_create_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc - - request = {} - client.create_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_security_health_analytics_custom_module(request) - - # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_security_health_analytics_custom_module._get_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_security_health_analytics_custom_module._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) - 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_security_health_analytics_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_security_health_analytics_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_security_health_analytics_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "securityHealthAnalyticsCustomModule", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_security_health_analytics_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_security_health_analytics_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_security_health_analytics_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.to_json(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - - request = securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - client.create_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_security_health_analytics_custom_module(request) - - -def test_create_security_health_analytics_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(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_security_health_analytics_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules" % client.transport._host, args[1]) - - -def test_create_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_health_analytics_custom_module( - securitycenter_service.CreateSecurityHealthAnalyticsCustomModuleRequest(), - parent='parent_value', - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - ) - - -def test_create_security_health_analytics_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.CreateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_source(request) - - -def test_create_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_create_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -def test_create_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request_init["finding"] = {'name': 'name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_value', 'mute': 1, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True, 'exploit_release_date': {}}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'mute_info': {'static_mute': {'state': 1, 'apply_time': {}}, 'dynamic_mute_records': [{'mute_config': 'mute_config_value', 'match_time': {}}]}, 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.create_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.create_finding] = mock_rpc - - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["finding_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 "findingId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "findingId" in jsonified_request - assert jsonified_request["findingId"] == request_init["finding_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["findingId"] = 'finding_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request - assert jsonified_request["findingId"] == 'finding_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.create_finding(request) - - expected_params = [ - ( - "findingId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.CreateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_finding(request) - - -def test_create_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(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 = gcs_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.create_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/v1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) - - -def test_create_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_create_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateMuteConfigRequest, - dict, -]) -def test_create_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["mute_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'type_': 1, 'expiry_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 = securitycenter_service.CreateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): - del request_init["mute_config"][field][i][subfield] - else: - del request_init["mute_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 = gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - -def test_create_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - - request = {} - client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.CreateMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["mute_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 "muteConfigId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "muteConfigId" in jsonified_request - assert jsonified_request["muteConfigId"] == request_init["mute_config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["muteConfigId"] = 'mute_config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("mute_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 "muteConfigId" in jsonified_request - assert jsonified_request["muteConfigId"] == 'mute_config_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - expected_params = [ - ( - "muteConfigId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("muteConfigId", )) & set(("parent", "muteConfig", "muteConfigId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_mute_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_mute_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateMuteConfigRequest.pb(securitycenter_service.CreateMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) - - request = securitycenter_service.CreateMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_mute_config.MuteConfig() - - client.create_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_mute_config(request) - - -def test_create_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_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 = gcs_mute_config.MuteConfig.pb(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_mute_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=organizations/*}/muteConfigs" % client.transport._host, args[1]) - - -def test_create_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.CreateMuteConfigRequest(), - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_id_value', - ) - - -def test_create_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateNotificationConfigRequest, - dict, -]) -def test_create_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["notification_config"] = {'name': 'name_value', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.CreateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): - del request_init["notification_config"][field][i][subfield] - else: - del request_init["notification_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 = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.CreateNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["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 "configId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "configId" in jsonified_request - assert jsonified_request["configId"] == request_init["config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["configId"] = 'config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("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 "configId" in jsonified_request - assert jsonified_request["configId"] == 'config_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ( - "configId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("configId", )) & set(("parent", "configId", "notificationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateNotificationConfigRequest.pb(securitycenter_service.CreateNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) - - request = securitycenter_service.CreateNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_notification_config.NotificationConfig() - - client.create_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_notification_config(request) - - -def test_create_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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=organizations/*}/notificationConfigs" % client.transport._host, args[1]) - - -def test_create_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - -def test_create_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteMuteConfigRequest, - dict, -]) -def test_delete_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/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 = 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - - request = {} - client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.DeleteMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( - 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_mute_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_mute_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteMuteConfigRequest.pb(securitycenter_service.DeleteMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_mute_config(request) - - -def test_delete_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/muteConfigs/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_mute_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=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.DeleteMuteConfigRequest(), - name='name_value', - ) - - -def test_delete_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteNotificationConfigRequest, - dict, -]) -def test_delete_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/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 = 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_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.DeleteNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_notification_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteNotificationConfigRequest.pb(securitycenter_service.DeleteNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_notification_config(request) - - -def test_delete_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/notificationConfigs/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_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=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -def test_delete_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_delete_security_health_analytics_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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 = 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_security_health_analytics_custom_module(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_security_health_analytics_custom_module] = mock_rpc - - request = {} - client.delete_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_security_health_analytics_custom_module(request) - - # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - 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_security_health_analytics_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_security_health_analytics_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_security_health_analytics_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_security_health_analytics_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_security_health_analytics_custom_module") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_security_health_analytics_custom_module(request) - - -def test_delete_security_health_analytics_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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_security_health_analytics_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings/customModules/*}" % client.transport._host, args[1]) - - -def test_delete_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_health_analytics_custom_module( - securitycenter_service.DeleteSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - - -def test_delete_security_health_analytics_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSimulationRequest, - dict, -]) -def test_get_simulation_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = simulation.Simulation.pb(return_value) - 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_simulation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, simulation.Simulation) - assert response.name == 'name_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - -def test_get_simulation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_simulation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc - - request = {} - client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_simulation(request) - - # Establish 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_simulation_rest_required_fields(request_type=securitycenter_service.GetSimulationRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_simulation._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_simulation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = simulation.Simulation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = simulation.Simulation.pb(return_value) - 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_simulation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_simulation_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_simulation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_simulation_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_simulation") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_simulation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSimulationRequest.pb(securitycenter_service.GetSimulationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = simulation.Simulation.to_json(simulation.Simulation()) - - request = securitycenter_service.GetSimulationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = simulation.Simulation() - - client.get_simulation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_simulation_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSimulationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_simulation(request) - - -def test_get_simulation_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = simulation.Simulation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation.pb(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_simulation(**mock_args) - - # Establish that the underlying call 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=organizations/*/simulations/*}" % client.transport._host, args[1]) - - -def test_get_simulation_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_simulation( - securitycenter_service.GetSimulationRequest(), - name='name_value', - ) - - -def test_get_simulation_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetValuedResourceRequest, - dict, -]) -def test_get_valued_resource_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = valued_resource.ValuedResource.pb(return_value) - 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_valued_resource(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, valued_resource.ValuedResource) - assert response.name == 'name_value' - assert response.resource == 'resource_value' - assert response.resource_type == 'resource_type_value' - assert response.display_name == 'display_name_value' - assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW - assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) - -def test_get_valued_resource_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_valued_resource in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc - - request = {} - client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_valued_resource(request) - - # Establish 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_valued_resource_rest_required_fields(request_type=securitycenter_service.GetValuedResourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_valued_resource._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_valued_resource._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = valued_resource.ValuedResource() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = valued_resource.ValuedResource.pb(return_value) - 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_valued_resource(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_valued_resource_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_valued_resource._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_valued_resource_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_valued_resource") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_valued_resource") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetValuedResourceRequest.pb(securitycenter_service.GetValuedResourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = valued_resource.ValuedResource.to_json(valued_resource.ValuedResource()) - - request = securitycenter_service.GetValuedResourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = valued_resource.ValuedResource() - - client.get_valued_resource(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_valued_resource_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetValuedResourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_valued_resource(request) - - -def test_get_valued_resource_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = valued_resource.ValuedResource() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource.pb(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_valued_resource(**mock_args) - - # Establish that the underlying call 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=organizations/*/simulations/*/valuedResources/*}" % client.transport._host, args[1]) - - -def test_get_valued_resource_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_valued_resource( - securitycenter_service.GetValuedResourceRequest(), - name='name_value', - ) - - -def test_get_valued_resource_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetBigQueryExportRequest, - dict, -]) -def test_get_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/bigQueryExports/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 = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - -def test_get_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc - - request = {} - client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.GetBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_big_query_export") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_big_query_export") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetBigQueryExportRequest.pb(securitycenter_service.GetBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) - - request = securitycenter_service.GetBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = bigquery_export.BigQueryExport() - - client.get_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/bigQueryExports/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_big_query_export(request) - - -def test_get_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/bigQueryExports/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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) - - # Establish that the underlying call 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=organizations/*/bigQueryExports/*}" % client.transport._host, args[1]) - - -def test_get_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.GetBigQueryExportRequest(), - name='name_value', - ) - - -def test_get_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.get_iam_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/v1/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetMuteConfigRequest, - dict, -]) -def test_get_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=mute_config.MuteConfig.MuteConfigType.STATIC, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC - -def test_get_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_mute_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_mute_config] = mock_rpc - - request = {} - client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.GetMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = mute_config.MuteConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_mute_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_mute_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetMuteConfigRequest.pb(securitycenter_service.GetMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = mute_config.MuteConfig.to_json(mute_config.MuteConfig()) - - request = securitycenter_service.GetMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = mute_config.MuteConfig() - - client.get_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_mute_config(request) - - -def test_get_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = mute_config.MuteConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig.pb(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_mute_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=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) - - -def test_get_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.GetMuteConfigRequest(), - name='name_value', - ) - - -def test_get_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetNotificationConfigRequest, - dict, -]) -def test_get_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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_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_notification_config] = mock_rpc - - request = {} - client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.GetNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetNotificationConfigRequest.pb(securitycenter_service.GetNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = notification_config.NotificationConfig.to_json(notification_config.NotificationConfig()) - - request = securitycenter_service.GetNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = notification_config.NotificationConfig() - - client.get_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_notification_config(request) - - -def test_get_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig.pb(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_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=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_get_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -def test_get_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetOrganizationSettingsRequest, - dict, -]) -def test_get_organization_settings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/organizationSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_organization_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_organization_settings] = mock_rpc - - request = {} - client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.GetOrganizationSettingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_organization_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_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_organization_settings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_organization_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_organization_settings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_organization_settings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_organization_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetOrganizationSettingsRequest.pb(securitycenter_service.GetOrganizationSettingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = organization_settings.OrganizationSettings.to_json(organization_settings.OrganizationSettings()) - - request = securitycenter_service.GetOrganizationSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = organization_settings.OrganizationSettings() - - client.get_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/organizationSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_organization_settings(request) - - -def test_get_organization_settings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/organizationSettings'} - - # get truthy value for each flattened field - mock_args = dict( - 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 = organization_settings.OrganizationSettings.pb(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_organization_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/v1/{name=organizations/*/organizationSettings}" % client.transport._host, args[1]) - - -def test_get_organization_settings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -def test_get_organization_settings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_get_effective_security_health_analytics_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/effectiveCustomModules/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 = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule( - name='name_value', - enablement_state=effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - display_name='display_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(return_value) - 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_effective_security_health_analytics_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.enablement_state == effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.display_name == 'display_name_value' - -def test_get_effective_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_effective_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_effective_security_health_analytics_custom_module] = mock_rpc - - request = {} - client.get_effective_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_effective_security_health_analytics_custom_module(request) - - # Establish 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_effective_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_effective_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_effective_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(return_value) - 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_effective_security_health_analytics_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_effective_security_health_analytics_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_effective_security_health_analytics_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_effective_security_health_analytics_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_effective_security_health_analytics_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_effective_security_health_analytics_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.to_json(effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule()) - - request = securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - - client.get_effective_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_effective_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/effectiveCustomModules/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_effective_security_health_analytics_custom_module(request) - - -def test_get_effective_security_health_analytics_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/effectiveCustomModules/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 = effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule.pb(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_effective_security_health_analytics_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings/effectiveCustomModules/*}" % client.transport._host, args[1]) - - -def test_get_effective_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_effective_security_health_analytics_custom_module( - securitycenter_service.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - - -def test_get_effective_security_health_analytics_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_get_security_health_analytics_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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 = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) - 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_security_health_analytics_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - -def test_get_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_security_health_analytics_custom_module] = mock_rpc - - request = {} - client.get_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_security_health_analytics_custom_module(request) - - # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_security_health_analytics_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) - 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_security_health_analytics_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_security_health_analytics_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_security_health_analytics_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_security_health_analytics_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_security_health_analytics_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_security_health_analytics_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.to_json(security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - - request = securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - client.get_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_security_health_analytics_custom_module(request) - - -def test_get_security_health_analytics_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/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 = security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(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_security_health_analytics_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings/customModules/*}" % client.transport._host, args[1]) - - -def test_get_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_health_analytics_custom_module( - securitycenter_service.GetSecurityHealthAnalyticsCustomModuleRequest(), - name='name_value', - ) - - -def test_get_security_health_analytics_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/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 = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = source.Source.to_json(source.Source()) - - request = securitycenter_service.GetSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = source.Source() - - client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_source(request) - - -def test_get_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v1/{name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_get_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -def test_get_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupAssetsRequest, - dict, -]) -def test_group_assets_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_group_assets_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc - - request = {} - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_group_assets_rest_required_fields(request_type=securitycenter_service.GroupAssetsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupAssetsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_assets_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_assets_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_assets") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupAssetsRequest.pb(securitycenter_service.GroupAssetsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupAssetsResponse.to_json(securitycenter_service.GroupAssetsResponse()) - - request = securitycenter_service.GroupAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupAssetsResponse() - - client.group_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_assets(request) - - -def test_group_assets_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupAssetsResponse.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': 'organizations/sample1'} - - pager = client.group_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_findings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_findings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_findings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) - - request = securitycenter_service.GroupFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupFindingsResponse() - - client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_findings(request) - - -def test_group_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - group_by='group_by_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v1/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) - - -def test_group_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} - - pager = client.group_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_findings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListAssetsRequest, - dict, -]) -def test_list_assets_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListAssetsResponse.pb(return_value) - 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_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_list_assets_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc - - request = {} - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_assets(request) - - # Establish 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_assets_rest_required_fields(request_type=securitycenter_service.ListAssetsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_assets._get_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_assets._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) - jsonified_request.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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAssetsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListAssetsResponse.pb(return_value) - 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_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_assets_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_assets_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_assets") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListAssetsRequest.pb(securitycenter_service.ListAssetsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListAssetsResponse.to_json(securitycenter_service.ListAssetsResponse()) - - request = securitycenter_service.ListAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListAssetsResponse() - - client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_assets(request) - - -def test_list_assets_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListAssetsResponse.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': 'organizations/sample1'} - - pager = client.list_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) - - pages = list(client.list_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, - dict, -]) -def test_list_descendant_security_health_analytics_custom_modules_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) - 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_descendant_security_health_analytics_custom_modules(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_descendant_security_health_analytics_custom_modules_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_descendant_security_health_analytics_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_descendant_security_health_analytics_custom_modules] = mock_rpc - - request = {} - client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_descendant_security_health_analytics_custom_modules(request) - - # Establish 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_descendant_security_health_analytics_custom_modules_rest_required_fields(request_type=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_descendant_security_health_analytics_custom_modules._get_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_descendant_security_health_analytics_custom_modules._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) - 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_descendant_security_health_analytics_custom_modules(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_descendant_security_health_analytics_custom_modules_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_descendant_security_health_analytics_custom_modules._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_descendant_security_health_analytics_custom_modules_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_descendant_security_health_analytics_custom_modules") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_descendant_security_health_analytics_custom_modules") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.pb(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.to_json(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse()) - - request = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - - client.list_descendant_security_health_analytics_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_descendant_security_health_analytics_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_descendant_security_health_analytics_custom_modules(request) - - -def test_list_descendant_security_health_analytics_custom_modules_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - - # 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 = securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.pb(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_descendant_security_health_analytics_custom_modules(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules:listDescendant" % client.transport._host, args[1]) - - -def test_list_descendant_security_health_analytics_custom_modules_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_descendant_security_health_analytics_custom_modules( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_descendant_security_health_analytics_custom_modules_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListDescendantSecurityHealthAnalyticsCustomModulesResponse.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': 'organizations/sample1/securityHealthAnalyticsSettings'} - - pager = client.list_descendant_security_health_analytics_custom_modules(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - for i in results) - - pages = list(client.list_descendant_security_health_analytics_custom_modules(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.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' - assert response.total_size == 1086 - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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=securitycenter_service.ListFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) - jsonified_request.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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.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 = securitycenter_service.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 = [ - ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) - - request = securitycenter_service.ListFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListFindingsResponse() - - client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_findings(request) - - -def test_list_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} - - pager = client.list_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) - 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 - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListMuteConfigsRequest, - dict, -]) -def test_list_mute_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) - 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_mute_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMuteConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_mute_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_mute_configs] = mock_rpc - - request = {} - client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_mute_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_mute_configs_rest_required_fields(request_type=securitycenter_service.ListMuteConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListMuteConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) - 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_mute_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_mute_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_mute_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_mute_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_mute_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_mute_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListMuteConfigsRequest.pb(securitycenter_service.ListMuteConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListMuteConfigsResponse.to_json(securitycenter_service.ListMuteConfigsResponse()) - - request = securitycenter_service.ListMuteConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListMuteConfigsResponse() - - client.list_mute_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_mute_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListMuteConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_mute_configs(request) - - -def test_list_mute_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListMuteConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse.pb(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_mute_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=organizations/*}/muteConfigs" % client.transport._host, args[1]) - - -def test_list_mute_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_configs( - securitycenter_service.ListMuteConfigsRequest(), - parent='parent_value', - ) - - -def test_list_mute_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListMuteConfigsResponse.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': 'organizations/sample1'} - - pager = client.list_mute_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, mute_config.MuteConfig) - for i in results) - - pages = list(client.list_mute_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListNotificationConfigsRequest, - dict, -]) -def test_list_notification_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) - 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_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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_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_notification_configs] = mock_rpc - - request = {} - client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_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_notification_configs_rest_required_fields(request_type=securitycenter_service.ListNotificationConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListNotificationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) - 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_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_notification_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_notification_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_notification_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_notification_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_notification_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListNotificationConfigsRequest.pb(securitycenter_service.ListNotificationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListNotificationConfigsResponse.to_json(securitycenter_service.ListNotificationConfigsResponse()) - - request = securitycenter_service.ListNotificationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListNotificationConfigsResponse() - - client.list_notification_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_notification_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_notification_configs(request) - - -def test_list_notification_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListNotificationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse.pb(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_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=organizations/*}/notificationConfigs" % client.transport._host, args[1]) - - -def test_list_notification_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListNotificationConfigsResponse.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': 'organizations/sample1'} - - pager = client.list_notification_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, notification_config.NotificationConfig) - for i in results) - - pages = list(client.list_notification_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, - dict, -]) -def test_list_effective_security_health_analytics_custom_modules_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) - 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_effective_security_health_analytics_custom_modules(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_effective_security_health_analytics_custom_modules_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_effective_security_health_analytics_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_effective_security_health_analytics_custom_modules] = mock_rpc - - request = {} - client.list_effective_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_effective_security_health_analytics_custom_modules(request) - - # Establish 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_effective_security_health_analytics_custom_modules_rest_required_fields(request_type=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_effective_security_health_analytics_custom_modules._get_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_effective_security_health_analytics_custom_modules._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) - 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_effective_security_health_analytics_custom_modules(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_effective_security_health_analytics_custom_modules_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_effective_security_health_analytics_custom_modules._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_effective_security_health_analytics_custom_modules_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_effective_security_health_analytics_custom_modules") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_effective_security_health_analytics_custom_modules") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest.pb(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.to_json(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse()) - - request = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - - client.list_effective_security_health_analytics_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_effective_security_health_analytics_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_effective_security_health_analytics_custom_modules(request) - - -def test_list_effective_security_health_analytics_custom_modules_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - - # 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 = securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.pb(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_effective_security_health_analytics_custom_modules(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/effectiveCustomModules" % client.transport._host, args[1]) - - -def test_list_effective_security_health_analytics_custom_modules_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_effective_security_health_analytics_custom_modules( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_effective_security_health_analytics_custom_modules_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse( - effective_security_health_analytics_custom_modules=[ - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse.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': 'organizations/sample1/securityHealthAnalyticsSettings'} - - pager = client.list_effective_security_health_analytics_custom_modules(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, effective_security_health_analytics_custom_module.EffectiveSecurityHealthAnalyticsCustomModule) - for i in results) - - pages = list(client.list_effective_security_health_analytics_custom_modules(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest, - dict, -]) -def test_list_security_health_analytics_custom_modules_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) - 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_security_health_analytics_custom_modules(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSecurityHealthAnalyticsCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_security_health_analytics_custom_modules_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_security_health_analytics_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_security_health_analytics_custom_modules] = mock_rpc - - request = {} - client.list_security_health_analytics_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_security_health_analytics_custom_modules(request) - - # Establish 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_security_health_analytics_custom_modules_rest_required_fields(request_type=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_security_health_analytics_custom_modules._get_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_security_health_analytics_custom_modules._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(return_value) - 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_security_health_analytics_custom_modules(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_security_health_analytics_custom_modules_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_security_health_analytics_custom_modules._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_security_health_analytics_custom_modules_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_security_health_analytics_custom_modules") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_security_health_analytics_custom_modules") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest.pb(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.to_json(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse()) - - request = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - - client.list_security_health_analytics_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_security_health_analytics_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_security_health_analytics_custom_modules(request) - - -def test_list_security_health_analytics_custom_modules_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - - # 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 = securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.pb(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_security_health_analytics_custom_modules(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules" % client.transport._host, args[1]) - - -def test_list_security_health_analytics_custom_modules_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_health_analytics_custom_modules( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_security_health_analytics_custom_modules_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse( - security_health_analytics_custom_modules=[ - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListSecurityHealthAnalyticsCustomModulesResponse.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': 'organizations/sample1/securityHealthAnalyticsSettings'} - - pager = client.list_security_health_analytics_custom_modules(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - for i in results) - - pages = list(client.list_security_health_analytics_custom_modules(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_sources_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_sources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_sources_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) - - request = securitycenter_service.ListSourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListSourcesResponse() - - client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_sources(request) - - -def test_list_sources_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v1/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_list_sources_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} - - pager = client.list_sources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, source.Source) - for i in results) - - pages = list(client.list_sources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.RunAssetDiscoveryRequest, - dict, -]) -def test_run_asset_discovery_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') - - # 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 - response = client.run_asset_discovery(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_run_asset_discovery_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.run_asset_discovery in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc - - request = {} - client.run_asset_discovery(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.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_run_asset_discovery_rest_required_fields(request_type=securitycenter_service.RunAssetDiscoveryRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_asset_discovery._get_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()).run_asset_discovery._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 = SecurityCenterClient( - 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.run_asset_discovery(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_run_asset_discovery_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.run_asset_discovery._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_run_asset_discovery_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_run_asset_discovery") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_run_asset_discovery") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.RunAssetDiscoveryRequest.pb(securitycenter_service.RunAssetDiscoveryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = securitycenter_service.RunAssetDiscoveryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.run_asset_discovery(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_run_asset_discovery_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.run_asset_discovery(request) - - -def test_run_asset_discovery_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.run_asset_discovery(**mock_args) - - # Establish that the underlying call 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=organizations/*}/assets:runDiscovery" % client.transport._host, args[1]) - - -def test_run_asset_discovery_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -def test_run_asset_discovery_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # 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 - response = client.set_finding_state(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( - 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': "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 = 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.set_finding_state(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_finding_state_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_finding_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "state", "startTime", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_finding_state_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = finding.Finding.to_json(finding.Finding()) - - request = securitycenter_service.SetFindingStateRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_finding_state(request) - - -def test_set_finding_state_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - mock_args.update(sample_request) - - # 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.set_finding_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/v1/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) - - -def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -def test_set_finding_state_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetMuteRequest, - dict, -]) -def test_set_mute_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # 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 - response = client.set_mute(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_set_mute_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_mute in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc - - request = {} - client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_mute(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_set_mute_rest_required_fields(request_type=securitycenter_service.SetMuteRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - 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': "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 = 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.set_mute(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_mute_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_mute._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "mute", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_mute_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_mute") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_mute") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SetMuteRequest.pb(securitycenter_service.SetMuteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = finding.Finding.to_json(finding.Finding()) - - request = securitycenter_service.SetMuteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.set_mute(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_mute_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetMuteRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_mute(request) - - -def test_set_mute_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - mock_args.update(sample_request) - - # 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.set_mute(**mock_args) - - # Establish that the underlying call 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=organizations/*/sources/*/findings/*}:setMute" % client.transport._host, args[1]) - - -def test_set_mute_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_mute( - securitycenter_service.SetMuteRequest(), - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - -def test_set_mute_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.set_iam_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/v1/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # 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 - response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_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.test_iam_permissions(**mock_args) - - # Establish that the underlying call 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/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_simulate_security_health_analytics_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.simulate_security_health_analytics_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse) - -def test_simulate_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.simulate_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.simulate_security_health_analytics_custom_module] = mock_rpc - - request = {} - client.simulate_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.simulate_security_health_analytics_custom_module(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_simulate_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).simulate_security_health_analytics_custom_module._get_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()).simulate_security_health_analytics_custom_module._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.simulate_security_health_analytics_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_simulate_security_health_analytics_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.simulate_security_health_analytics_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "customConfig", "resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_simulate_security_health_analytics_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_simulate_security_health_analytics_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_simulate_security_health_analytics_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.to_json(securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse()) - - request = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - - client.simulate_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_simulate_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.simulate_security_health_analytics_custom_module(request) - - -def test_simulate_security_health_analytics_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/securityHealthAnalyticsSettings'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), - resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleResponse.pb(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.simulate_security_health_analytics_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/securityHealthAnalyticsSettings}/customModules:simulate" % client.transport._host, args[1]) - - -def test_simulate_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.simulate_security_health_analytics_custom_module( - securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest(), - parent='parent_value', - custom_config=security_health_analytics_custom_config.CustomConfig(predicate=expr_pb2.Expr(expression='expression_value')), - resource=securitycenter_service.SimulateSecurityHealthAnalyticsCustomModuleRequest.SimulatedResource(resource_type='resource_type_value'), - ) - - -def test_simulate_security_health_analytics_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateExternalSystemRequest, - dict, -]) -def test_update_external_system_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} - request_init["external_system"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4', 'assignees': ['assignees_value1', 'assignees_value2'], 'external_uid': 'external_uid_value', 'status': 'status_value', 'external_system_update_time': {'seconds': 751, 'nanos': 543}, 'case_uri': 'case_uri_value', 'case_priority': 'case_priority_value', 'case_sla': {}, 'case_create_time': {}, 'case_close_time': {}, 'ticket_info': {'id': 'id_value', 'assignee': 'assignee_value', 'description': 'description_value', 'uri': 'uri_value', 'status': 'status_value', 'update_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 = securitycenter_service.UpdateExternalSystemRequest.meta.fields["external_system"] - - 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["external_system"].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["external_system"][field])): - del request_init["external_system"][field][i][subfield] - else: - del request_init["external_system"][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 = gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_external_system.ExternalSystem.pb(return_value) - 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_external_system(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_external_system.ExternalSystem) - assert response.name == 'name_value' - assert response.assignees == ['assignees_value'] - assert response.external_uid == 'external_uid_value' - assert response.status == 'status_value' - assert response.case_uri == 'case_uri_value' - assert response.case_priority == 'case_priority_value' - -def test_update_external_system_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_external_system in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc - - request = {} - client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_external_system(request) - - # Establish 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_external_system_rest_required_fields(request_type=securitycenter_service.UpdateExternalSystemRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_external_system._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_external_system._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_external_system.ExternalSystem() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_external_system.ExternalSystem.pb(return_value) - 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_external_system(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_external_system_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_external_system._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("externalSystem", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_external_system_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_external_system") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_external_system") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateExternalSystemRequest.pb(securitycenter_service.UpdateExternalSystemRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_external_system.ExternalSystem.to_json(gcs_external_system.ExternalSystem()) - - request = securitycenter_service.UpdateExternalSystemRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_external_system.ExternalSystem() - - client.update_external_system(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_external_system_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateExternalSystemRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_external_system(request) - - -def test_update_external_system_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_external_system.ExternalSystem() - - # get arguments that satisfy an http rule for this method - sample_request = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - external_system=gcs_external_system.ExternalSystem(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 = gcs_external_system.ExternalSystem.pb(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_external_system(**mock_args) - - # Establish that the underlying call 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/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}" % client.transport._host, args[1]) - - -def test_update_external_system_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_external_system( - securitycenter_service.UpdateExternalSystemRequest(), - external_system=gcs_external_system.ExternalSystem(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_external_system_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_value', 'mute': 1, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True, 'exploit_release_date': {}}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'mute_info': {'static_mute': {'state': 1, 'apply_time': {}}, 'dynamic_mute_records': [{'mute_config': 'mute_config_value', 'match_time': {}}]}, 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.update_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.update_finding] = mock_rpc - - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_finding._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_finding._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.update_finding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.UpdateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_finding(request) - - -def test_update_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - finding=gcs_finding.Finding(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 = gcs_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.update_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/v1/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) - - -def test_update_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_update_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateMuteConfigRequest, - dict, -]) -def test_update_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} - request_init["mute_config"] = {'name': 'organizations/sample1/muteConfigs/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'type_': 1, 'expiry_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 = securitycenter_service.UpdateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): - del request_init["mute_config"][field][i][subfield] - else: - del request_init["mute_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 = gcs_mute_config.MuteConfig( - name='name_value', - display_name='display_name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - -def test_update_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - - request = {} - client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.UpdateMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_mute_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_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("muteConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_mute_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_mute_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateMuteConfigRequest.pb(securitycenter_service.UpdateMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) - - request = securitycenter_service.UpdateMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_mute_config.MuteConfig() - - client.update_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_mute_config(request) - - -def test_update_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - mute_config=gcs_mute_config.MuteConfig(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 = gcs_mute_config.MuteConfig.pb(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_mute_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/{mute_config.name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) - - -def test_update_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.UpdateMuteConfigRequest(), - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateNotificationConfigRequest, - dict, -]) -def test_update_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} - request_init["notification_config"] = {'name': 'organizations/sample1/notificationConfigs/sample2', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.UpdateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): - del request_init["notification_config"][field][i][subfield] - else: - del request_init["notification_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 = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.UpdateNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("notificationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateNotificationConfigRequest.pb(securitycenter_service.UpdateNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) - - request = securitycenter_service.UpdateNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_notification_config.NotificationConfig() - - client.update_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_notification_config(request) - - -def test_update_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/{notification_config.name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_update_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateOrganizationSettingsRequest, - dict, -]) -def test_update_organization_settings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - request_init["organization_settings"] = {'name': 'organizations/sample1/organizationSettings', 'enable_asset_discovery': True, 'asset_discovery_config': {'project_ids': ['project_ids_value1', 'project_ids_value2'], 'inclusion_mode': 1, 'folder_ids': ['folder_ids_value1', 'folder_ids_value2']}} - # The version of a generated dependency at test runtime may differ from the version used 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 = securitycenter_service.UpdateOrganizationSettingsRequest.meta.fields["organization_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["organization_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["organization_settings"][field])): - del request_init["organization_settings"][field][i][subfield] - else: - del request_init["organization_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 = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_organization_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_organization_settings] = mock_rpc - - request = {} - client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_organization_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_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_organization_settings.OrganizationSettings() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_organization_settings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_organization_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("organizationSettings", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_organization_settings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_organization_settings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_organization_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateOrganizationSettingsRequest.pb(securitycenter_service.UpdateOrganizationSettingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_organization_settings.OrganizationSettings.to_json(gcs_organization_settings.OrganizationSettings()) - - request = securitycenter_service.UpdateOrganizationSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_organization_settings.OrganizationSettings() - - client.update_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_organization_settings(request) - - -def test_update_organization_settings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_organization_settings.OrganizationSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - - # get truthy value for each flattened field - mock_args = dict( - organization_settings=gcs_organization_settings.OrganizationSettings(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 = gcs_organization_settings.OrganizationSettings.pb(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_organization_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/v1/{organization_settings.name=organizations/*/organizationSettings}" % client.transport._host, args[1]) - - -def test_update_organization_settings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -def test_update_organization_settings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest, - dict, -]) -def test_update_security_health_analytics_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'security_health_analytics_custom_module': {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'}} - request_init["security_health_analytics_custom_module"] = {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2', 'display_name': 'display_name_value', 'enablement_state': 1, 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_value', 'ancestor_module': 'ancestor_module_value', 'custom_config': {'predicate': {'expression': 'expression_value', 'title': 'title_value', 'description': 'description_value', 'location': 'location_value'}, 'custom_output': {'properties': [{'name': 'name_value', 'value_expression': {}}]}, 'resource_selector': {'resource_types': ['resource_types_value1', 'resource_types_value2']}, 'severity': 1, 'description': 'description_value', 'recommendation': 'recommendation_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 = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.meta.fields["security_health_analytics_custom_module"] - - 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["security_health_analytics_custom_module"].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["security_health_analytics_custom_module"][field])): - del request_init["security_health_analytics_custom_module"][field][i][subfield] - else: - del request_init["security_health_analytics_custom_module"][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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule( - name='name_value', - display_name='display_name_value', - enablement_state=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED, - last_editor='last_editor_value', - ancestor_module='ancestor_module_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) - 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_security_health_analytics_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.enablement_state == gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.EnablementState.ENABLED - assert response.last_editor == 'last_editor_value' - assert response.ancestor_module == 'ancestor_module_value' - -def test_update_security_health_analytics_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_health_analytics_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_health_analytics_custom_module] = mock_rpc - - request = {} - client.update_security_health_analytics_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_health_analytics_custom_module(request) - - # Establish 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_security_health_analytics_custom_module_rest_required_fields(request_type=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_security_health_analytics_custom_module._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_security_health_analytics_custom_module._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(return_value) - 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_security_health_analytics_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_security_health_analytics_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_security_health_analytics_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("securityHealthAnalyticsCustomModule", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_security_health_analytics_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_health_analytics_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_health_analytics_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest.pb(securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.to_json(gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule()) - - request = securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - client.update_security_health_analytics_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_security_health_analytics_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'security_health_analytics_custom_module': {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_security_health_analytics_custom_module(request) - - -def test_update_security_health_analytics_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'security_health_analytics_custom_module': {'name': 'organizations/sample1/securityHealthAnalyticsSettings/customModules/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(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 = gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule.pb(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_security_health_analytics_custom_module(**mock_args) - - # Establish that the underlying call 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/{security_health_analytics_custom_module.name=organizations/*/securityHealthAnalyticsSettings/customModules/*}" % client.transport._host, args[1]) - - -def test_update_security_health_analytics_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_health_analytics_custom_module( - securitycenter_service.UpdateSecurityHealthAnalyticsCustomModuleRequest(), - security_health_analytics_custom_module=gcs_security_health_analytics_custom_module.SecurityHealthAnalyticsCustomModule(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_security_health_analytics_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.UpdateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_source(request) - - -def test_update_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_update_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - - -def test_update_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - request_init["security_marks"] = {'name': 'organizations/sample1/assets/sample2/securityMarks', 'marks': {}, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] - - 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["security_marks"].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["security_marks"][field])): - del request_init["security_marks"][field][i][subfield] - else: - del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - -def test_update_security_marks_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_security_marks._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_security_marks._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("start_time", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_security_marks_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_security_marks._get_unset_required_fields({}) - assert set(unset_fields) == (set(("startTime", "updateMask", )) & set(("securityMarks", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_security_marks_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) - - request = securitycenter_service.UpdateSecurityMarksRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_security_marks.SecurityMarks() - - client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_security_marks(request) - - -def test_update_security_marks_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - - # get arguments that satisfy an http rule for this method - sample_request = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - - # get truthy value for each flattened field - mock_args = dict( - security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) - - # Establish that the underlying call 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/{security_marks.name=organizations/*/assets/*/securityMarks}" % client.transport._host, args[1]) - - -def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - -def test_update_security_marks_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateBigQueryExportRequest, - dict, -]) -def test_create_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["big_query_export"] = {'name': 'name_value', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.CreateBigQueryExportRequest.meta.fields["big_query_export"] - - 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["big_query_export"].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["big_query_export"][field])): - del request_init["big_query_export"][field][i][subfield] - else: - del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - -def test_create_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - - request = {} - client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.CreateBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["big_query_export_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 "bigQueryExportId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "bigQueryExportId" in jsonified_request - assert jsonified_request["bigQueryExportId"] == request_init["big_query_export_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["bigQueryExportId"] = 'big_query_export_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("big_query_export_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 "bigQueryExportId" in jsonified_request - assert jsonified_request["bigQueryExportId"] == 'big_query_export_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - expected_params = [ - ( - "bigQueryExportId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(("bigQueryExportId", )) & set(("parent", "bigQueryExport", "bigQueryExportId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_big_query_export") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_big_query_export") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateBigQueryExportRequest.pb(securitycenter_service.CreateBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) - - request = securitycenter_service.CreateBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = bigquery_export.BigQueryExport() - - client.create_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_big_query_export(request) - - -def test_create_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) - - # Establish that the underlying call 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=organizations/*}/bigQueryExports" % client.transport._host, args[1]) - - -def test_create_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.CreateBigQueryExportRequest(), - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_id_value', - ) - - -def test_create_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteBigQueryExportRequest, - dict, -]) -def test_delete_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/bigQueryExports/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 = 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - - request = {} - client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.DeleteBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - 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_big_query_export(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_big_query_export") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteBigQueryExportRequest.pb(securitycenter_service.DeleteBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/bigQueryExports/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_big_query_export(request) - - -def test_delete_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/bigQueryExports/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_big_query_export(**mock_args) - - # Establish that the underlying call 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=organizations/*/bigQueryExports/*}" % client.transport._host, args[1]) - - -def test_delete_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.DeleteBigQueryExportRequest(), - name='name_value', - ) - - -def test_delete_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateBigQueryExportRequest, - dict, -]) -def test_update_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'big_query_export': {'name': 'organizations/sample1/bigQueryExports/sample2'}} - request_init["big_query_export"] = {'name': 'organizations/sample1/bigQueryExports/sample2', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.UpdateBigQueryExportRequest.meta.fields["big_query_export"] - - 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["big_query_export"].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["big_query_export"][field])): - del request_init["big_query_export"][field][i][subfield] - else: - del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - -def test_update_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc - - request = {} - client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.UpdateBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_big_query_export._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_big_query_export._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("bigQueryExport", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_big_query_export") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_big_query_export") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateBigQueryExportRequest.pb(securitycenter_service.UpdateBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) - - request = securitycenter_service.UpdateBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = bigquery_export.BigQueryExport() - - client.update_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'big_query_export': {'name': 'organizations/sample1/bigQueryExports/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_big_query_export(request) - - -def test_update_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - - # get arguments that satisfy an http rule for this method - sample_request = {'big_query_export': {'name': 'organizations/sample1/bigQueryExports/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - big_query_export=bigquery_export.BigQueryExport(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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) - - # Establish that the underlying call 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/{big_query_export.name=organizations/*/bigQueryExports/*}" % client.transport._host, args[1]) - - -def test_update_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.UpdateBigQueryExportRequest(), - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListBigQueryExportsRequest, - dict, -]) -def test_list_big_query_exports_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) - 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_big_query_exports(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryExportsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_big_query_exports_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_big_query_exports in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc - - request = {} - client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_big_query_exports(request) - - # Establish 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_big_query_exports_rest_required_fields(request_type=securitycenter_service.ListBigQueryExportsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_big_query_exports._get_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_big_query_exports._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListBigQueryExportsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) - 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_big_query_exports(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_big_query_exports_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_big_query_exports._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_big_query_exports_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_big_query_exports") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_big_query_exports") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListBigQueryExportsRequest.pb(securitycenter_service.ListBigQueryExportsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListBigQueryExportsResponse.to_json(securitycenter_service.ListBigQueryExportsResponse()) - - request = securitycenter_service.ListBigQueryExportsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListBigQueryExportsResponse() - - client.list_big_query_exports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_big_query_exports_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListBigQueryExportsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_big_query_exports(request) - - -def test_list_big_query_exports_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListBigQueryExportsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse.pb(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_big_query_exports(**mock_args) - - # Establish that the underlying call 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=organizations/*}/bigQueryExports" % client.transport._host, args[1]) - - -def test_list_big_query_exports_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_exports( - securitycenter_service.ListBigQueryExportsRequest(), - parent='parent_value', - ) - - -def test_list_big_query_exports_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListBigQueryExportsResponse.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': 'organizations/sample1'} - - pager = client.list_big_query_exports(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, bigquery_export.BigQueryExport) - for i in results) - - pages = list(client.list_big_query_exports(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_create_event_threat_detection_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request_init["event_threat_detection_custom_module"] = {'name': 'name_value', 'config': {'fields': {}}, 'ancestor_module': 'ancestor_module_value', 'enablement_state': 1, 'type_': 'type__value', 'display_name': 'display_name_value', 'description': 'description_value', 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_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 = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.meta.fields["event_threat_detection_custom_module"] - - 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["event_threat_detection_custom_module"].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["event_threat_detection_custom_module"][field])): - del request_init["event_threat_detection_custom_module"][field][i][subfield] - else: - del request_init["event_threat_detection_custom_module"][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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) - 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_event_threat_detection_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - -def test_create_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc - - request = {} - client.create_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_event_threat_detection_custom_module(request) - - # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_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_event_threat_detection_custom_module._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) - 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_event_threat_detection_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_event_threat_detection_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_event_threat_detection_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "eventThreatDetectionCustomModule", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_event_threat_detection_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_event_threat_detection_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_event_threat_detection_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.CreateEventThreatDetectionCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.to_json(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - - request = securitycenter_service.CreateEventThreatDetectionCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - client.create_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateEventThreatDetectionCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_event_threat_detection_custom_module(request) - - -def test_create_event_threat_detection_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(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_event_threat_detection_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/customModules" % client.transport._host, args[1]) - - -def test_create_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_event_threat_detection_custom_module( - securitycenter_service.CreateEventThreatDetectionCustomModuleRequest(), - parent='parent_value', - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - ) - - -def test_create_event_threat_detection_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_delete_event_threat_detection_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/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 = 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_event_threat_detection_custom_module(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc - - request = {} - client.delete_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_event_threat_detection_custom_module(request) - - # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - 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_event_threat_detection_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_event_threat_detection_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_event_threat_detection_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_event_threat_detection_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_event_threat_detection_custom_module") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_event_threat_detection_custom_module(request) - - -def test_delete_event_threat_detection_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/eventThreatDetectionSettings/customModules/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_event_threat_detection_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings/customModules/*}" % client.transport._host, args[1]) - - -def test_delete_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_event_threat_detection_custom_module( - securitycenter_service.DeleteEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - - -def test_delete_event_threat_detection_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_get_event_threat_detection_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/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 = event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) - 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_event_threat_detection_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - -def test_get_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_event_threat_detection_custom_module] = mock_rpc - - request = {} - client.get_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_event_threat_detection_custom_module(request) - - # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.GetEventThreatDetectionCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) - 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_event_threat_detection_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_event_threat_detection_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_event_threat_detection_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_event_threat_detection_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_event_threat_detection_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_event_threat_detection_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.GetEventThreatDetectionCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = event_threat_detection_custom_module.EventThreatDetectionCustomModule.to_json(event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - - request = securitycenter_service.GetEventThreatDetectionCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - client.get_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetEventThreatDetectionCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_event_threat_detection_custom_module(request) - - -def test_get_event_threat_detection_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/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 = event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(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_event_threat_detection_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings/customModules/*}" % client.transport._host, args[1]) - - -def test_get_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_event_threat_detection_custom_module( - securitycenter_service.GetEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - - -def test_get_event_threat_detection_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest, - dict, -]) -def test_list_descendant_event_threat_detection_custom_modules_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(return_value) - 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_descendant_event_threat_detection_custom_modules(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDescendantEventThreatDetectionCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_descendant_event_threat_detection_custom_modules_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_descendant_event_threat_detection_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_descendant_event_threat_detection_custom_modules] = mock_rpc - - request = {} - client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_descendant_event_threat_detection_custom_modules(request) - - # Establish 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_descendant_event_threat_detection_custom_modules_rest_required_fields(request_type=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_descendant_event_threat_detection_custom_modules._get_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_descendant_event_threat_detection_custom_modules._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(return_value) - 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_descendant_event_threat_detection_custom_modules(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_descendant_event_threat_detection_custom_modules_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_descendant_event_threat_detection_custom_modules._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_descendant_event_threat_detection_custom_modules_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_descendant_event_threat_detection_custom_modules") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_descendant_event_threat_detection_custom_modules") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest.pb(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.to_json(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse()) - - request = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - - client.list_descendant_event_threat_detection_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_descendant_event_threat_detection_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_descendant_event_threat_detection_custom_modules(request) - - -def test_list_descendant_event_threat_detection_custom_modules_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - - # 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 = securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.pb(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_descendant_event_threat_detection_custom_modules(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/customModules:listDescendant" % client.transport._host, args[1]) - - -def test_list_descendant_event_threat_detection_custom_modules_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_descendant_event_threat_detection_custom_modules( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_descendant_event_threat_detection_custom_modules_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListDescendantEventThreatDetectionCustomModulesResponse.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': 'organizations/sample1/eventThreatDetectionSettings'} - - pager = client.list_descendant_event_threat_detection_custom_modules(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - for i in results) - - pages = list(client.list_descendant_event_threat_detection_custom_modules(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListEventThreatDetectionCustomModulesRequest, - dict, -]) -def test_list_event_threat_detection_custom_modules_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(return_value) - 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_event_threat_detection_custom_modules(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEventThreatDetectionCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_event_threat_detection_custom_modules_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_event_threat_detection_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_event_threat_detection_custom_modules] = mock_rpc - - request = {} - client.list_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_event_threat_detection_custom_modules(request) - - # Establish 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_event_threat_detection_custom_modules_rest_required_fields(request_type=securitycenter_service.ListEventThreatDetectionCustomModulesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_event_threat_detection_custom_modules._get_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_event_threat_detection_custom_modules._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(return_value) - 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_event_threat_detection_custom_modules(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_event_threat_detection_custom_modules_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_event_threat_detection_custom_modules._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_event_threat_detection_custom_modules_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_event_threat_detection_custom_modules") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_event_threat_detection_custom_modules") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListEventThreatDetectionCustomModulesRequest.pb(securitycenter_service.ListEventThreatDetectionCustomModulesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.to_json(securitycenter_service.ListEventThreatDetectionCustomModulesResponse()) - - request = securitycenter_service.ListEventThreatDetectionCustomModulesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - - client.list_event_threat_detection_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_event_threat_detection_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListEventThreatDetectionCustomModulesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_event_threat_detection_custom_modules(request) - - -def test_list_event_threat_detection_custom_modules_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEventThreatDetectionCustomModulesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - - # 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 = securitycenter_service.ListEventThreatDetectionCustomModulesResponse.pb(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_event_threat_detection_custom_modules(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/customModules" % client.transport._host, args[1]) - - -def test_list_event_threat_detection_custom_modules_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_event_threat_detection_custom_modules( - securitycenter_service.ListEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_event_threat_detection_custom_modules_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEventThreatDetectionCustomModulesResponse( - event_threat_detection_custom_modules=[ - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - event_threat_detection_custom_module.EventThreatDetectionCustomModule(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListEventThreatDetectionCustomModulesResponse.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': 'organizations/sample1/eventThreatDetectionSettings'} - - pager = client.list_event_threat_detection_custom_modules(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, event_threat_detection_custom_module.EventThreatDetectionCustomModule) - for i in results) - - pages = list(client.list_event_threat_detection_custom_modules(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_update_event_threat_detection_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'event_threat_detection_custom_module': {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'}} - request_init["event_threat_detection_custom_module"] = {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2', 'config': {'fields': {}}, 'ancestor_module': 'ancestor_module_value', 'enablement_state': 1, 'type_': 'type__value', 'display_name': 'display_name_value', 'description': 'description_value', 'update_time': {'seconds': 751, 'nanos': 543}, 'last_editor': 'last_editor_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 = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.meta.fields["event_threat_detection_custom_module"] - - 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["event_threat_detection_custom_module"].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["event_threat_detection_custom_module"][field])): - del request_init["event_threat_detection_custom_module"][field][i][subfield] - else: - del request_init["event_threat_detection_custom_module"][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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule( - name='name_value', - ancestor_module='ancestor_module_value', - enablement_state=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - last_editor='last_editor_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) - 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_event_threat_detection_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.ancestor_module == 'ancestor_module_value' - assert response.enablement_state == gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.last_editor == 'last_editor_value' - -def test_update_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_event_threat_detection_custom_module] = mock_rpc - - request = {} - client.update_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_event_threat_detection_custom_module(request) - - # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_event_threat_detection_custom_module._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_event_threat_detection_custom_module._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(return_value) - 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_event_threat_detection_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_event_threat_detection_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_event_threat_detection_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("eventThreatDetectionCustomModule", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_event_threat_detection_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_event_threat_detection_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_event_threat_detection_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.to_json(gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule()) - - request = securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - client.update_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'event_threat_detection_custom_module': {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_event_threat_detection_custom_module(request) - - -def test_update_event_threat_detection_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'event_threat_detection_custom_module': {'name': 'organizations/sample1/eventThreatDetectionSettings/customModules/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(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 = gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule.pb(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_event_threat_detection_custom_module(**mock_args) - - # Establish that the underlying call 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/{event_threat_detection_custom_module.name=organizations/*/eventThreatDetectionSettings/customModules/*}" % client.transport._host, args[1]) - - -def test_update_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_event_threat_detection_custom_module( - securitycenter_service.UpdateEventThreatDetectionCustomModuleRequest(), - event_threat_detection_custom_module=gcs_event_threat_detection_custom_module.EventThreatDetectionCustomModule(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_event_threat_detection_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_validate_event_threat_detection_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.pb(return_value) - 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_event_threat_detection_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse) - -def test_validate_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_event_threat_detection_custom_module] = mock_rpc - - request = {} - client.validate_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.validate_event_threat_detection_custom_module(request) - - # Establish 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_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["raw_text"] = "" - request_init["type_"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["rawText"] = 'raw_text_value' - jsonified_request["type"] = 'type__value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).validate_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "rawText" in jsonified_request - assert jsonified_request["rawText"] == 'raw_text_value' - assert "type" in jsonified_request - assert jsonified_request["type"] == 'type__value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.pb(return_value) - 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_event_threat_detection_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_validate_event_threat_detection_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.validate_event_threat_detection_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "rawText", "type", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_validate_event_threat_detection_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_validate_event_threat_detection_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_validate_event_threat_detection_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse.to_json(securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse()) - - request = securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ValidateEventThreatDetectionCustomModuleResponse() - - client.validate_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_validate_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ValidateEventThreatDetectionCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.validate_event_threat_detection_custom_module(request) - - -def test_validate_event_threat_detection_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest, - dict, -]) -def test_get_effective_event_threat_detection_custom_module_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/effectiveCustomModules/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 = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule( - name='name_value', - enablement_state=effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED, - type_='type__value', - display_name='display_name_value', - description='description_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(return_value) - 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_effective_event_threat_detection_custom_module(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) - assert response.name == 'name_value' - assert response.enablement_state == effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.EnablementState.ENABLED - assert response.type_ == 'type__value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - -def test_get_effective_event_threat_detection_custom_module_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_effective_event_threat_detection_custom_module in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_effective_event_threat_detection_custom_module] = mock_rpc - - request = {} - client.get_effective_event_threat_detection_custom_module(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_effective_event_threat_detection_custom_module(request) - - # Establish 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_effective_event_threat_detection_custom_module_rest_required_fields(request_type=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_effective_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_effective_event_threat_detection_custom_module._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(return_value) - 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_effective_event_threat_detection_custom_module(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_effective_event_threat_detection_custom_module_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_effective_event_threat_detection_custom_module._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_effective_event_threat_detection_custom_module_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_effective_event_threat_detection_custom_module") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_effective_event_threat_detection_custom_module") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest.pb(securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.to_json(effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule()) - - request = securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - - client.get_effective_event_threat_detection_custom_module(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_effective_event_threat_detection_custom_module_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/eventThreatDetectionSettings/effectiveCustomModules/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_effective_event_threat_detection_custom_module(request) - - -def test_get_effective_event_threat_detection_custom_module_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/eventThreatDetectionSettings/effectiveCustomModules/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 = effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule.pb(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_effective_event_threat_detection_custom_module(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings/effectiveCustomModules/*}" % client.transport._host, args[1]) - - -def test_get_effective_event_threat_detection_custom_module_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_effective_event_threat_detection_custom_module( - securitycenter_service.GetEffectiveEventThreatDetectionCustomModuleRequest(), - name='name_value', - ) - - -def test_get_effective_event_threat_detection_custom_module_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest, - dict, -]) -def test_list_effective_event_threat_detection_custom_modules_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(return_value) - 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_effective_event_threat_detection_custom_modules(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEffectiveEventThreatDetectionCustomModulesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_effective_event_threat_detection_custom_modules_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_effective_event_threat_detection_custom_modules in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_effective_event_threat_detection_custom_modules] = mock_rpc - - request = {} - client.list_effective_event_threat_detection_custom_modules(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_effective_event_threat_detection_custom_modules(request) - - # Establish 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_effective_event_threat_detection_custom_modules_rest_required_fields(request_type=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_effective_event_threat_detection_custom_modules._get_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_effective_event_threat_detection_custom_modules._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(return_value) - 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_effective_event_threat_detection_custom_modules(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_effective_event_threat_detection_custom_modules_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_effective_event_threat_detection_custom_modules._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_effective_event_threat_detection_custom_modules_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_effective_event_threat_detection_custom_modules") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_effective_event_threat_detection_custom_modules") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest.pb(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.to_json(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse()) - - request = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - - client.list_effective_event_threat_detection_custom_modules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_effective_event_threat_detection_custom_modules_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_effective_event_threat_detection_custom_modules(request) - - -def test_list_effective_event_threat_detection_custom_modules_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/eventThreatDetectionSettings'} - - # 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 = securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.pb(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_effective_event_threat_detection_custom_modules(**mock_args) - - # Establish that the underlying call 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=organizations/*/eventThreatDetectionSettings}/effectiveCustomModules" % client.transport._host, args[1]) - - -def test_list_effective_event_threat_detection_custom_modules_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_effective_event_threat_detection_custom_modules( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesRequest(), - parent='parent_value', - ) - - -def test_list_effective_event_threat_detection_custom_modules_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='abc', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[], - next_page_token='def', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse( - effective_event_threat_detection_custom_modules=[ - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListEffectiveEventThreatDetectionCustomModulesResponse.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': 'organizations/sample1/eventThreatDetectionSettings'} - - pager = client.list_effective_event_threat_detection_custom_modules(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, effective_event_threat_detection_custom_module.EffectiveEventThreatDetectionCustomModule) - for i in results) - - pages = list(client.list_effective_event_threat_detection_custom_modules(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.BatchCreateResourceValueConfigsRequest, - dict, -]) -def test_batch_create_resource_value_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.BatchCreateResourceValueConfigsResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) - -def test_batch_create_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc - - request = {} - client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_resource_value_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_batch_create_resource_value_configs_rest_required_fields(request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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()).batch_create_resource_value_configs._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_create_resource_value_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_create_resource_value_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_resource_value_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_batch_create_resource_value_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_batch_create_resource_value_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(securitycenter_service.BatchCreateResourceValueConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.BatchCreateResourceValueConfigsResponse.to_json(securitycenter_service.BatchCreateResourceValueConfigsResponse()) - - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - - client.batch_create_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_create_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_create_resource_value_configs(request) - - -def test_batch_create_resource_value_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(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.batch_create_resource_value_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=organizations/*}/resourceValueConfigs:batchCreate" % client.transport._host, args[1]) - - -def test_batch_create_resource_value_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_create_resource_value_configs( - securitycenter_service.BatchCreateResourceValueConfigsRequest(), - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], - ) - - -def test_batch_create_resource_value_configs_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteResourceValueConfigRequest, - dict, -]) -def test_delete_resource_value_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = 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_resource_value_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - - request = {} - client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.DeleteResourceValueConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( - 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_resource_value_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_resource_value_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_resource_value_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_resource_value_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_resource_value_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteResourceValueConfigRequest.pb(securitycenter_service.DeleteResourceValueConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteResourceValueConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteResourceValueConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_resource_value_config(request) - - -def test_delete_resource_value_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/resourceValueConfigs/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_resource_value_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=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_resource_value_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_config( - securitycenter_service.DeleteResourceValueConfigRequest(), - name='name_value', - ) - - -def test_delete_resource_value_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetResourceValueConfigRequest, - dict, -]) -def test_get_resource_value_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - -def test_get_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc - - request = {} - client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.GetResourceValueConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resource_value_config.ResourceValueConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_resource_value_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_resource_value_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_resource_value_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_resource_value_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_resource_value_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetResourceValueConfigRequest.pb(securitycenter_service.GetResourceValueConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resource_value_config.ResourceValueConfig.to_json(resource_value_config.ResourceValueConfig()) - - request = securitycenter_service.GetResourceValueConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resource_value_config.ResourceValueConfig() - - client.get_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetResourceValueConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_resource_value_config(request) - - -def test_get_resource_value_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resource_value_config.ResourceValueConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig.pb(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_resource_value_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=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) - - -def test_get_resource_value_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_config( - securitycenter_service.GetResourceValueConfigRequest(), - name='name_value', - ) - - -def test_get_resource_value_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListResourceValueConfigsRequest, - dict, -]) -def test_list_resource_value_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceValueConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc - - request = {} - client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_resource_value_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_resource_value_configs_rest_required_fields(request_type=securitycenter_service.ListResourceValueConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListResourceValueConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_resource_value_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_resource_value_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_resource_value_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_resource_value_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_resource_value_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListResourceValueConfigsRequest.pb(securitycenter_service.ListResourceValueConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListResourceValueConfigsResponse.to_json(securitycenter_service.ListResourceValueConfigsResponse()) - - request = securitycenter_service.ListResourceValueConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListResourceValueConfigsResponse() - - client.list_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListResourceValueConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_resource_value_configs(request) - - -def test_list_resource_value_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListResourceValueConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse.pb(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_resource_value_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=organizations/*}/resourceValueConfigs" % client.transport._host, args[1]) - - -def test_list_resource_value_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_configs( - securitycenter_service.ListResourceValueConfigsRequest(), - parent='parent_value', - ) - - -def test_list_resource_value_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListResourceValueConfigsResponse.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': 'organizations/sample1'} - - pager = client.list_resource_value_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resource_value_config.ResourceValueConfig) - for i in results) - - pages = list(client.list_resource_value_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateResourceValueConfigRequest, - dict, -]) -def test_update_resource_value_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} - request_init["resource_value_config"] = {'name': 'organizations/sample1/resourceValueConfigs/sample2', 'resource_value': 1, 'tag_values': ['tag_values_value1', 'tag_values_value2'], 'resource_type': 'resource_type_value', 'scope': 'scope_value', 'resource_labels_selector': {}, 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'cloud_provider': 1, 'sensitive_data_protection_mapping': {'high_sensitivity_mapping': 1, 'medium_sensitivity_mapping': 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 = securitycenter_service.UpdateResourceValueConfigRequest.meta.fields["resource_value_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["resource_value_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["resource_value_config"][field])): - del request_init["resource_value_config"][field][i][subfield] - else: - del request_init["resource_value_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 = gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - -def test_update_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - - request = {} - client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.UpdateResourceValueConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_resource_value_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_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_resource_value_config.ResourceValueConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_resource_value_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_resource_value_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("resourceValueConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_resource_value_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_resource_value_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_resource_value_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateResourceValueConfigRequest.pb(securitycenter_service.UpdateResourceValueConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_resource_value_config.ResourceValueConfig.to_json(gcs_resource_value_config.ResourceValueConfig()) - - request = securitycenter_service.UpdateResourceValueConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_resource_value_config.ResourceValueConfig() - - client.update_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateResourceValueConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_resource_value_config(request) - - -def test_update_resource_value_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_resource_value_config.ResourceValueConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - resource_value_config=gcs_resource_value_config.ResourceValueConfig(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 = gcs_resource_value_config.ResourceValueConfig.pb(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_resource_value_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/{resource_value_config.name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) - - -def test_update_resource_value_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_config( - securitycenter_service.UpdateResourceValueConfigRequest(), - resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_resource_value_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListValuedResourcesRequest, - dict, -]) -def test_list_valued_resources_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) - 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_valued_resources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListValuedResourcesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_list_valued_resources_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_valued_resources in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc - - request = {} - client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_valued_resources(request) - - # Establish 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_valued_resources_rest_required_fields(request_type=securitycenter_service.ListValuedResourcesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_valued_resources._get_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_valued_resources._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListValuedResourcesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) - 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_valued_resources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_valued_resources_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_valued_resources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_valued_resources_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_valued_resources") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_valued_resources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListValuedResourcesRequest.pb(securitycenter_service.ListValuedResourcesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListValuedResourcesResponse.to_json(securitycenter_service.ListValuedResourcesResponse()) - - request = securitycenter_service.ListValuedResourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListValuedResourcesResponse() - - client.list_valued_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_valued_resources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListValuedResourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_valued_resources(request) - - -def test_list_valued_resources_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListValuedResourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse.pb(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_valued_resources(**mock_args) - - # Establish that the underlying call 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=organizations/*/simulations/*}/valuedResources" % client.transport._host, args[1]) - - -def test_list_valued_resources_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_valued_resources( - securitycenter_service.ListValuedResourcesRequest(), - parent='parent_value', - ) - - -def test_list_valued_resources_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListValuedResourcesResponse.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': 'organizations/sample1/simulations/sample2'} - - pager = client.list_valued_resources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, valued_resource.ValuedResource) - for i in results) - - pages = list(client.list_valued_resources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListAttackPathsRequest, - dict, -]) -def test_list_attack_paths_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) - 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_attack_paths(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttackPathsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_attack_paths_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_attack_paths in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc - - request = {} - client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_attack_paths(request) - - # Establish 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_attack_paths_rest_required_fields(request_type=securitycenter_service.ListAttackPathsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_attack_paths._get_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_attack_paths._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAttackPathsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) - 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_attack_paths(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_attack_paths_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_attack_paths._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_attack_paths_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_attack_paths") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_attack_paths") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListAttackPathsRequest.pb(securitycenter_service.ListAttackPathsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListAttackPathsResponse.to_json(securitycenter_service.ListAttackPathsResponse()) - - request = securitycenter_service.ListAttackPathsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListAttackPathsResponse() - - client.list_attack_paths(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_attack_paths_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAttackPathsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_attack_paths(request) - - -def test_list_attack_paths_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAttackPathsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse.pb(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_attack_paths(**mock_args) - - # Establish that the underlying call 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=organizations/*/simulations/*}/attackPaths" % client.transport._host, args[1]) - - -def test_list_attack_paths_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_attack_paths( - securitycenter_service.ListAttackPathsRequest(), - parent='parent_value', - ) - - -def test_list_attack_paths_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListAttackPathsResponse.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': 'organizations/sample1/simulations/sample2'} - - pager = client.list_attack_paths(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, attack_path.AttackPath) - for i in results) - - pages = list(client.list_attack_paths(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.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SecurityCenterClient( - 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 = SecurityCenterClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SecurityCenterClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SecurityCenterClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SecurityCenterGrpcTransport, - ) - -def test_security_center_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_security_center_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.securitycenter_v1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'bulk_mute_findings', - 'create_security_health_analytics_custom_module', - 'create_source', - 'create_finding', - 'create_mute_config', - 'create_notification_config', - 'delete_mute_config', - 'delete_notification_config', - 'delete_security_health_analytics_custom_module', - 'get_simulation', - 'get_valued_resource', - 'get_big_query_export', - 'get_iam_policy', - 'get_mute_config', - 'get_notification_config', - 'get_organization_settings', - 'get_effective_security_health_analytics_custom_module', - 'get_security_health_analytics_custom_module', - 'get_source', - 'group_assets', - 'group_findings', - 'list_assets', - 'list_descendant_security_health_analytics_custom_modules', - 'list_findings', - 'list_mute_configs', - 'list_notification_configs', - 'list_effective_security_health_analytics_custom_modules', - 'list_security_health_analytics_custom_modules', - 'list_sources', - 'run_asset_discovery', - 'set_finding_state', - 'set_mute', - 'set_iam_policy', - 'test_iam_permissions', - 'simulate_security_health_analytics_custom_module', - 'update_external_system', - 'update_finding', - 'update_mute_config', - 'update_notification_config', - 'update_organization_settings', - 'update_security_health_analytics_custom_module', - 'update_source', - 'update_security_marks', - 'create_big_query_export', - 'delete_big_query_export', - 'update_big_query_export', - 'list_big_query_exports', - 'create_event_threat_detection_custom_module', - 'delete_event_threat_detection_custom_module', - 'get_event_threat_detection_custom_module', - 'list_descendant_event_threat_detection_custom_modules', - 'list_event_threat_detection_custom_modules', - 'update_event_threat_detection_custom_module', - 'validate_event_threat_detection_custom_module', - 'get_effective_event_threat_detection_custom_module', - 'list_effective_event_threat_detection_custom_modules', - 'batch_create_resource_value_configs', - 'delete_resource_value_config', - 'get_resource_value_config', - 'list_resource_value_configs', - 'update_resource_value_config', - 'list_valued_resources', - 'list_attack_paths', - '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_security_center_base_transport_with_credentials_file(): - # Instantiate the 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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - 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_security_center_base_transport_with_adc(): - # Test the default 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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport() - adc.assert_called_once() - - -def test_security_center_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) - SecurityCenterClient() - 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -def test_security_center_transport_auth_adc(transport_class): - # If 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, - ], -) -def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), - (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_security_center_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host 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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_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.SecurityCenterRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_security_center_rest_lro_client(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a 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 - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_no_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_with_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_security_center_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SecurityCenterClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SecurityCenterClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.bulk_mute_findings._session - session2 = client2.transport.bulk_mute_findings._session - assert session1 != session2 - session1 = client1.transport.create_security_health_analytics_custom_module._session - session2 = client2.transport.create_security_health_analytics_custom_module._session - assert session1 != session2 - session1 = client1.transport.create_source._session - session2 = client2.transport.create_source._session - assert session1 != session2 - session1 = client1.transport.create_finding._session - session2 = client2.transport.create_finding._session - assert session1 != session2 - session1 = client1.transport.create_mute_config._session - session2 = client2.transport.create_mute_config._session - assert session1 != session2 - session1 = client1.transport.create_notification_config._session - session2 = client2.transport.create_notification_config._session - assert session1 != session2 - session1 = client1.transport.delete_mute_config._session - session2 = client2.transport.delete_mute_config._session - assert session1 != session2 - session1 = client1.transport.delete_notification_config._session - session2 = client2.transport.delete_notification_config._session - assert session1 != session2 - session1 = client1.transport.delete_security_health_analytics_custom_module._session - session2 = client2.transport.delete_security_health_analytics_custom_module._session - assert session1 != session2 - session1 = client1.transport.get_simulation._session - session2 = client2.transport.get_simulation._session - assert session1 != session2 - session1 = client1.transport.get_valued_resource._session - session2 = client2.transport.get_valued_resource._session - assert session1 != session2 - session1 = client1.transport.get_big_query_export._session - session2 = client2.transport.get_big_query_export._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.get_mute_config._session - session2 = client2.transport.get_mute_config._session - assert session1 != session2 - session1 = client1.transport.get_notification_config._session - session2 = client2.transport.get_notification_config._session - assert session1 != session2 - session1 = client1.transport.get_organization_settings._session - session2 = client2.transport.get_organization_settings._session - assert session1 != session2 - session1 = client1.transport.get_effective_security_health_analytics_custom_module._session - session2 = client2.transport.get_effective_security_health_analytics_custom_module._session - assert session1 != session2 - session1 = client1.transport.get_security_health_analytics_custom_module._session - session2 = client2.transport.get_security_health_analytics_custom_module._session - assert session1 != session2 - session1 = client1.transport.get_source._session - session2 = client2.transport.get_source._session - assert session1 != session2 - session1 = client1.transport.group_assets._session - session2 = client2.transport.group_assets._session - assert session1 != session2 - session1 = client1.transport.group_findings._session - session2 = client2.transport.group_findings._session - assert session1 != session2 - session1 = client1.transport.list_assets._session - session2 = client2.transport.list_assets._session - assert session1 != session2 - session1 = client1.transport.list_descendant_security_health_analytics_custom_modules._session - session2 = client2.transport.list_descendant_security_health_analytics_custom_modules._session - assert session1 != session2 - session1 = client1.transport.list_findings._session - session2 = client2.transport.list_findings._session - assert session1 != session2 - session1 = client1.transport.list_mute_configs._session - session2 = client2.transport.list_mute_configs._session - assert session1 != session2 - session1 = client1.transport.list_notification_configs._session - session2 = client2.transport.list_notification_configs._session - assert session1 != session2 - session1 = client1.transport.list_effective_security_health_analytics_custom_modules._session - session2 = client2.transport.list_effective_security_health_analytics_custom_modules._session - assert session1 != session2 - session1 = client1.transport.list_security_health_analytics_custom_modules._session - session2 = client2.transport.list_security_health_analytics_custom_modules._session - assert session1 != session2 - session1 = client1.transport.list_sources._session - session2 = client2.transport.list_sources._session - assert session1 != session2 - session1 = client1.transport.run_asset_discovery._session - session2 = client2.transport.run_asset_discovery._session - assert session1 != session2 - session1 = client1.transport.set_finding_state._session - session2 = client2.transport.set_finding_state._session - assert session1 != session2 - session1 = client1.transport.set_mute._session - session2 = client2.transport.set_mute._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 - session1 = client1.transport.simulate_security_health_analytics_custom_module._session - session2 = client2.transport.simulate_security_health_analytics_custom_module._session - assert session1 != session2 - session1 = client1.transport.update_external_system._session - session2 = client2.transport.update_external_system._session - assert session1 != session2 - session1 = client1.transport.update_finding._session - session2 = client2.transport.update_finding._session - assert session1 != session2 - session1 = client1.transport.update_mute_config._session - session2 = client2.transport.update_mute_config._session - assert session1 != session2 - session1 = client1.transport.update_notification_config._session - session2 = client2.transport.update_notification_config._session - assert session1 != session2 - session1 = client1.transport.update_organization_settings._session - session2 = client2.transport.update_organization_settings._session - assert session1 != session2 - session1 = client1.transport.update_security_health_analytics_custom_module._session - session2 = client2.transport.update_security_health_analytics_custom_module._session - assert session1 != session2 - session1 = client1.transport.update_source._session - session2 = client2.transport.update_source._session - assert session1 != session2 - session1 = client1.transport.update_security_marks._session - session2 = client2.transport.update_security_marks._session - assert session1 != session2 - session1 = client1.transport.create_big_query_export._session - session2 = client2.transport.create_big_query_export._session - assert session1 != session2 - session1 = client1.transport.delete_big_query_export._session - session2 = client2.transport.delete_big_query_export._session - assert session1 != session2 - session1 = client1.transport.update_big_query_export._session - session2 = client2.transport.update_big_query_export._session - assert session1 != session2 - session1 = client1.transport.list_big_query_exports._session - session2 = client2.transport.list_big_query_exports._session - assert session1 != session2 - session1 = client1.transport.create_event_threat_detection_custom_module._session - session2 = client2.transport.create_event_threat_detection_custom_module._session - assert session1 != session2 - session1 = client1.transport.delete_event_threat_detection_custom_module._session - session2 = client2.transport.delete_event_threat_detection_custom_module._session - assert session1 != session2 - session1 = client1.transport.get_event_threat_detection_custom_module._session - session2 = client2.transport.get_event_threat_detection_custom_module._session - assert session1 != session2 - session1 = client1.transport.list_descendant_event_threat_detection_custom_modules._session - session2 = client2.transport.list_descendant_event_threat_detection_custom_modules._session - assert session1 != session2 - session1 = client1.transport.list_event_threat_detection_custom_modules._session - session2 = client2.transport.list_event_threat_detection_custom_modules._session - assert session1 != session2 - session1 = client1.transport.update_event_threat_detection_custom_module._session - session2 = client2.transport.update_event_threat_detection_custom_module._session - assert session1 != session2 - session1 = client1.transport.validate_event_threat_detection_custom_module._session - session2 = client2.transport.validate_event_threat_detection_custom_module._session - assert session1 != session2 - session1 = client1.transport.get_effective_event_threat_detection_custom_module._session - session2 = client2.transport.get_effective_event_threat_detection_custom_module._session - assert session1 != session2 - session1 = client1.transport.list_effective_event_threat_detection_custom_modules._session - session2 = client2.transport.list_effective_event_threat_detection_custom_modules._session - assert session1 != session2 - session1 = client1.transport.batch_create_resource_value_configs._session - session2 = client2.transport.batch_create_resource_value_configs._session - assert session1 != session2 - session1 = client1.transport.delete_resource_value_config._session - session2 = client2.transport.delete_resource_value_config._session - assert session1 != session2 - session1 = client1.transport.get_resource_value_config._session - session2 = client2.transport.get_resource_value_config._session - assert session1 != session2 - session1 = client1.transport.list_resource_value_configs._session - session2 = client2.transport.list_resource_value_configs._session - assert session1 != session2 - session1 = client1.transport.update_resource_value_config._session - session2 = client2.transport.update_resource_value_config._session - assert session1 != session2 - session1 = client1.transport.list_valued_resources._session - session2 = client2.transport.list_valued_resources._session - assert session1 != session2 - session1 = client1.transport.list_attack_paths._session - session2 = client2.transport.list_attack_paths._session - assert session1 != session2 -def test_security_center_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcTransport( - 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_security_center_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcAsyncIOTransport( - 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(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_security_center_grpc_lro_client(): - client = SecurityCenterClient( - 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_security_center_grpc_lro_async_client(): - client = SecurityCenterAsyncClient( - 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_asset_path(): - organization = "squid" - asset = "clam" - expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.asset_path(organization, asset) - assert expected == actual - - -def test_parse_asset_path(): - expected = { - "organization": "whelk", - "asset": "octopus", - } - path = SecurityCenterClient.asset_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_asset_path(path) - assert expected == actual - -def test_attack_path_path(): - organization = "oyster" - simulation = "nudibranch" - valued_resource = "cuttlefish" - attack_path = "mussel" - expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) - actual = SecurityCenterClient.attack_path_path(organization, simulation, valued_resource, attack_path) - assert expected == actual - - -def test_parse_attack_path_path(): - expected = { - "organization": "winkle", - "simulation": "nautilus", - "valued_resource": "scallop", - "attack_path": "abalone", - } - path = SecurityCenterClient.attack_path_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_attack_path_path(path) - assert expected == actual - -def test_big_query_export_path(): - organization = "squid" - export = "clam" - expected = "organizations/{organization}/bigQueryExports/{export}".format(organization=organization, export=export, ) - actual = SecurityCenterClient.big_query_export_path(organization, export) - assert expected == actual - - -def test_parse_big_query_export_path(): - expected = { - "organization": "whelk", - "export": "octopus", - } - path = SecurityCenterClient.big_query_export_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_big_query_export_path(path) - assert expected == actual - -def test_dlp_job_path(): - project = "oyster" - dlp_job = "nudibranch" - expected = "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) - actual = SecurityCenterClient.dlp_job_path(project, dlp_job) - assert expected == actual - - -def test_parse_dlp_job_path(): - expected = { - "project": "cuttlefish", - "dlp_job": "mussel", - } - path = SecurityCenterClient.dlp_job_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_dlp_job_path(path) - assert expected == actual - -def test_effective_event_threat_detection_custom_module_path(): - organization = "winkle" - module = "nautilus" - expected = "organizations/{organization}/eventThreatDetectionSettings/effectiveCustomModules/{module}".format(organization=organization, module=module, ) - actual = SecurityCenterClient.effective_event_threat_detection_custom_module_path(organization, module) - assert expected == actual - - -def test_parse_effective_event_threat_detection_custom_module_path(): - expected = { - "organization": "scallop", - "module": "abalone", - } - path = SecurityCenterClient.effective_event_threat_detection_custom_module_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_effective_event_threat_detection_custom_module_path(path) - assert expected == actual - -def test_effective_security_health_analytics_custom_module_path(): - organization = "squid" - effective_custom_module = "clam" - expected = "organizations/{organization}/securityHealthAnalyticsSettings/effectiveCustomModules/{effective_custom_module}".format(organization=organization, effective_custom_module=effective_custom_module, ) - actual = SecurityCenterClient.effective_security_health_analytics_custom_module_path(organization, effective_custom_module) - assert expected == actual - - -def test_parse_effective_security_health_analytics_custom_module_path(): - expected = { - "organization": "whelk", - "effective_custom_module": "octopus", - } - path = SecurityCenterClient.effective_security_health_analytics_custom_module_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_effective_security_health_analytics_custom_module_path(path) - assert expected == actual - -def test_event_threat_detection_custom_module_path(): - organization = "oyster" - module = "nudibranch" - expected = "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}".format(organization=organization, module=module, ) - actual = SecurityCenterClient.event_threat_detection_custom_module_path(organization, module) - assert expected == actual - - -def test_parse_event_threat_detection_custom_module_path(): - expected = { - "organization": "cuttlefish", - "module": "mussel", - } - path = SecurityCenterClient.event_threat_detection_custom_module_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_event_threat_detection_custom_module_path(path) - assert expected == actual - -def test_external_system_path(): - organization = "winkle" - source = "nautilus" - finding = "scallop" - externalsystem = "abalone" - expected = "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) - actual = SecurityCenterClient.external_system_path(organization, source, finding, externalsystem) - assert expected == actual - - -def test_parse_external_system_path(): - expected = { - "organization": "squid", - "source": "clam", - "finding": "whelk", - "externalsystem": "octopus", - } - path = SecurityCenterClient.external_system_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_external_system_path(path) - assert expected == actual - -def test_finding_path(): - organization = "oyster" - source = "nudibranch" - finding = "cuttlefish" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - actual = SecurityCenterClient.finding_path(organization, source, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "organization": "mussel", - "source": "winkle", - "finding": "nautilus", - } - path = SecurityCenterClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_finding_path(path) - assert expected == actual - -def test_mute_config_path(): - organization = "scallop" - mute_config = "abalone" - expected = "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) - actual = SecurityCenterClient.mute_config_path(organization, mute_config) - assert expected == actual - - -def test_parse_mute_config_path(): - expected = { - "organization": "squid", - "mute_config": "clam", - } - path = SecurityCenterClient.mute_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_mute_config_path(path) - assert expected == actual - -def test_notification_config_path(): - organization = "whelk" - notification_config = "octopus" - expected = "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) - actual = SecurityCenterClient.notification_config_path(organization, notification_config) - assert expected == actual - - -def test_parse_notification_config_path(): - expected = { - "organization": "oyster", - "notification_config": "nudibranch", - } - path = SecurityCenterClient.notification_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_notification_config_path(path) - assert expected == actual - -def test_organization_settings_path(): - organization = "cuttlefish" - expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) - actual = SecurityCenterClient.organization_settings_path(organization) - assert expected == actual - - -def test_parse_organization_settings_path(): - expected = { - "organization": "mussel", - } - path = SecurityCenterClient.organization_settings_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_organization_settings_path(path) - assert expected == actual - -def test_policy_path(): - organization = "winkle" - constraint_name = "nautilus" - expected = "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) - actual = SecurityCenterClient.policy_path(organization, constraint_name) - assert expected == actual - - -def test_parse_policy_path(): - expected = { - "organization": "scallop", - "constraint_name": "abalone", - } - path = SecurityCenterClient.policy_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_policy_path(path) - assert expected == actual - -def test_resource_value_config_path(): - organization = "squid" - resource_value_config = "clam" - expected = "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) - actual = SecurityCenterClient.resource_value_config_path(organization, resource_value_config) - assert expected == actual - - -def test_parse_resource_value_config_path(): - expected = { - "organization": "whelk", - "resource_value_config": "octopus", - } - path = SecurityCenterClient.resource_value_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_resource_value_config_path(path) - assert expected == actual - -def test_security_health_analytics_custom_module_path(): - organization = "oyster" - custom_module = "nudibranch" - expected = "organizations/{organization}/securityHealthAnalyticsSettings/customModules/{custom_module}".format(organization=organization, custom_module=custom_module, ) - actual = SecurityCenterClient.security_health_analytics_custom_module_path(organization, custom_module) - assert expected == actual - - -def test_parse_security_health_analytics_custom_module_path(): - expected = { - "organization": "cuttlefish", - "custom_module": "mussel", - } - path = SecurityCenterClient.security_health_analytics_custom_module_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_security_health_analytics_custom_module_path(path) - assert expected == actual - -def test_security_marks_path(): - organization = "winkle" - asset = "nautilus" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.security_marks_path(organization, asset) - assert expected == actual - - -def test_parse_security_marks_path(): - expected = { - "organization": "scallop", - "asset": "abalone", - } - path = SecurityCenterClient.security_marks_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_security_marks_path(path) - assert expected == actual - -def test_simulation_path(): - organization = "squid" - simulation = "clam" - expected = "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) - actual = SecurityCenterClient.simulation_path(organization, simulation) - assert expected == actual - - -def test_parse_simulation_path(): - expected = { - "organization": "whelk", - "simulation": "octopus", - } - path = SecurityCenterClient.simulation_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_simulation_path(path) - assert expected == actual - -def test_source_path(): - organization = "oyster" - source = "nudibranch" - expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - actual = SecurityCenterClient.source_path(organization, source) - assert expected == actual - - -def test_parse_source_path(): - expected = { - "organization": "cuttlefish", - "source": "mussel", - } - path = SecurityCenterClient.source_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_source_path(path) - assert expected == actual - -def test_table_data_profile_path(): - project = "winkle" - table_profile = "nautilus" - expected = "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) - actual = SecurityCenterClient.table_data_profile_path(project, table_profile) - assert expected == actual - - -def test_parse_table_data_profile_path(): - expected = { - "project": "scallop", - "table_profile": "abalone", - } - path = SecurityCenterClient.table_data_profile_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_table_data_profile_path(path) - assert expected == actual - -def test_topic_path(): - project = "squid" - topic = "clam" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = SecurityCenterClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "whelk", - "topic": "octopus", - } - path = SecurityCenterClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_topic_path(path) - assert expected == actual - -def test_valued_resource_path(): - organization = "oyster" - simulation = "nudibranch" - valued_resource = "cuttlefish" - expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) - actual = SecurityCenterClient.valued_resource_path(organization, simulation, valued_resource) - assert expected == actual - - -def test_parse_valued_resource_path(): - expected = { - "organization": "mussel", - "simulation": "winkle", - "valued_resource": "nautilus", - } - path = SecurityCenterClient.valued_resource_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_valued_resource_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SecurityCenterClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = SecurityCenterClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = SecurityCenterClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = SecurityCenterClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SecurityCenterClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = SecurityCenterClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = SecurityCenterClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = SecurityCenterClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SecurityCenterClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = SecurityCenterClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - transport_class = SecurityCenterClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations/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 = 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.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations/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 = 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_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations/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() - - # 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 - - 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(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations'}, 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() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations'} - request = request_type(**request_init) - # Mock the http request call within the method and 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.ListOperationsResponse() - - # 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 - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), -]) -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-securitycenter/v1beta1/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v1beta1/.coveragerc deleted file mode 100644 index 45cb273f8f7c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/securitycenter/__init__.py - google/cloud/securitycenter/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-securitycenter/v1beta1/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v1beta1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/.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-securitycenter/v1beta1/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v1beta1/MANIFEST.in deleted file mode 100644 index 328e3b8929b0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/securitycenter *.py -recursive-include google/cloud/securitycenter_v1beta1 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst deleted file mode 100644 index f8c63f4cb48a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v1beta1/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/conf.py deleted file mode 100644 index 8e92d2319721..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter 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-securitycenter" -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-securitycenter-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-securitycenter.tex", - u"google-cloud-securitycenter 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-securitycenter", - u"Google Cloud Securitycenter 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-securitycenter", - u"google-cloud-securitycenter Documentation", - author, - "google-cloud-securitycenter", - "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v1beta1/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/index.rst deleted file mode 100644 index 883606269b5e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - securitycenter_v1beta1/services - securitycenter_v1beta1/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst deleted file mode 100644 index 304849ecc112..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/security_center.rst +++ /dev/null @@ -1,10 +0,0 @@ -SecurityCenter --------------------------------- - -.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center - :members: - :inherited-members: - -.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst deleted file mode 100644 index a09a4b86906d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Securitycenter v1beta1 API -==================================================== -.. toctree:: - :maxdepth: 2 - - security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst deleted file mode 100644 index 0bbeba064657..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/docs/securitycenter_v1beta1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Securitycenter v1beta1 API -================================================= - -.. automodule:: google.cloud.securitycenter_v1beta1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__init__.py deleted file mode 100644 index 34bcf9197d85..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/__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.cloud.securitycenter import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.securitycenter_v1beta1.services.security_center.client import SecurityCenterClient -from google.cloud.securitycenter_v1beta1.services.security_center.async_client import SecurityCenterAsyncClient - -from google.cloud.securitycenter_v1beta1.types.asset import Asset -from google.cloud.securitycenter_v1beta1.types.finding import Finding -from google.cloud.securitycenter_v1beta1.types.organization_settings import OrganizationSettings -from google.cloud.securitycenter_v1beta1.types.run_asset_discovery_response import RunAssetDiscoveryResponse -from google.cloud.securitycenter_v1beta1.types.security_marks import SecurityMarks -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import CreateFindingRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import CreateSourceRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GetOrganizationSettingsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GetSourceRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupAssetsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupAssetsResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupFindingsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupFindingsResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupResult -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListAssetsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListAssetsResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListFindingsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListFindingsResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListSourcesRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListSourcesResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import RunAssetDiscoveryRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import SetFindingStateRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateFindingRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateOrganizationSettingsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateSecurityMarksRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateSourceRequest -from google.cloud.securitycenter_v1beta1.types.source import Source - -__all__ = ('SecurityCenterClient', - 'SecurityCenterAsyncClient', - 'Asset', - 'Finding', - 'OrganizationSettings', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateSourceRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/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-securitycenter/v1beta1/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py deleted file mode 100644 index 4f049ee47efe..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/__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.cloud.securitycenter_v1beta1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.security_center import SecurityCenterClient -from .services.security_center import SecurityCenterAsyncClient - -from .types.asset import Asset -from .types.finding import Finding -from .types.organization_settings import OrganizationSettings -from .types.run_asset_discovery_response import RunAssetDiscoveryResponse -from .types.security_marks import SecurityMarks -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import GetOrganizationSettingsRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GroupAssetsRequest -from .types.securitycenter_service import GroupAssetsResponse -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAssetsRequest -from .types.securitycenter_service import ListAssetsResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import RunAssetDiscoveryRequest -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateOrganizationSettingsRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.source import Source - -__all__ = ( - 'SecurityCenterAsyncClient', -'Asset', -'CreateFindingRequest', -'CreateSourceRequest', -'Finding', -'GetOrganizationSettingsRequest', -'GetSourceRequest', -'GroupAssetsRequest', -'GroupAssetsResponse', -'GroupFindingsRequest', -'GroupFindingsResponse', -'GroupResult', -'ListAssetsRequest', -'ListAssetsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListSourcesRequest', -'ListSourcesResponse', -'OrganizationSettings', -'RunAssetDiscoveryRequest', -'RunAssetDiscoveryResponse', -'SecurityCenterClient', -'SecurityMarks', -'SetFindingStateRequest', -'Source', -'UpdateFindingRequest', -'UpdateOrganizationSettingsRequest', -'UpdateSecurityMarksRequest', -'UpdateSourceRequest', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json deleted file mode 100644 index afd9dcb019c2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json +++ /dev/null @@ -1,298 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.securitycenter_v1beta1", - "protoPackage": "google.cloud.securitycenter.v1beta1", - "schema": "1.0", - "services": { - "SecurityCenter": { - "clients": { - "grpc": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SecurityCenterAsyncClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "rest": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/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-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/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-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py deleted file mode 100644 index bffcff5da306..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - 'SecurityCenterClient', - 'SecurityCenterAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py deleted file mode 100644 index 6e93123eb92f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.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. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.securitycenter_v1beta1 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.securitycenter_v1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V1 Beta APIs for Security Center service.""" - - _client: SecurityCenterClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE - - asset_path = staticmethod(SecurityCenterClient.asset_path) - parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) - parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) - organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) - parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) - source_path = staticmethod(SecurityCenterClient.source_path) - parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) - common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) - parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) - common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) - parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) - parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) - parse_common_location_path = staticmethod(SecurityCenterClient.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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v1beta1 - - async def sample_create_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.CreateSourceRequest, dict]]): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = 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_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding_id: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_create_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.CreateFindingRequest, dict]]): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 get_organization_settings(self, - request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest, dict]]): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_organization_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 get_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v1beta1 - - async def sample_get_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GetSourceRequest, dict]]): - The request object. Request message for getting a source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 group_assets(self, - request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsAsyncPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_group_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest, dict]]): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsAsyncPager: - Response message for grouping by - assets. - 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, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.GroupAssetsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_group_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest, dict]]): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state``). The string value - should follow SQL syntax: comma separated list of - fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_assets(self, - request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsAsyncPager: - r"""Lists an organization's assets. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_list_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.ListAssetsRequest, dict]]): - The request object. Request message for listing assets. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsAsyncPager: - Response message for listing assets. - - 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, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(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_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListAssetsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings(self, - request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_list_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListFindingsRequest( - parent="parent_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.securitycenter_v1beta1.types.ListFindingsRequest, dict]]): - The request object. Request message for listing findings. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.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_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_list_sources(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.ListSourcesRequest, dict]]): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id]". - - 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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesAsyncPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_asset_discovery(self, - request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), - ) -> operation_async.AsyncOperation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS 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 securitycenter_v1beta1 - - async def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest, dict]]): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.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([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, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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, - empty_pb2.Empty, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - async def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - start_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of 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 securitycenter_v1beta1 - - async def sample_set_finding_state(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest, dict]]): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`google.cloud.securitycenter_v1beta1.types.Finding.State`): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 update_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_update_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest, dict]]): - The request object. Request message for updating or - creating a finding. - finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe domain. - self._client._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_organization_settings(self, - request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, - *, - organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = await client.update_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest, dict]]): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`google.cloud.securitycenter_v1beta1.types.OrganizationSettings`): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_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 update_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v1beta1 - - async def sample_update_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest, dict]]): - The request object. Request message for updating a - source. - source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): - Required. The source resource to - update. - - This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - async def sample_update_security_marks(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest, dict]]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`google.cloud.securitycenter_v1beta1.types.SecurityMarks`): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe domain. - self._client._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) -> "SecurityCenterAsyncClient": - 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__ = ( - "SecurityCenterAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py deleted file mode 100644 index 72d03d765968..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py +++ /dev/null @@ -1,2755 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_v1beta1 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.securitycenter_v1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .transports.rest import SecurityCenterRestTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - _transport_registry["rest"] = SecurityCenterRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SecurityCenterTransport]: - """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V1 Beta APIs for Security Center 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 = "securitycenter.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: - SecurityCenterClient: 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: - SecurityCenterClient: 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) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def asset_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified asset string.""" - return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_asset_path(path: str) -> Dict[str,str]: - """Parses a asset path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def finding_path(organization: str,source: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def organization_settings_path(organization: str,) -> str: - """Returns a fully-qualified organization_settings string.""" - return "organizations/{organization}/organizationSettings".format(organization=organization, ) - - @staticmethod - def parse_organization_settings_path(path: str) -> Dict[str,str]: - """Parses a organization_settings path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str,str]: - """Parses a security_marks path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str,source: str,) -> str: - """Returns a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str,str]: - """Parses a source path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 - SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient._read_environment_variables() - self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) - if transport_provided: - # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( - type(self).get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., SecurityCenterTransport], 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_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v1beta1 - - def sample_create_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.CreateSourceRequest, dict]): - The request object. Request message for creating a - source. - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (google.cloud.securitycenter_v1beta1.types.Source): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding_id: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_create_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.CreateFindingRequest, dict]): - The request object. Request message for creating a - finding. - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (google.cloud.securitycenter_v1beta1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 get_organization_settings(self, - request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest, dict]): - The request object. Request message for getting - organization settings. - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_organization_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 get_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v1beta1 - - def sample_get_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.GetSourceRequest, dict]): - The request object. Request message for getting a source. - name (str): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 group_assets(self, - request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_group_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest, dict]): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsPager: - Response message for grouping by - assets. - 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, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.GroupAssetsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_group_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest, dict]): - The request object. Request message for grouping by - findings. - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (str): - Required. Expression that defines what assets fields to - use for grouping (including ``state``). The string value - should follow SQL syntax: comma separated list of - fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_assets(self, - request: Optional[Union[securitycenter_service.ListAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsPager: - r"""Lists an organization's assets. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_list_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.ListAssetsRequest, dict]): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsPager: - Response message for listing assets. - - 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, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListAssetsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings(self, - request: Optional[Union[securitycenter_service.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"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_list_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListFindingsRequest( - parent="parent_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.securitycenter_v1beta1.types.ListFindingsRequest, dict]): - The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsPager: - Response message for listing - findings. - 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.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_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_list_sources(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.ListSourcesRequest, dict]): - The request object. Request message for listing sources. - parent (str): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id]". - - 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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_asset_discovery(self, - request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), - ) -> operation.Operation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS 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 securitycenter_v1beta1 - - def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest, dict]): - The request object. Request message for running asset - discovery for an organization. - parent (str): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.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([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, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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, - empty_pb2.Empty, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - start_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of 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 securitycenter_v1beta1 - - def sample_set_finding_state(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest, dict]): - The request object. Request message for updating a - finding's state. - name (str): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (google.cloud.securitycenter_v1beta1.types.Finding.State): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # 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 - - def update_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_update_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest, dict]): - The request object. Request message for updating or - creating a finding. - finding (google.cloud.securitycenter_v1beta1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe 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_organization_settings(self, - request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, - *, - organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = client.update_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest, dict]): - The request object. Request message for updating an - organization's settings. - organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_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 update_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v1beta1 - - def sample_update_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest, dict]): - The request object. Request message for updating a - source. - source (google.cloud.securitycenter_v1beta1.types.Source): - Required. The source resource to - update. - - This corresponds to the ``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.cloud.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1beta1 - - def sample_update_security_marks(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest, dict]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1beta1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe 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) -> "SecurityCenterClient": - 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__ = ( - "SecurityCenterClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py deleted file mode 100644 index 51807c4b0d79..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.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 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.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source - - -class GroupAssetsPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupAssetsResponse], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1beta1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - 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[securitycenter_service.GroupAssetsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupAssetsAsyncPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` - attributes are available on the 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[securitycenter_service.GroupAssetsResponse]], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1beta1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - 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[securitycenter_service.GroupAssetsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1beta1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` - attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1beta1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListAssetsResponse], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - 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[securitycenter_service.ListAssetsResponse]: - 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - for page in self.pages: - yield from page.list_assets_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` - attributes are available on the 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[securitycenter_service.ListAssetsResponse]], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - 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[securitycenter_service.ListAssetsResponse]: - 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_assets_results: - 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.securitycenter_v1beta1.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.securitycenter_v1beta1.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[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v1beta1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.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 = securitycenter_service.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[securitycenter_service.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.securitycenter_v1beta1.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.securitycenter_v1beta1.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[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v1beta1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.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 = securitycenter_service.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[securitycenter_service.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) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1beta1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` - attributes are available on the 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[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1beta1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.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-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py deleted file mode 100644 index 9d36139c1a9b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/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 SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .rest import SecurityCenterRestTransport -from .rest import SecurityCenterRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry['grpc'] = SecurityCenterGrpcTransport -_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport -_transport_registry['rest'] = SecurityCenterRestTransport - -__all__ = ( - 'SecurityCenterTransport', - 'SecurityCenterGrpcTransport', - 'SecurityCenterGrpcAsyncIOTransport', - 'SecurityCenterRestTransport', - 'SecurityCenterRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py deleted file mode 100644 index 9c83124b6382..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py +++ /dev/null @@ -1,498 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.securitycenter_v1beta1 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.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -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 SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'securitycenter.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.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: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_source: gapic_v1.method.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_organization_settings: gapic_v1.method.wrap_method( - self.get_organization_settings, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_source: gapic_v1.method.wrap_method( - self.get_source, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.group_assets: gapic_v1.method.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_sources: gapic_v1.method.wrap_method( - self.list_sources, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.run_asset_discovery: gapic_v1.method.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_finding: gapic_v1.method.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=480.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 operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - 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 get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Union[ - organization_settings.OrganizationSettings, - Awaitable[organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Union[ - source.Source, - Awaitable[source.Source] - ]]: - raise NotImplementedError() - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Union[ - securitycenter_service.GroupAssetsResponse, - Awaitable[securitycenter_service.GroupAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Union[ - securitycenter_service.GroupFindingsResponse, - Awaitable[securitycenter_service.GroupFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Union[ - securitycenter_service.ListAssetsResponse, - Awaitable[securitycenter_service.ListAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Union[ - securitycenter_service.ListFindingsResponse, - Awaitable[securitycenter_service.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Union[ - securitycenter_service.ListSourcesResponse, - Awaitable[securitycenter_service.ListSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - 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 test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Union[ - gcs_organization_settings.OrganizationSettings, - Awaitable[gcs_organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Union[ - gcs_security_marks.SecurityMarks, - Awaitable[gcs_security_marks.SecurityMarks] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SecurityCenterTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py deleted file mode 100644 index bd93a5f13210..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.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. -# -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.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -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 SecurityCenterTransport, DEFAULT_CLIENT_INFO - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V1 Beta APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: 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 create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - ~.GroupAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - 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.securitycenter.v1beta1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - operations_pb2.Operation]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - ~.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 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - ~.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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SecurityCenterGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index 47e586023e58..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,945 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -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 SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V1 Beta APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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._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 create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - 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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Awaitable[organization_settings.OrganizationSettings]]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Awaitable[securitycenter_service.GroupAssetsResponse]]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - Awaitable[~.GroupAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse]]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Awaitable[securitycenter_service.ListAssetsResponse]]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - 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.securitycenter.v1beta1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse]]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - 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 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - 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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.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.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - 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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Awaitable[gcs_organization_settings.OrganizationSettings]]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks]]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - 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_source: gapic_v1.method_async.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method_async.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( - self.get_iam_policy, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_organization_settings: gapic_v1.method_async.wrap_method( - self.get_organization_settings, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_source: gapic_v1.method_async.wrap_method( - self.get_source, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.group_assets: gapic_v1.method_async.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method_async.wrap_method( - self.group_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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method_async.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method_async.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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_sources: gapic_v1.method_async.wrap_method( - self.list_sources, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.run_asset_discovery: gapic_v1.method_async.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method_async.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( - self.test_iam_permissions, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_finding: gapic_v1.method_async.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method_async.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method_async.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method_async.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py deleted file mode 100644 index a44f2b2a1487..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/rest.py +++ /dev/null @@ -1,2542 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # 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 path_template -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 -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -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.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -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 SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SecurityCenterRestInterceptor: - """Interceptor for SecurityCenter. - - 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 SecurityCenterRestTransport. - - .. code-block:: python - class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): - def pre_create_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_organization_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_organization_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_assets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_assets(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_sources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_sources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_run_asset_discovery(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_run_asset_discovery(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_finding_state(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_finding_state(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_organization_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_organization_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_security_marks(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_security_marks(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_source(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) - client = SecurityCenterClient(transport=transport) - - - """ - def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for create_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for create_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_organization_settings(self, request: securitycenter_service.GetOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_organization_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_organization_settings(self, response: organization_settings.OrganizationSettings) -> organization_settings.OrganizationSettings: - """Post-rpc interceptor for get_organization_settings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_source(self, response: source.Source) -> source.Source: - """Post-rpc interceptor for get_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_assets(self, request: securitycenter_service.GroupAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_assets(self, response: securitycenter_service.GroupAssetsResponse) -> securitycenter_service.GroupAssetsResponse: - """Post-rpc interceptor for group_assets - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: - """Post-rpc interceptor for group_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_assets(self, request: securitycenter_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_assets(self, response: securitycenter_service.ListAssetsResponse) -> securitycenter_service.ListAssetsResponse: - """Post-rpc interceptor for list_assets - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. - """ - return request, metadata - - def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: - """Post-rpc interceptor for list_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_sources - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: - """Post-rpc interceptor for list_sources - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_run_asset_discovery(self, request: securitycenter_service.RunAssetDiscoveryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.RunAssetDiscoveryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for run_asset_discovery - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_run_asset_discovery(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for run_asset_discovery - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for update_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_organization_settings(self, request: securitycenter_service.UpdateOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_organization_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_organization_settings(self, response: gcs_organization_settings.OrganizationSettings) -> gcs_organization_settings.OrganizationSettings: - """Post-rpc interceptor for update_organization_settings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: - """Post-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for update_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SecurityCenterRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SecurityCenterRestInterceptor - - -class SecurityCenterRestTransport(SecurityCenterTransport): - """REST backend transport for SecurityCenter. - - V1 Beta APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SecurityCenterRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 - 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 - ) - 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 SecurityCenterRestInterceptor() - 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': '/v1beta1/{name=organizations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1beta1/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta1/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta1/{name=organizations/*/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="v1beta1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "findingId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the create finding method over HTTP. - - Args: - request (~.securitycenter_service.CreateFindingRequest): - The request object. Request message for creating a - finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=organizations/*/sources/*}/findings', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_create_finding(request, metadata) - pb_request = securitycenter_service.CreateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_finding(resp) - return resp - - class _CreateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the create source method over HTTP. - - Args: - request (~.securitycenter_service.CreateSourceRequest): - The request object. Request message for creating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=organizations/*}/sources', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_create_source(request, metadata) - pb_request = securitycenter_service.CreateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_source(resp) - return resp - - class _GetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{resource=organizations/*/sources/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _GetOrganizationSettings(SecurityCenterRestStub): - def __hash__(self): - return hash("GetOrganizationSettings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetOrganizationSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> organization_settings.OrganizationSettings: - r"""Call the get organization settings method over HTTP. - - Args: - request (~.securitycenter_service.GetOrganizationSettingsRequest): - The request object. Request message for getting - organization 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: - ~.organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{name=organizations/*/organizationSettings}', - }, - ] - request, metadata = self._interceptor.pre_get_organization_settings(request, metadata) - pb_request = securitycenter_service.GetOrganizationSettingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = organization_settings.OrganizationSettings() - pb_resp = organization_settings.OrganizationSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_organization_settings(resp) - return resp - - class _GetSource(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> source.Source: - r"""Call the get source method over HTTP. - - Args: - request (~.securitycenter_service.GetSourceRequest): - The request object. Request message for getting a source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{name=organizations/*/sources/*}', - }, - ] - request, metadata = self._interceptor.pre_get_source(request, metadata) - pb_request = securitycenter_service.GetSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = source.Source() - pb_resp = source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_source(resp) - return resp - - class _GroupAssets(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupAssets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupAssetsResponse: - r"""Call the group assets method over HTTP. - - Args: - request (~.securitycenter_service.GroupAssetsRequest): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupAssetsResponse: - Response message for grouping by - assets. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=organizations/*}/assets:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_assets(request, metadata) - pb_request = securitycenter_service.GroupAssetsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupAssetsResponse() - pb_resp = securitycenter_service.GroupAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_assets(resp) - return resp - - class _GroupFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupFindingsResponse: - r"""Call the group findings method over HTTP. - - Args: - request (~.securitycenter_service.GroupFindingsRequest): - The request object. Request message for grouping by - findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupFindingsResponse: - Response message for group by - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=organizations/*/sources/*}/findings:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_findings(request, metadata) - pb_request = securitycenter_service.GroupFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupFindingsResponse() - pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_findings(resp) - return resp - - class _ListAssets(SecurityCenterRestStub): - def __hash__(self): - return hash("ListAssets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListAssetsResponse: - r"""Call the list assets method over HTTP. - - Args: - request (~.securitycenter_service.ListAssetsRequest): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListAssetsResponse: - Response message for listing assets. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{parent=organizations/*}/assets', - }, - ] - request, metadata = self._interceptor.pre_list_assets(request, metadata) - pb_request = securitycenter_service.ListAssetsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListAssetsResponse() - pb_resp = securitycenter_service.ListAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_assets(resp) - return resp - - class _ListFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("ListFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListFindingsResponse: - r"""Call the list findings method over HTTP. - - Args: - request (~.securitycenter_service.ListFindingsRequest): - The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListFindingsResponse: - Response message for listing - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{parent=organizations/*/sources/*}/findings', - }, - ] - request, metadata = self._interceptor.pre_list_findings(request, metadata) - pb_request = securitycenter_service.ListFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListFindingsResponse() - pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_findings(resp) - return resp - - class _ListSources(SecurityCenterRestStub): - def __hash__(self): - return hash("ListSources") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListSourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListSourcesResponse: - r"""Call the list sources method over HTTP. - - Args: - request (~.securitycenter_service.ListSourcesRequest): - The request object. Request message for listing sources. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListSourcesResponse: - Response message for listing sources. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{parent=organizations/*}/sources', - }, - ] - request, metadata = self._interceptor.pre_list_sources(request, metadata) - pb_request = securitycenter_service.ListSourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListSourcesResponse() - pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_sources(resp) - return resp - - class _RunAssetDiscovery(SecurityCenterRestStub): - def __hash__(self): - return hash("RunAssetDiscovery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.RunAssetDiscoveryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the run asset discovery method over HTTP. - - Args: - request (~.securitycenter_service.RunAssetDiscoveryRequest): - The request object. Request message for running asset - discovery for an organization. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=organizations/*}/assets:runDiscovery', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_run_asset_discovery(request, metadata) - pb_request = securitycenter_service.RunAssetDiscoveryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_run_asset_discovery(resp) - return resp - - class _SetFindingState(SecurityCenterRestStub): - def __hash__(self): - return hash("SetFindingState") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SetFindingStateRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the set finding state method over HTTP. - - Args: - request (~.securitycenter_service.SetFindingStateRequest): - The request object. Request message for updating a - finding's state. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{name=organizations/*/sources/*/findings/*}:setState', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_finding_state(request, metadata) - pb_request = securitycenter_service.SetFindingStateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_set_finding_state(resp) - return resp - - class _SetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{resource=organizations/*/sources/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _TestIamPermissions(SecurityCenterRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{resource=organizations/*/sources/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UpdateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the update finding method over HTTP. - - Args: - request (~.securitycenter_service.UpdateFindingRequest): - The request object. Request message for updating or - creating a finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta1/{finding.name=organizations/*/sources/*/findings/*}', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_update_finding(request, metadata) - pb_request = securitycenter_service.UpdateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_finding(resp) - return resp - - class _UpdateOrganizationSettings(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateOrganizationSettings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateOrganizationSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Call the update organization - settings method over HTTP. - - Args: - request (~.securitycenter_service.UpdateOrganizationSettingsRequest): - The request object. Request message for updating an - organization's 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: - ~.gcs_organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta1/{organization_settings.name=organizations/*/organizationSettings}', - 'body': 'organization_settings', - }, - ] - request, metadata = self._interceptor.pre_update_organization_settings(request, metadata) - pb_request = securitycenter_service.UpdateOrganizationSettingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_organization_settings.OrganizationSettings() - pb_resp = gcs_organization_settings.OrganizationSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_organization_settings(resp) - return resp - - class _UpdateSecurityMarks(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSecurityMarks") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSecurityMarksRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_security_marks.SecurityMarks: - r"""Call the update security marks method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSecurityMarksRequest): - The request object. Request message for updating a - SecurityMarks resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1beta1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, - ] - request, metadata = self._interceptor.pre_update_security_marks(request, metadata) - pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_security_marks.SecurityMarks() - pb_resp = gcs_security_marks.SecurityMarks.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_security_marks(resp) - return resp - - class _UpdateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the update source method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSourceRequest): - The request object. Request message for updating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta1/{source.name=organizations/*/sources/*}', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_update_source(request, metadata) - pb_request = securitycenter_service.UpdateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_source(resp) - return resp - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.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_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSources(self._session, self._host, self._interceptor) # type: ignore - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - 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._RunAssetDiscovery(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SecurityCenterRestTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py deleted file mode 100644 index d3d5b965f804..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py +++ /dev/null @@ -1,86 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .asset import ( - Asset, -) -from .finding import ( - Finding, -) -from .organization_settings import ( - OrganizationSettings, -) -from .run_asset_discovery_response import ( - RunAssetDiscoveryResponse, -) -from .security_marks import ( - SecurityMarks, -) -from .securitycenter_service import ( - CreateFindingRequest, - CreateSourceRequest, - GetOrganizationSettingsRequest, - GetSourceRequest, - GroupAssetsRequest, - GroupAssetsResponse, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListAssetsRequest, - ListAssetsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListSourcesRequest, - ListSourcesResponse, - RunAssetDiscoveryRequest, - SetFindingStateRequest, - UpdateFindingRequest, - UpdateOrganizationSettingsRequest, - UpdateSecurityMarksRequest, - UpdateSourceRequest, -) -from .source import ( - Source, -) - -__all__ = ( - 'Asset', - 'Finding', - 'OrganizationSettings', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateSourceRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py deleted file mode 100644 index 16ad84206b64..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py +++ /dev/null @@ -1,155 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'Asset', - }, -) - - -class Asset(proto.Message): - r"""Security Command Center representation of a Google Cloud - resource. - - The Asset is a Security Command Center resource that captures - information about a single Google Cloud resource. All - modifications to an Asset are only within the context of - Security Command Center and don't affect the referenced Google - Cloud resource. - - Attributes: - name (str): - The relative resource name of this asset. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (google.cloud.securitycenter_v1beta1.types.Asset.SecurityCenterProperties): - Security Command Center managed properties. - These properties are managed by Security Command - Center and cannot be modified by the user. - resource_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Resource managed properties. These properties - are managed and defined by the Google Cloud - resource and cannot be modified by the user. - security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): - User specified security marks. These marks - are entirely managed by the user and come from - the SecurityMarks resource that belongs to the - asset. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was created in - Security Command Center. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was last updated, - added, or deleted in Security Command Center. - """ - - class SecurityCenterProperties(proto.Message): - r"""Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified by - the user. - - Attributes: - resource_name (str): - Immutable. The full resource name of the Google Cloud - resource this asset represents. This field is immutable - after create time. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_type (str): - The type of the Google Cloud resource. - Examples include: APPLICATION, PROJECT, and - ORGANIZATION. This is a case insensitive field - defined by Security Command Center and/or the - producer of the resource and is immutable after - create time. - resource_parent (str): - The full resource name of the immediate parent of the - resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_project (str): - The full resource name of the project the resource belongs - to. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_owners (MutableSequence[str]): - Owners of the Google Cloud resource. - """ - - resource_name: str = proto.Field( - proto.STRING, - number=1, - ) - resource_type: str = proto.Field( - proto.STRING, - number=2, - ) - resource_parent: str = proto.Field( - proto.STRING, - number=3, - ) - resource_project: str = proto.Field( - proto.STRING, - number=4, - ) - resource_owners: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - security_center_properties: SecurityCenterProperties = proto.Field( - proto.MESSAGE, - number=2, - message=SecurityCenterProperties, - ) - resource_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py deleted file mode 100644 index 15d2a4ec1ee5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.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.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - - A finding is a record of assessment data (security, risk, health - or privacy) ingested into Security Command Center for - presentation, notification, analysis, policy testing, and - enforcement. For example, an XSS vulnerability in an App Engine - application is a finding. - - Attributes: - name (str): - The relative resource name of this finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". - parent (str): - Immutable. The relative resource name of the source the - finding belongs to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. For example: - "organizations/{organization_id}/sources/{source_id}". - resource_name (str): - For findings on Google Cloud resources, the full resource - name of the Google Cloud resource this finding is for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - This field is immutable after creation time. - state (google.cloud.securitycenter_v1beta1.types.Finding.State): - The state of the finding. - category (str): - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. - Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the event took place, or - when an update to the finding occurred. For - example, if the finding represents an open - firewall it would capture the time the detector - believes the firewall became open. The accuracy - is determined by the detector. If the finding - were to be resolved afterward, this time would - reflect when the finding was resolved. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the finding was created in - Security Command Center. - """ - class State(proto.Enum): - r"""The state of the finding. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - ACTIVE (1): - The finding requires attention and has not - been addressed yet. - INACTIVE (2): - The finding has been fixed, triaged as a - non-issue or otherwise addressed and is no - longer active. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - resource_name: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - category: str = proto.Field( - proto.STRING, - number=5, - ) - external_uri: str = proto.Field( - proto.STRING, - number=6, - ) - source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py deleted file mode 100644 index e94e037fd61a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py +++ /dev/null @@ -1,115 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'OrganizationSettings', - }, -) - - -class OrganizationSettings(proto.Message): - r"""User specified settings that are attached to the Security - Command Center organization. - - Attributes: - name (str): - The relative resource name of the settings. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/organizationSettings". - enable_asset_discovery (bool): - A flag that indicates if Asset Discovery should be enabled. - If the flag is set to ``true``, then discovery of assets - will occur. If it is set to \`false, all historical assets - will remain, but discovery of future assets will not occur. - asset_discovery_config (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig): - The configuration used for Asset Discovery - runs. - """ - - class AssetDiscoveryConfig(proto.Message): - r"""The configuration used for Asset Discovery runs. - - Attributes: - project_ids (MutableSequence[str]): - The project ids to use for filtering asset - discovery. - inclusion_mode (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): - The mode to use for filtering asset - discovery. - """ - class InclusionMode(proto.Enum): - r"""The mode of inclusion when running Asset Discovery. Asset discovery - can be limited by explicitly identifying projects to be included or - excluded. If INCLUDE_ONLY is set, then only those projects within - the organization and their children are discovered during asset - discovery. If EXCLUDE is set, then projects that don't match those - projects are discovered during asset discovery. If neither are set, - then all projects within the organization are discovered during - asset discovery. - - Values: - INCLUSION_MODE_UNSPECIFIED (0): - Unspecified. Setting the mode with this value - will disable inclusion/exclusion filtering for - Asset Discovery. - INCLUDE_ONLY (1): - Asset Discovery will capture only the - resources within the projects specified. All - other resources will be ignored. - EXCLUDE (2): - Asset Discovery will ignore all resources - under the projects specified. All other - resources will be retrieved. - """ - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - project_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - inclusion_mode: 'OrganizationSettings.AssetDiscoveryConfig.InclusionMode' = proto.Field( - proto.ENUM, - number=2, - enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - enable_asset_discovery: bool = proto.Field( - proto.BOOL, - number=2, - ) - asset_discovery_config: AssetDiscoveryConfig = proto.Field( - proto.MESSAGE, - number=3, - message=AssetDiscoveryConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py deleted file mode 100644 index c5bccb3dd7f2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.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 - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'RunAssetDiscoveryResponse', - }, -) - - -class RunAssetDiscoveryResponse(proto.Message): - r"""Response of asset discovery run - - Attributes: - state (google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryResponse.State): - The state of an asset discovery run. - duration (google.protobuf.duration_pb2.Duration): - The duration between asset discovery run - start and end - """ - class State(proto.Enum): - r"""The state of an asset discovery run. - - Values: - STATE_UNSPECIFIED (0): - Asset discovery run state was unspecified. - COMPLETED (1): - Asset discovery run completed successfully. - SUPERSEDED (2): - Asset discovery run was cancelled with tasks - still pending, as another run for the same - organization was started with a higher priority. - TERMINATED (3): - Asset discovery run was killed and - terminated. - """ - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py deleted file mode 100644 index f2b762a6f2ec..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'SecurityMarks', - }, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (MutableMapping[str, str]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - marks: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py deleted file mode 100644 index dd7fedfd6122..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py +++ /dev/null @@ -1,1053 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1beta1.types import asset as gcs_asset -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'CreateFindingRequest', - 'CreateSourceRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'SetFindingStateRequest', - 'RunAssetDiscoveryRequest', - 'UpdateFindingRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSourceRequest', - 'UpdateSecurityMarksRequest', - }, -) - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - - Attributes: - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - alphanumeric and less than or equal to 32 - characters and greater than 0 characters in - length. - finding (google.cloud.securitycenter_v1beta1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - finding_id: str = proto.Field( - proto.STRING, - number=2, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_finding.Finding, - ) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - source (google.cloud.securitycenter_v1beta1.types.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_source.Source, - ) - - -class GetOrganizationSettingsRequest(proto.Message): - r"""Request message for getting organization settings. - - Attributes: - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is "organizations/[organization_id]/source/[source_id]". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GroupAssetsRequest(proto.Message): - r"""Request message for grouping by assets. - - Attributes: - parent (str): - Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``resource_properties.size = 100`` is a valid - filter string. - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is - not set: - - - security_center_properties.resource_project - - security_center_properties.resource_type - - security_center_properties.resource_parent - - The following fields are supported when compare_duration is - set: - - - security_center_properties.resource_type - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the Asset's "state" property - is updated to indicate whether the asset was added, removed, - or remained present during the compare_duration period of - time that precedes the read_time. This is the time between - (read_time - compare_duration) and read_time. - - The state value is derived based on the presence of the - asset at the two points in time. Intermediate state changes - between the two times don't affect the result. For example, - the results aren't affected if the asset is removed and - re-created again. - - Possible "state" values when compare_duration is specified: - - - "ADDED": indicates that the asset was not present before - compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at - reference_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and reference_time. - - This field is ignored if ``state`` is not a field in - ``group_by``. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupAssetsResponse``; - indicates that this is a continuation of a prior - ``GroupAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - page_size: int = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupAssetsResponse(proto.Message): - r"""Response message for grouping by assets. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - - Attributes: - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". To - groupBy across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``source_properties.size = 100`` is a valid - filter string. - group_by (str): - Required. Expression that defines what assets fields to use - for grouping (including ``state``). The string value should - follow SQL syntax: comma separated list of fields. For - example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - page_size: int = proto.Field( - proto.INT32, - number=6, - ) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message=struct_pb2.Value, - ) - count: int = proto.Field( - proto.INT64, - number=2, - ) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be "organizations/[organization_id]". - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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=7, - ) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - - Attributes: - sources (MutableSequence[google.cloud.securitycenter_v1beta1.types.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListAssetsRequest(proto.Message): - r"""Request message for listing assets. - - Attributes: - parent (str): - Required. Name of the organization assets should belong to. - Its format is "organizations/[organization_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``resource_properties.size = 100`` is a valid - filter string. - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,resource_properties.a_property". - Redundant space characters in the syntax are insignificant. - "name desc,resource_properties.a_property" and " name desc , - resource_properties.a_property " are equivalent. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListAssetResult's "state" - attribute is updated to indicate whether the asset was - added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state value is derived based on the presence of the - asset at the two points in time. Intermediate state changes - between the two times don't affect the result. For example, - the results aren't affected if the asset is removed and - re-created again. - - Possible "state" values when compare_duration is specified: - - - "ADDED": indicates that the asset was not present before - compare_duration, but present at read_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at read_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and read_time. - - If compare_duration is not specified, then the only possible - state is "UNUSED", which indicates that the asset is present - at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. A field mask to specify the - ListAssetsResult fields to be listed in the - response. An empty field mask will list all - fields. - page_token (str): - The value returned by the last ``ListAssetsResponse``; - indicates that this is a continuation of a prior - ``ListAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=8, - ) - page_size: int = proto.Field( - proto.INT32, - number=9, - ) - - -class ListAssetsResponse(proto.Message): - r"""Response message for listing assets. - - Attributes: - list_assets_results (MutableSequence[google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult]): - Assets matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of assets matching the - query. - """ - - class ListAssetsResult(proto.Message): - r"""Result containing the Asset and its State. - - Attributes: - asset (google.cloud.securitycenter_v1beta1.types.Asset): - Asset matching the search request. - state (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult.State): - State of the asset. - """ - class State(proto.Enum): - r"""State of the asset. - - When querying across two points in time this describes the change - between the two points: ADDED, REMOVED, or ACTIVE. If there was no - compare_duration supplied in the request the state should be: UNUSED - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - UNUSED (1): - Request did not specify use of this field in - the result. - ADDED (2): - Asset was added between the points in time. - REMOVED (3): - Asset was removed between the points in time. - ACTIVE (4): - Asset was active at both point(s) in time. - """ - STATE_UNSPECIFIED = 0 - UNUSED = 1 - ADDED = 2 - REMOVED = 3 - ACTIVE = 4 - - asset: gcs_asset.Asset = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_asset.Asset, - ) - state: 'ListAssetsResponse.ListAssetsResult.State' = proto.Field( - proto.ENUM, - number=2, - enum='ListAssetsResponse.ListAssetsResult.State', - ) - - @property - def raw_page(self): - return self - - list_assets_results: MutableSequence[ListAssetsResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListAssetsResult, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - - Attributes: - parent (str): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id]". To - list across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``source_properties.size = 100`` is a valid - filter string. - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,source_properties.a_property". Redundant - space characters in the syntax are insignificant. "name - desc,source_properties.a_property" and " name desc , - source_properties.a_property " are equivalent. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. A field mask to specify the Finding - fields to be listed in the response. An empty - field mask will list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=6, - ) - page_size: int = proto.Field( - proto.INT32, - number=7, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - - Attributes: - findings (MutableSequence[google.cloud.securitycenter_v1beta1.types.Finding]): - Findings matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - @property - def raw_page(self): - return self - - findings: MutableSequence[gcs_finding.Finding] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - - Attributes: - name (str): - Required. The relative resource name of the finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - state (google.cloud.securitycenter_v1beta1.types.Finding.State): - Required. The desired State of the finding. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the updated state - takes effect. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: gcs_finding.Finding.State = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.State, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class RunAssetDiscoveryRequest(proto.Message): - r"""Request message for running asset discovery for an - organization. - - Attributes: - parent (str): - Required. Name of the organization to run asset discovery - for. Its format is "organizations/[organization_id]". - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - - Attributes: - finding (google.cloud.securitycenter_v1beta1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - finding resource. This field should not be - specified when creating a finding. - """ - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateOrganizationSettingsRequest(proto.Message): - r"""Request message for updating an organization's settings. - - Attributes: - organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): - Required. The organization settings resource - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - settings resource. - """ - - organization_settings: gcs_organization_settings.OrganizationSettings = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_organization_settings.OrganizationSettings, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - - Attributes: - source (google.cloud.securitycenter_v1beta1.types.Source): - Required. The source resource to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the source - resource. - """ - - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - - Attributes: - security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): - Required. The security marks resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - security marks resource. - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the updated SecurityMarks - take effect. - """ - - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_security_marks.SecurityMarks, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - start_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-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py deleted file mode 100644 index 761384a9c28f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py +++ /dev/null @@ -1,77 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v1beta1', - manifest={ - 'Source', - }, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, etc. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and - outdated/insecure libraries.". - """ - - 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, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/noxfile.py deleted file mode 100644 index 09f9f6872402..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-securitycenter' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -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"): - 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/securitycenter_v1beta1/', - '--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"): - 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", - "grpcio", - "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/securitycenter_v1beta1/', - '--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( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): - # Ignore release of mypy 1.11.0 which may have a regression - 'mypy!=1.11.0', - '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-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_async.py deleted file mode 100644 index e2ccd162023c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_create_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_sync.py deleted file mode 100644 index 8a6cd38a65ea..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_create_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_async.py deleted file mode 100644 index b705b58ee221..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_CreateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_create_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_source_sync.py deleted file mode 100644 index ed1f60c4c944..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_CreateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_create_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py deleted file mode 100644 index 8f5186953423..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py deleted file mode 100644 index 74daec484fa2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py deleted file mode 100644 index e21dbe268313..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_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 GetOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py deleted file mode 100644 index 40c62b6f158e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_organization_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 GetOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_async.py deleted file mode 100644 index 92eeeb159eb1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GetSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_get_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_source_sync.py deleted file mode 100644 index 4432d6697cb8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GetSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_get_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_async.py deleted file mode 100644 index 7bc11cd58a3d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_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 GroupAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_group_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_sync.py deleted file mode 100644 index b5a0c8f1322b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_assets_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 GroupAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_group_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_async.py deleted file mode 100644 index 367437acd112..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_group_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_findings_sync.py deleted file mode 100644 index 2b3cdac52e46..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_group_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_async.py deleted file mode 100644 index 80d46cf5ce6f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_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 ListAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_ListAssets_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_list_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_sync.py deleted file mode 100644 index 6f45a7b22700..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_assets_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 ListAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_ListAssets_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_list_assets(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_async.py deleted file mode 100644 index 3ee6027b07d6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_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 securitycenter_v1beta1 - - -async def sample_list_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_sync.py deleted file mode 100644 index 6a9a7c526574..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_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 securitycenter_v1beta1 - - -def sample_list_findings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_async.py deleted file mode 100644 index ced7ea701eeb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_ListSources_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_list_sources(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_sources_sync.py deleted file mode 100644 index 3eff727dc701..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_ListSources_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_list_sources(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py deleted file mode 100644 index 7ec0a72a67a5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py deleted file mode 100644 index 7efbac655d2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_async.py deleted file mode 100644 index f9245b6f398e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_set_finding_state(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py deleted file mode 100644 index a2b160db84a8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_set_finding_state(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py deleted file mode 100644 index 9863d798d645..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py deleted file mode 100644 index ddac6e4fadb8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py deleted file mode 100644 index f1ecc97a8e8c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py deleted file mode 100644 index 87f3b0ee6c7b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_async.py deleted file mode 100644 index 8f8e6f58f99f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_update_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_finding_sync.py deleted file mode 100644 index 9c214219e880..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_update_finding(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py deleted file mode 100644 index 8174ebf4f93b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = await client.update_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py deleted file mode 100644 index b587f61c0ce3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = client.update_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_async.py deleted file mode 100644 index 230075087471..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_update_security_marks(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py deleted file mode 100644 index f041a1b1fa1a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_update_security_marks(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_async.py deleted file mode 100644 index 3afe218c0c83..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -async def sample_update_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_sync.py deleted file mode 100644 index 0ff7573f017d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/securitycenter_v1beta1_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1beta1 - - -def sample_update_source(): - # Create a client - client = securitycenter_v1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1beta1.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json b/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json deleted file mode 100644 index a4c1295eaf99..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json +++ /dev/null @@ -1,2945 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.securitycenter.v1beta1", - "version": "v1beta1" - } - ], - "language": "PYTHON", - "name": "google-cloud-securitycenter", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1beta1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v1beta1_generated_security_center_create_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1beta1_generated_security_center_create_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1beta1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v1beta1_generated_security_center_create_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1beta1_generated_security_center_create_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1beta1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v1beta1_generated_security_center_create_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_create_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1beta1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v1beta1_generated_security_center_create_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_CreateSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_create_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.get_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest" - }, - { - "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.securitycenter_v1beta1.types.OrganizationSettings", - "shortName": "get_organization_settings" - }, - "description": "Sample for GetOrganizationSettings", - "file": "securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_get_organization_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.get_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest" - }, - { - "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.securitycenter_v1beta1.types.OrganizationSettings", - "shortName": "get_organization_settings" - }, - "description": "Sample for GetOrganizationSettings", - "file": "securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetOrganizationSettings_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_get_organization_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GetSourceRequest" - }, - { - "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.securitycenter_v1beta1.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v1beta1_generated_security_center_get_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_get_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GetSourceRequest" - }, - { - "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.securitycenter_v1beta1.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v1beta1_generated_security_center_get_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GetSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_get_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.group_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsAsyncPager", - "shortName": "group_assets" - }, - "description": "Sample for GroupAssets", - "file": "securitycenter_v1beta1_generated_security_center_group_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1beta1_generated_security_center_group_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.group_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsPager", - "shortName": "group_assets" - }, - "description": "Sample for GroupAssets", - "file": "securitycenter_v1beta1_generated_security_center_group_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1beta1_generated_security_center_group_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsAsyncPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v1beta1_generated_security_center_group_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1beta1_generated_security_center_group_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v1beta1_generated_security_center_group_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1beta1_generated_security_center_group_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.list_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.ListAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsAsyncPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "securitycenter_v1beta1_generated_security_center_list_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1beta1_generated_security_center_list_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.list_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.ListAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "securitycenter_v1beta1_generated_security_center_list_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1beta1_generated_security_center_list_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.ListFindingsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsAsyncPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v1beta1_generated_security_center_list_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1beta1_generated_security_center_list_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.ListFindingsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v1beta1_generated_security_center_list_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1beta1_generated_security_center_list_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.ListSourcesRequest" - }, - { - "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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesAsyncPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v1beta1_generated_security_center_list_sources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1beta1_generated_security_center_list_sources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.ListSourcesRequest" - }, - { - "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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v1beta1_generated_security_center_list_sources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1beta1_generated_security_center_list_sources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.run_asset_discovery", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.RunAssetDiscovery", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "RunAssetDiscovery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "run_asset_discovery" - }, - "description": "Sample for RunAssetDiscovery", - "file": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.run_asset_discovery", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.RunAssetDiscovery", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "RunAssetDiscovery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "run_asset_discovery" - }, - "description": "Sample for RunAssetDiscovery", - "file": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1beta1_generated_security_center_run_asset_discovery_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v1beta1.types.Finding.State" - }, - { - "name": "start_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v1beta1_generated_security_center_set_finding_state_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1beta1_generated_security_center_set_finding_state_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v1beta1.types.Finding.State" - }, - { - "name": "start_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1beta1_generated_security_center_set_finding_state_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1beta1_generated_security_center_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1beta1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v1beta1_generated_security_center_update_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1beta1_generated_security_center_update_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1beta1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v1beta1_generated_security_center_update_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1beta1_generated_security_center_update_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest" - }, - { - "name": "organization_settings", - "type": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings", - "shortName": "update_organization_settings" - }, - "description": "Sample for UpdateOrganizationSettings", - "file": "securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1beta1_generated_security_center_update_organization_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest" - }, - { - "name": "organization_settings", - "type": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.OrganizationSettings", - "shortName": "update_organization_settings" - }, - "description": "Sample for UpdateOrganizationSettings", - "file": "securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1beta1_generated_security_center_update_organization_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v1beta1.types.SecurityMarks" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v1beta1_generated_security_center_update_security_marks_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1beta1_generated_security_center_update_security_marks_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v1beta1.types.SecurityMarks" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1beta1_generated_security_center_update_security_marks_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterAsyncClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1beta1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v1beta1_generated_security_center_update_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1beta1_generated_security_center_update_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1beta1.SecurityCenterClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1beta1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1beta1.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v1beta1_generated_security_center_update_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1beta1_generated_security_center_update_source_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py deleted file mode 100644 index e4b81a3218c2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py +++ /dev/null @@ -1,193 +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 securitycenterCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_source': ('parent', 'source', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_organization_settings': ('name', ), - 'get_source': ('name', ), - 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), - 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'page_token', 'page_size', ), - 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'field_mask', 'page_token', 'page_size', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'run_asset_discovery': ('parent', ), - 'set_finding_state': ('name', 'state', 'start_time', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_organization_settings': ('organization_settings', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), - 'update_source': ('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=securitycenterCallTransformer(), -): - """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 securitycenter 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-securitycenter/v1beta1/setup.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/setup.py deleted file mode 100644 index c4538ec101f3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/setup.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. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-securitycenter' - - -description = "Google Cloud Securitycenter API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/securitycenter/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", - "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", -] -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" - -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v1beta1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/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-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__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-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py deleted file mode 100644 index 1ba9f20c0bed..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py +++ /dev/null @@ -1,14372 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -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 - -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.securitycenter_v1beta1.services.security_center import SecurityCenterAsyncClient -from google.cloud.securitycenter_v1beta1.services.security_center import SecurityCenterClient -from google.cloud.securitycenter_v1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1beta1.services.security_center import transports -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -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 duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None - assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert SecurityCenterClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SecurityCenterGrpcTransport, "grpc"), - (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - 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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -def test_security_center_client_get_transport_class(): - transport = SecurityCenterClient.get_transport_class() - available_transports = [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterRestTransport, - ] - assert transport in available_transports - - transport = SecurityCenterClient.get_transport_class("grpc") - assert transport == transports.SecurityCenterGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, 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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), -]) -def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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_security_center_client_client_options_from_dict(): - with mock.patch('google.cloud.securitycenter_v1beta1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_create_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object - - request = {} - await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_create_source_async_from_dict(): - await test_create_source_async(request_type=dict) - - -def test_create_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.create_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - - -def test_create_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - response = client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -def test_create_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.create_finding] = mock_rpc - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object - - request = {} - await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -@pytest.mark.asyncio -async def test_create_finding_async_from_dict(): - await test_create_finding_async(request_type=dict) - - -def test_create_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - arg = args[0].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - - -def test_create_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - arg = args[0].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.GetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest( - resource='resource_value', - ) - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object - - request = {} - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_get_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetOrganizationSettingsRequest, - dict, -]) -def test_get_organization_settings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_get_organization_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetOrganizationSettingsRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_organization_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest( - name='name_value', - ) - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_organization_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_organization_settings] = mock_rpc - request = {} - client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_organization_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_organization_settings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - -@pytest.mark.asyncio -async def test_get_organization_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_organization_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_organization_settings] = mock_object - - request = {} - await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_organization_settings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_get_organization_settings_async_from_dict(): - await test_get_organization_settings_async(request_type=dict) - - -def test_get_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = organization_settings.OrganizationSettings() - client.get_organization_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_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - await client.get_organization_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_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_organization_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_organization_settings_flattened_error(): - client = SecurityCenterClient( - credentials=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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_organization_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_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_get_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest( - name='name_value', - ) - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - -@pytest.mark.asyncio -async def test_get_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object - - request = {} - await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_get_source_async_from_dict(): - await test_get_source_async(request_type=dict) - - -def test_get_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = source.Source() - client.get_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_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_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_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_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupAssetsRequest, - dict, -]) -def test_group_assets(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - ) - response = client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_group_assets_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - -def test_group_assets_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupAssetsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_assets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_assets_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc - request = {} - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_group_assets_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - )) - response = await client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - -@pytest.mark.asyncio -async def test_group_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_assets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_assets] = mock_object - - request = {} - await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - )) - response = await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_group_assets_async_from_dict(): - await test_group_assets_async(request_type=dict) - - -def test_group_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = securitycenter_service.GroupAssetsResponse() - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_group_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) - await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_group_assets_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_assets(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, securitycenter_service.GroupResult) - for i in results) -def test_group_assets_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_assets(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_group_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_assets(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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_assets(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", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - ) - response = client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_group_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - -@pytest.mark.asyncio -async def test_group_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_findings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object - - request = {} - await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_findings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_group_findings_async_from_dict(): - await test_group_findings_async(request_type=dict) - - -def test_group_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_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_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - await client.group_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_group_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that the 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - - -def test_group_findings_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - -@pytest.mark.asyncio -async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_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, securitycenter_service.GroupResult) - for i in results) -def test_group_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_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_group_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_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", [ - securitycenter_service.ListAssetsRequest, - dict, -]) -def test_list_assets(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_assets_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - -def test_list_assets_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListAssetsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_assets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_value', - page_token='page_token_value', - ) - -def test_list_assets_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc - request = {} - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_assets_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - -@pytest.mark.asyncio -async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_assets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object - - request = {} - await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_assets_async_from_dict(): - await test_list_assets_async(request_type=dict) - - -def test_list_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = securitycenter_service.ListAssetsResponse() - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) - await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_assets_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) -def test_list_assets_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_assets(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_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - 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_assets(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", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -def test_list_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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] == securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - -@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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object - - request = {} - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -@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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.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 = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.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 = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.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 = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.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", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_sources_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListSourcesRequest( - 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_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - -@pytest.mark.asyncio -async def test_list_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_sources in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object - - request = {} - await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_sources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_sources_async_from_dict(): - await test_list_sources_async(request_type=dict) - - -def test_list_sources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = securitycenter_service.ListSourcesResponse() - client.list_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_sources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - await client.list_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_sources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_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_sources_flattened_error(): - client = SecurityCenterClient( - credentials=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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_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_sources_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_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, source.Source) - for i in results) -def test_list_sources_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = list(client.list_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_sources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_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, source.Source) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - 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_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", [ - securitycenter_service.RunAssetDiscoveryRequest, - dict, -]) -def test_run_asset_discovery(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.RunAssetDiscoveryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_run_asset_discovery_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - -def test_run_asset_discovery_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.RunAssetDiscoveryRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.run_asset_discovery(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest( - parent='parent_value', - ) - -def test_run_asset_discovery_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.run_asset_discovery in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc - request = {} - client.run_asset_discovery(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.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_run_asset_discovery_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - -@pytest.mark.asyncio -async def test_run_asset_discovery_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.run_asset_discovery in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.run_asset_discovery] = mock_object - - request = {} - await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.RunAssetDiscoveryRequest() - 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_run_asset_discovery_async_from_dict(): - await test_run_asset_discovery_async(request_type=dict) - - -def test_run_asset_discovery_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_run_asset_discovery_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_run_asset_discovery_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery( - 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_run_asset_discovery_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_run_asset_discovery_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery( - 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_run_asset_discovery_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - response = client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -def test_set_finding_state_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - -@pytest.mark.asyncio -async def test_set_finding_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object - - request = {} - await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_finding_state(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -@pytest.mark.asyncio -async def test_set_finding_state_async_from_dict(): - await test_set_finding_state_async(request_type=dict) - - -def test_set_finding_state_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = finding.Finding() - client.set_finding_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_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_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_set_finding_state_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - - -def test_set_finding_state_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.SetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest( - resource='resource_value', - ) - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object - - request = {} - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = SecurityCenterClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.TestIamPermissionsRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( - resource='resource_value', - ) - -def test_test_iam_permissions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object - - request = {} - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - response = client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -def test_update_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateFindingRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.update_finding] = mock_rpc - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object - - request = {} - await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -@pytest.mark.asyncio -async def test_update_finding_async_from_dict(): - await test_update_finding_async(request_type=dict) - - -def test_update_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -def test_update_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_finding( - finding=gcs_finding.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].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - - -def test_update_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_finding( - finding=gcs_finding.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].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateOrganizationSettingsRequest, - dict, -]) -def test_update_organization_settings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_update_organization_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateOrganizationSettingsRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_organization_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest( - ) - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_organization_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_organization_settings] = mock_rpc - request = {} - client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_organization_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_organization_settings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - -@pytest.mark.asyncio -async def test_update_organization_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_organization_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_organization_settings] = mock_object - - request = {} - await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_organization_settings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_update_organization_settings_async_from_dict(): - await test_update_organization_settings_async(request_type=dict) - - -def test_update_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = gcs_organization_settings.OrganizationSettings() - client.update_organization_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', - 'organization_settings.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - await client.update_organization_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', - 'organization_settings.name=name_value', - ) in kw['metadata'] - - -def test_update_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].organization_settings - mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') - assert arg == mock_val - - -def test_update_organization_settings_flattened_error(): - client = SecurityCenterClient( - credentials=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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].organization_settings - mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_update_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSourceRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object - - request = {} - await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_update_source_async_from_dict(): - await test_update_source_async(request_type=dict) - - -def test_update_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -def test_update_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_source( - source=gcs_source.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].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - - -def test_update_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_source( - source=gcs_source.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].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks( - name='name_value', - ) - response = client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - - -def test_update_security_marks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - -def test_update_security_marks_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSecurityMarksRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( - ) - -def test_update_security_marks_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish that a new wrapper 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_security_marks_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - )) - response = await client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - -@pytest.mark.asyncio -async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_marks in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object - - request = {} - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_security_marks(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - )) - response = await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_update_security_marks_async_from_dict(): - await test_update_security_marks_async(request_type=dict) - - -def test_update_security_marks_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -def test_update_security_marks_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].security_marks - mock_val = gcs_security_marks.SecurityMarks(name='name_value') - assert arg == mock_val - - -def test_update_security_marks_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].security_marks - mock_val = gcs_security_marks.SecurityMarks(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': '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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.CreateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_source(request) - - -def test_create_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_create_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -def test_create_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request_init["finding"] = {'name': 'name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.create_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.create_finding] = mock_rpc - - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["finding_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 "findingId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "findingId" in jsonified_request - assert jsonified_request["findingId"] == request_init["finding_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["findingId"] = 'finding_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request - assert jsonified_request["findingId"] == 'finding_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.create_finding(request) - - expected_params = [ - ( - "findingId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.CreateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_finding(request) - - -def test_create_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(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 = gcs_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.create_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/v1beta1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) - - -def test_create_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_create_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.get_iam_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/v1beta1/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetOrganizationSettingsRequest, - dict, -]) -def test_get_organization_settings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/organizationSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_organization_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_organization_settings] = mock_rpc - - request = {} - client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.GetOrganizationSettingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_organization_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_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_organization_settings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_organization_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_organization_settings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_organization_settings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_organization_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetOrganizationSettingsRequest.pb(securitycenter_service.GetOrganizationSettingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = organization_settings.OrganizationSettings.to_json(organization_settings.OrganizationSettings()) - - request = securitycenter_service.GetOrganizationSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = organization_settings.OrganizationSettings() - - client.get_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/organizationSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_organization_settings(request) - - -def test_get_organization_settings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/organizationSettings'} - - # get truthy value for each flattened field - mock_args = dict( - 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 = organization_settings.OrganizationSettings.pb(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_organization_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/v1beta1/{name=organizations/*/organizationSettings}" % client.transport._host, args[1]) - - -def test_get_organization_settings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -def test_get_organization_settings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/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 = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = source.Source.to_json(source.Source()) - - request = securitycenter_service.GetSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = source.Source() - - client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_source(request) - - -def test_get_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v1beta1/{name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_get_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -def test_get_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupAssetsRequest, - dict, -]) -def test_group_assets_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_group_assets_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc - - request = {} - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_group_assets_rest_required_fields(request_type=securitycenter_service.GroupAssetsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupAssetsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_assets_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_assets_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_assets") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupAssetsRequest.pb(securitycenter_service.GroupAssetsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupAssetsResponse.to_json(securitycenter_service.GroupAssetsResponse()) - - request = securitycenter_service.GroupAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupAssetsResponse() - - client.group_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_assets(request) - - -def test_group_assets_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupAssetsResponse.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': 'organizations/sample1'} - - pager = client.group_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_findings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_findings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_findings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) - - request = securitycenter_service.GroupFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupFindingsResponse() - - client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_findings(request) - - -def test_group_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - group_by='group_by_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v1beta1/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) - - -def test_group_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} - - pager = client.group_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_findings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListAssetsRequest, - dict, -]) -def test_list_assets_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListAssetsResponse.pb(return_value) - 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_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_list_assets_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc - - request = {} - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_assets(request) - - # Establish 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_assets_rest_required_fields(request_type=securitycenter_service.ListAssetsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_assets._get_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_assets._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) - jsonified_request.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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAssetsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListAssetsResponse.pb(return_value) - 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_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_assets_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_assets_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_assets") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListAssetsRequest.pb(securitycenter_service.ListAssetsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListAssetsResponse.to_json(securitycenter_service.ListAssetsResponse()) - - request = securitycenter_service.ListAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListAssetsResponse() - - client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_assets(request) - - -def test_list_assets_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListAssetsResponse.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': 'organizations/sample1'} - - pager = client.list_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) - - pages = list(client.list_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.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' - assert response.total_size == 1086 - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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=securitycenter_service.ListFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) - jsonified_request.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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.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 = securitycenter_service.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 = [ - ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) - - request = securitycenter_service.ListFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListFindingsResponse() - - client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_findings(request) - - -def test_list_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} - - 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 - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_sources_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_sources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_sources_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) - - request = securitycenter_service.ListSourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListSourcesResponse() - - client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_sources(request) - - -def test_list_sources_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_list_sources_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} - - pager = client.list_sources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, source.Source) - for i in results) - - pages = list(client.list_sources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.RunAssetDiscoveryRequest, - dict, -]) -def test_run_asset_discovery_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') - - # 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 - response = client.run_asset_discovery(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_run_asset_discovery_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.run_asset_discovery in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc - - request = {} - client.run_asset_discovery(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.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_run_asset_discovery_rest_required_fields(request_type=securitycenter_service.RunAssetDiscoveryRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_asset_discovery._get_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()).run_asset_discovery._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 = SecurityCenterClient( - 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.run_asset_discovery(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_run_asset_discovery_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.run_asset_discovery._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_run_asset_discovery_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_run_asset_discovery") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_run_asset_discovery") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.RunAssetDiscoveryRequest.pb(securitycenter_service.RunAssetDiscoveryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = securitycenter_service.RunAssetDiscoveryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.run_asset_discovery(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_run_asset_discovery_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.run_asset_discovery(request) - - -def test_run_asset_discovery_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.run_asset_discovery(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{parent=organizations/*}/assets:runDiscovery" % client.transport._host, args[1]) - - -def test_run_asset_discovery_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -def test_run_asset_discovery_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - - # 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 - response = client.set_finding_state(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( - 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': "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 = 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.set_finding_state(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_finding_state_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_finding_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "state", "startTime", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_finding_state_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = finding.Finding.to_json(finding.Finding()) - - request = securitycenter_service.SetFindingStateRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_finding_state(request) - - -def test_set_finding_state_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - mock_args.update(sample_request) - - # 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.set_finding_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/v1beta1/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) - - -def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -def test_set_finding_state_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.set_iam_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/v1beta1/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # 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 - response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_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.test_iam_permissions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.update_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.update_finding] = mock_rpc - - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_finding._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_finding._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.update_finding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.UpdateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_finding(request) - - -def test_update_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - finding=gcs_finding.Finding(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 = gcs_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.update_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/v1beta1/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) - - -def test_update_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_update_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateOrganizationSettingsRequest, - dict, -]) -def test_update_organization_settings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - request_init["organization_settings"] = {'name': 'organizations/sample1/organizationSettings', 'enable_asset_discovery': True, 'asset_discovery_config': {'project_ids': ['project_ids_value1', 'project_ids_value2'], 'inclusion_mode': 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 = securitycenter_service.UpdateOrganizationSettingsRequest.meta.fields["organization_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["organization_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["organization_settings"][field])): - del request_init["organization_settings"][field][i][subfield] - else: - del request_init["organization_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 = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_organization_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_organization_settings] = mock_rpc - - request = {} - client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_organization_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_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_organization_settings.OrganizationSettings() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_organization_settings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_organization_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("organizationSettings", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_organization_settings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_organization_settings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_organization_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateOrganizationSettingsRequest.pb(securitycenter_service.UpdateOrganizationSettingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_organization_settings.OrganizationSettings.to_json(gcs_organization_settings.OrganizationSettings()) - - request = securitycenter_service.UpdateOrganizationSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_organization_settings.OrganizationSettings() - - client.update_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_organization_settings(request) - - -def test_update_organization_settings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_organization_settings.OrganizationSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - - # get truthy value for each flattened field - mock_args = dict( - organization_settings=gcs_organization_settings.OrganizationSettings(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 = gcs_organization_settings.OrganizationSettings.pb(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_organization_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/v1beta1/{organization_settings.name=organizations/*/organizationSettings}" % client.transport._host, args[1]) - - -def test_update_organization_settings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -def test_update_organization_settings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': '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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.UpdateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_source(request) - - -def test_update_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1beta1/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_update_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - - -def test_update_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - request_init["security_marks"] = {'name': 'organizations/sample1/assets/sample2/securityMarks', 'marks': {}} - # The version of a generated dependency at test runtime may differ from the version used 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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] - - 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["security_marks"].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["security_marks"][field])): - del request_init["security_marks"][field][i][subfield] - else: - del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( - name='name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - -def test_update_security_marks_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_security_marks._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_security_marks._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("start_time", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_security_marks_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_security_marks._get_unset_required_fields({}) - assert set(unset_fields) == (set(("startTime", "updateMask", )) & set(("securityMarks", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_security_marks_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) - - request = securitycenter_service.UpdateSecurityMarksRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_security_marks.SecurityMarks() - - client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_security_marks(request) - - -def test_update_security_marks_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - - # get arguments that satisfy an http rule for this method - sample_request = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - - # get truthy value for each flattened field - mock_args = dict( - security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}" % client.transport._host, args[1]) - - -def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - -def test_update_security_marks_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SecurityCenterClient( - 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 = SecurityCenterClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SecurityCenterClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SecurityCenterClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SecurityCenterGrpcTransport, - ) - -def test_security_center_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_security_center_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_source', - 'create_finding', - 'get_iam_policy', - 'get_organization_settings', - 'get_source', - 'group_assets', - 'group_findings', - 'list_assets', - 'list_findings', - 'list_sources', - 'run_asset_discovery', - 'set_finding_state', - 'set_iam_policy', - 'test_iam_permissions', - 'update_finding', - 'update_organization_settings', - 'update_source', - 'update_security_marks', - ) - 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_security_center_base_transport_with_credentials_file(): - # Instantiate the 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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - 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_security_center_base_transport_with_adc(): - # Test the default 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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport() - adc.assert_called_once() - - -def test_security_center_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) - SecurityCenterClient() - 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -def test_security_center_transport_auth_adc(transport_class): - # If 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, - ], -) -def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), - (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_security_center_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host 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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_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.SecurityCenterRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_security_center_rest_lro_client(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a 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 - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_no_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_with_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_security_center_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SecurityCenterClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SecurityCenterClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_source._session - session2 = client2.transport.create_source._session - assert session1 != session2 - session1 = client1.transport.create_finding._session - session2 = client2.transport.create_finding._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.get_organization_settings._session - session2 = client2.transport.get_organization_settings._session - assert session1 != session2 - session1 = client1.transport.get_source._session - session2 = client2.transport.get_source._session - assert session1 != session2 - session1 = client1.transport.group_assets._session - session2 = client2.transport.group_assets._session - assert session1 != session2 - session1 = client1.transport.group_findings._session - session2 = client2.transport.group_findings._session - assert session1 != session2 - session1 = client1.transport.list_assets._session - session2 = client2.transport.list_assets._session - assert session1 != session2 - session1 = client1.transport.list_findings._session - session2 = client2.transport.list_findings._session - assert session1 != session2 - session1 = client1.transport.list_sources._session - session2 = client2.transport.list_sources._session - assert session1 != session2 - session1 = client1.transport.run_asset_discovery._session - session2 = client2.transport.run_asset_discovery._session - assert session1 != session2 - session1 = client1.transport.set_finding_state._session - session2 = client2.transport.set_finding_state._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 - session1 = client1.transport.update_finding._session - session2 = client2.transport.update_finding._session - assert session1 != session2 - session1 = client1.transport.update_organization_settings._session - session2 = client2.transport.update_organization_settings._session - assert session1 != session2 - session1 = client1.transport.update_source._session - session2 = client2.transport.update_source._session - assert session1 != session2 - session1 = client1.transport.update_security_marks._session - session2 = client2.transport.update_security_marks._session - assert session1 != session2 -def test_security_center_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcTransport( - 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_security_center_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcAsyncIOTransport( - 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(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_security_center_grpc_lro_client(): - client = SecurityCenterClient( - 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_security_center_grpc_lro_async_client(): - client = SecurityCenterAsyncClient( - 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_asset_path(): - organization = "squid" - asset = "clam" - expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.asset_path(organization, asset) - assert expected == actual - - -def test_parse_asset_path(): - expected = { - "organization": "whelk", - "asset": "octopus", - } - path = SecurityCenterClient.asset_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_asset_path(path) - assert expected == actual - -def test_finding_path(): - organization = "oyster" - source = "nudibranch" - finding = "cuttlefish" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - actual = SecurityCenterClient.finding_path(organization, source, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "organization": "mussel", - "source": "winkle", - "finding": "nautilus", - } - path = SecurityCenterClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_finding_path(path) - assert expected == actual - -def test_organization_settings_path(): - organization = "scallop" - expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) - actual = SecurityCenterClient.organization_settings_path(organization) - assert expected == actual - - -def test_parse_organization_settings_path(): - expected = { - "organization": "abalone", - } - path = SecurityCenterClient.organization_settings_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_organization_settings_path(path) - assert expected == actual - -def test_security_marks_path(): - organization = "squid" - asset = "clam" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.security_marks_path(organization, asset) - assert expected == actual - - -def test_parse_security_marks_path(): - expected = { - "organization": "whelk", - "asset": "octopus", - } - path = SecurityCenterClient.security_marks_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_security_marks_path(path) - assert expected == actual - -def test_source_path(): - organization = "oyster" - source = "nudibranch" - expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - actual = SecurityCenterClient.source_path(organization, source) - assert expected == actual - - -def test_parse_source_path(): - expected = { - "organization": "cuttlefish", - "source": "mussel", - } - path = SecurityCenterClient.source_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_source_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SecurityCenterClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = SecurityCenterClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = SecurityCenterClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = SecurityCenterClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SecurityCenterClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = SecurityCenterClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = SecurityCenterClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = SecurityCenterClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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 = SecurityCenterClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = SecurityCenterClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - transport_class = SecurityCenterClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), -]) -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-securitycenter/v1p1beta1/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.coveragerc deleted file mode 100644 index 45cb273f8f7c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/securitycenter/__init__.py - google/cloud/securitycenter/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-securitycenter/v1p1beta1/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/.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-securitycenter/v1p1beta1/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/MANIFEST.in deleted file mode 100644 index 57b563bd1a48..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/securitycenter *.py -recursive-include google/cloud/securitycenter_v1p1beta1 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst deleted file mode 100644 index f8c63f4cb48a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v1p1beta1/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/conf.py deleted file mode 100644 index 8e92d2319721..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter 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-securitycenter" -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-securitycenter-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-securitycenter.tex", - u"google-cloud-securitycenter 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-securitycenter", - u"Google Cloud Securitycenter 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-securitycenter", - u"google-cloud-securitycenter Documentation", - author, - "google-cloud-securitycenter", - "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v1p1beta1/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/index.rst deleted file mode 100644 index 45263147b433..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - securitycenter_v1p1beta1/services - securitycenter_v1p1beta1/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst deleted file mode 100644 index adab7f4a5e87..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst +++ /dev/null @@ -1,10 +0,0 @@ -SecurityCenter --------------------------------- - -.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center - :members: - :inherited-members: - -.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst deleted file mode 100644 index 7f537e851e63..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Securitycenter v1p1beta1 API -====================================================== -.. toctree:: - :maxdepth: 2 - - security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst deleted file mode 100644 index a68ac5c68cff..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/docs/securitycenter_v1p1beta1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Securitycenter v1p1beta1 API -=================================================== - -.. automodule:: google.cloud.securitycenter_v1p1beta1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py deleted file mode 100644 index fe0af04fb73b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/__init__.py +++ /dev/null @@ -1,101 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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.securitycenter import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.securitycenter_v1p1beta1.services.security_center.client import SecurityCenterClient -from google.cloud.securitycenter_v1p1beta1.services.security_center.async_client import SecurityCenterAsyncClient - -from google.cloud.securitycenter_v1p1beta1.types.asset import Asset -from google.cloud.securitycenter_v1p1beta1.types.finding import Finding -from google.cloud.securitycenter_v1p1beta1.types.folder import Folder -from google.cloud.securitycenter_v1p1beta1.types.notification_config import NotificationConfig -from google.cloud.securitycenter_v1p1beta1.types.notification_message import NotificationMessage -from google.cloud.securitycenter_v1p1beta1.types.organization_settings import OrganizationSettings -from google.cloud.securitycenter_v1p1beta1.types.resource import Resource -from google.cloud.securitycenter_v1p1beta1.types.run_asset_discovery_response import RunAssetDiscoveryResponse -from google.cloud.securitycenter_v1p1beta1.types.security_marks import SecurityMarks -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateFindingRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateNotificationConfigRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateSourceRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import DeleteNotificationConfigRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetNotificationConfigRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetOrganizationSettingsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetSourceRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupAssetsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupAssetsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupFindingsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupFindingsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupResult -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListAssetsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListAssetsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListFindingsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListFindingsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListNotificationConfigsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListNotificationConfigsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListSourcesRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListSourcesResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import RunAssetDiscoveryRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import SetFindingStateRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateFindingRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateNotificationConfigRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateOrganizationSettingsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateSecurityMarksRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateSourceRequest -from google.cloud.securitycenter_v1p1beta1.types.source import Source - -__all__ = ('SecurityCenterClient', - 'SecurityCenterAsyncClient', - 'Asset', - 'Finding', - 'Folder', - 'NotificationConfig', - 'NotificationMessage', - 'OrganizationSettings', - 'Resource', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateNotificationConfigRequest', - 'CreateSourceRequest', - 'DeleteNotificationConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/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-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py deleted file mode 100644 index 84391a72a3b7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__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 google.cloud.securitycenter_v1p1beta1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.security_center import SecurityCenterClient -from .services.security_center import SecurityCenterAsyncClient - -from .types.asset import Asset -from .types.finding import Finding -from .types.folder import Folder -from .types.notification_config import NotificationConfig -from .types.notification_message import NotificationMessage -from .types.organization_settings import OrganizationSettings -from .types.resource import Resource -from .types.run_asset_discovery_response import RunAssetDiscoveryResponse -from .types.security_marks import SecurityMarks -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateNotificationConfigRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import DeleteNotificationConfigRequest -from .types.securitycenter_service import GetNotificationConfigRequest -from .types.securitycenter_service import GetOrganizationSettingsRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GroupAssetsRequest -from .types.securitycenter_service import GroupAssetsResponse -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAssetsRequest -from .types.securitycenter_service import ListAssetsResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListNotificationConfigsRequest -from .types.securitycenter_service import ListNotificationConfigsResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import RunAssetDiscoveryRequest -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateNotificationConfigRequest -from .types.securitycenter_service import UpdateOrganizationSettingsRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.source import Source - -__all__ = ( - 'SecurityCenterAsyncClient', -'Asset', -'CreateFindingRequest', -'CreateNotificationConfigRequest', -'CreateSourceRequest', -'DeleteNotificationConfigRequest', -'Finding', -'Folder', -'GetNotificationConfigRequest', -'GetOrganizationSettingsRequest', -'GetSourceRequest', -'GroupAssetsRequest', -'GroupAssetsResponse', -'GroupFindingsRequest', -'GroupFindingsResponse', -'GroupResult', -'ListAssetsRequest', -'ListAssetsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListNotificationConfigsRequest', -'ListNotificationConfigsResponse', -'ListSourcesRequest', -'ListSourcesResponse', -'NotificationConfig', -'NotificationMessage', -'OrganizationSettings', -'Resource', -'RunAssetDiscoveryRequest', -'RunAssetDiscoveryResponse', -'SecurityCenterClient', -'SecurityMarks', -'SetFindingStateRequest', -'Source', -'UpdateFindingRequest', -'UpdateNotificationConfigRequest', -'UpdateOrganizationSettingsRequest', -'UpdateSecurityMarksRequest', -'UpdateSourceRequest', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json deleted file mode 100644 index 892a85e5f9fd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json +++ /dev/null @@ -1,373 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.securitycenter_v1p1beta1", - "protoPackage": "google.cloud.securitycenter.v1p1beta1", - "schema": "1.0", - "services": { - "SecurityCenter": { - "clients": { - "grpc": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SecurityCenterAsyncClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "rest": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py deleted file mode 100644 index bffcff5da306..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - 'SecurityCenterClient', - 'SecurityCenterAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py deleted file mode 100644 index a996989322a3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py +++ /dev/null @@ -1,3039 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.securitycenter_v1p1beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.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.securitycenter_v1p1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1p1beta1.types import security_marks -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_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 SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V1p1Beta1 APIs for Security Center service.""" - - _client: SecurityCenterClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE - - asset_path = staticmethod(SecurityCenterClient.asset_path) - parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) - parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) - notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) - parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) - organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) - parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) - source_path = staticmethod(SecurityCenterClient.source_path) - parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) - topic_path = staticmethod(SecurityCenterClient.topic_path) - parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) - common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) - parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) - common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) - parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) - parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) - parse_common_location_path = staticmethod(SecurityCenterClient.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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v1p1beta1 - - async def sample_create_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest, dict]]): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = 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_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding_id: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_create_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest, dict]]): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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 create_notification_config(self, - request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - config_id: Optional[str] = None, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_create_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.create_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest, dict]]): - The request object. Request message for creating a - notification config. - parent (:class:`str`): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be between 1 and 128 characters, - and contains alphanumeric characters, - underscores or hyphens only. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_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.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_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_notification_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_notification_config(self, - request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest, dict]]): - The request object. Request message for deleting a - notification config. - name (:class:`str`): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1p1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 get_notification_config(self, - request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_get_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest, dict]]): - The request object. Request message for getting a - notification config. - name (:class:`str`): - Required. Name of the notification config to get. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 get_organization_settings(self, - request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest, dict]]): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_organization_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 get_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v1p1beta1 - - async def sample_get_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest, dict]]): - The request object. Request message for getting a source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 group_assets(self, - request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsAsyncPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_group_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest, dict]]): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsAsyncPager: - Response message for grouping by - assets. - 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, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.GroupAssetsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_group_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest, dict]]): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]", - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]. To groupBy - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/-, or - projects/{project_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - severity - - The following fields are supported when compare_duration - is set: - - - state_change - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_assets(self, - request: Optional[Union[securitycenter_service.ListAssetsRequest, 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.ListAssetsAsyncPager: - r"""Lists an organization's assets. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_list_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest, dict]]): - The request object. Request message for listing assets. - parent (:class:`str`): - Required. Name of the organization assets should belong - to. Its format is "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsAsyncPager: - Response message for listing assets. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListAssetsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings(self, - request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsAsyncPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_list_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListFindingsRequest( - parent="parent_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.securitycenter_v1p1beta1.types.ListFindingsRequest, dict]]): - The request object. Request message for listing findings. - parent (:class:`str`): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id], - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]". To list - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/- or - projects/{projects_id}/sources/- - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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_notification_configs(self, - request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsAsyncPager: - r"""Lists notification configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest, dict]]): - The request object. Request message for listing - notification configs. - parent (:class:`str`): - Required. Name of the organization to list notification - configs. Its format is - "organizations/[organization_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsAsyncPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListNotificationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_list_sources(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest, dict]]): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id], folders/[folder_id], - or projects/[project_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesAsyncPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_asset_discovery(self, - request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), - ) -> operation_async.AsyncOperation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS 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 securitycenter_v1p1beta1 - - async def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest, dict]]): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` - Response of asset discovery run - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - async def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - start_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of 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 securitycenter_v1p1beta1 - - async def sample_set_finding_state(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest, dict]]): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding.State`): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1p1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v1p1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 update_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - update_mask: 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]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_update_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest, dict]]): - The request object. Request message for updating or - creating a finding. - finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a - finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing - source_properties. Individual source_properties can be - added/updated by using "source_properties." in the field - mask. - - 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.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - 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_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe domain. - self._client._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_config(self, - request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, - *, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - update_mask: 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]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_update_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = await client.update_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest, dict]]): - The request object. Request message for updating a - notification config. - notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the notification config. - If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_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 update_organization_settings(self, - request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, - *, - organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = await client.update_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest, dict]]): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings`): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_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 update_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - update_mask: 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]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v1p1beta1 - - async def sample_update_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest, dict]]): - The request object. Request message for updating a - source. - source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): - Required. The source resource to - update. - - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the source resource. - If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = 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_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - update_mask: 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]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - async def sample_update_security_marks(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest, dict]]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`google.cloud.securitycenter_v1p1beta1.types.SecurityMarks`): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If - empty or set to "marks", all marks will be replaced. - Individual marks can be updated using - "marks.". - - 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.securitycenter_v1p1beta1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - 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_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe domain. - self._client._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) -> "SecurityCenterAsyncClient": - 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__ = ( - "SecurityCenterAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py deleted file mode 100644 index caeded73d36f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py +++ /dev/null @@ -1,3441 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_v1p1beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from 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.securitycenter_v1p1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1p1beta1.types import security_marks -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_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 SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .transports.rest import SecurityCenterRestTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - _transport_registry["rest"] = SecurityCenterRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SecurityCenterTransport]: - """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V1p1Beta1 APIs for Security Center 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 = "securitycenter.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: - SecurityCenterClient: 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: - SecurityCenterClient: 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) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def asset_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified asset string.""" - return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_asset_path(path: str) -> Dict[str,str]: - """Parses a asset path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def finding_path(organization: str,source: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def notification_config_path(organization: str,notification_config: str,) -> str: - """Returns a fully-qualified notification_config string.""" - return "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) - - @staticmethod - def parse_notification_config_path(path: str) -> Dict[str,str]: - """Parses a notification_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def organization_settings_path(organization: str,) -> str: - """Returns a fully-qualified organization_settings string.""" - return "organizations/{organization}/organizationSettings".format(organization=organization, ) - - @staticmethod - def parse_organization_settings_path(path: str) -> Dict[str,str]: - """Parses a organization_settings path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str,str]: - """Parses a security_marks path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str,source: str,) -> str: - """Returns a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str,str]: - """Parses a source path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def topic_path(project: str,topic: str,) -> str: - """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - - @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: - """Parses a topic path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/topics/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 - SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient._read_environment_variables() - self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) - if transport_provided: - # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( - type(self).get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., SecurityCenterTransport], 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_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v1p1beta1 - - def sample_create_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest, dict]): - The request object. Request message for creating a - source. - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (google.cloud.securitycenter_v1p1beta1.types.Source): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding_id: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_create_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest, dict]): - The request object. Request message for creating a - finding. - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (str): - Required. Unique identifier provided - by the client within the parent scope. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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 create_notification_config(self, - request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - config_id: Optional[str] = None, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_create_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = client.create_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest, dict]): - The request object. Request message for creating a - notification config. - parent (str): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must be between 1 and 128 characters, - and contains alphanumeric characters, - underscores or hyphens only. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_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.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_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, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_notification_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_notification_config(self, - request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest, dict]): - The request object. Request message for deleting a - notification config. - name (str): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1p1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 get_notification_config(self, - request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_get_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest, dict]): - The request object. Request message for getting a - notification config. - name (str): - Required. Name of the notification config to get. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 get_organization_settings(self, - request: Optional[Union[securitycenter_service.GetOrganizationSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest, dict]): - The request object. Request message for getting - organization settings. - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_organization_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 get_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v1p1beta1 - - def sample_get_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest, dict]): - The request object. Request message for getting a source. - name (str): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_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.cloud.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 group_assets(self, - request: Optional[Union[securitycenter_service.GroupAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_group_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest, dict]): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsPager: - Response message for grouping by - assets. - 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, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.GroupAssetsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_group_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest, dict]): - The request object. Request message for grouping by - findings. - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]", - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]. To groupBy - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/-, or - projects/{project_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (str): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - severity - - The following fields are supported when compare_duration - is set: - - - state_change - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_assets(self, - request: Optional[Union[securitycenter_service.ListAssetsRequest, 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.ListAssetsPager: - r"""Lists an organization's assets. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_list_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest, dict]): - The request object. Request message for listing assets. - parent (str): - Required. Name of the organization assets should belong - to. Its format is "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsPager: - Response message for listing assets. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListAssetsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings(self, - request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_list_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListFindingsRequest( - parent="parent_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.securitycenter_v1p1beta1.types.ListFindingsRequest, dict]): - The request object. Request message for listing findings. - parent (str): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id], - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]". To list - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/- or - projects/{projects_id}/sources/- - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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_notification_configs(self, - request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsPager: - r"""Lists notification configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest, dict]): - The request object. Request message for listing - notification configs. - parent (str): - Required. Name of the organization to list notification - configs. Its format is - "organizations/[organization_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListNotificationConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_list_sources(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest, dict]): - The request object. Request message for listing sources. - parent (str): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id], folders/[folder_id], - or projects/[project_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_asset_discovery(self, - request: Optional[Union[securitycenter_service.RunAssetDiscoveryRequest, 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]] = (), - ) -> operation.Operation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS 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 securitycenter_v1p1beta1 - - def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest, dict]): - The request object. Request message for running asset - discovery for an organization. - parent (str): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` - Response of asset discovery run - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - start_time: Optional[timestamp_pb2.Timestamp] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of 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 securitycenter_v1p1beta1 - - def sample_set_finding_state(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest, dict]): - The request object. Request message for updating a - finding's state. - name (str): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v1p1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v1p1beta1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # 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 - - def update_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - update_mask: 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]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_update_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest, dict]): - The request object. Request message for updating or - creating a finding. - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a - finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing - source_properties. Individual source_properties can be - added/updated by using "source_properties." in the field - mask. - - 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.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - 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_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe 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_config(self, - request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, - *, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - update_mask: 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]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_update_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = client.update_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest, dict]): - The request object. Request message for updating a - notification config. - notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the notification config. - If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_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 update_organization_settings(self, - request: Optional[Union[securitycenter_service.UpdateOrganizationSettingsRequest, dict]] = None, - *, - organization_settings: Optional[gcs_organization_settings.OrganizationSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = client.update_organization_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest, dict]): - The request object. Request message for updating an - organization's settings. - organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_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 update_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - update_mask: 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]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v1p1beta1 - - def sample_update_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest, dict]): - The request object. Request message for updating a - source. - source (google.cloud.securitycenter_v1p1beta1.types.Source): - Required. The source resource to - update. - - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the source resource. - If empty all mutable fields 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.cloud.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = 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_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - update_mask: 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]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v1p1beta1 - - def sample_update_security_marks(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest, dict]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If - empty or set to "marks", all marks will be replaced. - Individual marks can be updated using - "marks.". - - 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.securitycenter_v1p1beta1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - 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_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe 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) -> "SecurityCenterClient": - 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__ = ( - "SecurityCenterClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py deleted file mode 100644 index ddad1b803817..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py +++ /dev/null @@ -1,839 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from 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.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source - - -class GroupAssetsPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupAssetsResponse], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1p1beta1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - 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[securitycenter_service.GroupAssetsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupAssetsAsyncPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` - attributes are available on the 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[securitycenter_service.GroupAssetsResponse]], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1p1beta1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - 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[securitycenter_service.GroupAssetsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1p1beta1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` - attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1p1beta1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListAssetsResponse], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - 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[securitycenter_service.ListAssetsResponse]: - 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - for page in self.pages: - yield from page.list_assets_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` - attributes are available on the 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[securitycenter_service.ListAssetsResponse]], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - 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[securitycenter_service.ListAssetsResponse]: - 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[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_assets_results: - 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.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.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[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v1p1beta1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - for page in self.pages: - yield from page.list_findings_results - - 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.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.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[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v1p1beta1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_findings_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - 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[securitycenter_service.ListNotificationConfigsResponse]: - 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[notification_config.NotificationConfig]: - for page in self.pages: - yield from page.notification_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsAsyncPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` - attributes are available on the 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[securitycenter_service.ListNotificationConfigsResponse]], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - 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[securitycenter_service.ListNotificationConfigsResponse]: - 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[notification_config.NotificationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.notification_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1p1beta1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` - attributes are available on the 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[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1p1beta1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.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-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py deleted file mode 100644 index 9d36139c1a9b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/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 SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .rest import SecurityCenterRestTransport -from .rest import SecurityCenterRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry['grpc'] = SecurityCenterGrpcTransport -_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport -_transport_registry['rest'] = SecurityCenterRestTransport - -__all__ = ( - 'SecurityCenterTransport', - 'SecurityCenterGrpcTransport', - 'SecurityCenterGrpcAsyncIOTransport', - 'SecurityCenterRestTransport', - 'SecurityCenterRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py deleted file mode 100644 index 00cffef9c86f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py +++ /dev/null @@ -1,591 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.securitycenter_v1p1beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -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.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -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 empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'securitycenter.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.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: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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_source: gapic_v1.method.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method.wrap_method( - self.create_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method.wrap_method( - self.delete_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_notification_config: gapic_v1.method.wrap_method( - self.get_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_organization_settings: gapic_v1.method.wrap_method( - self.get_organization_settings, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_source: gapic_v1.method.wrap_method( - self.get_source, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.group_assets: gapic_v1.method.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method.wrap_method( - self.list_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_sources: gapic_v1.method.wrap_method( - self.list_sources, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.run_asset_discovery: gapic_v1.method.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_finding: gapic_v1.method.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method.wrap_method( - self.update_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=480.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 operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - 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 get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Union[ - notification_config.NotificationConfig, - Awaitable[notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Union[ - organization_settings.OrganizationSettings, - Awaitable[organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Union[ - source.Source, - Awaitable[source.Source] - ]]: - raise NotImplementedError() - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Union[ - securitycenter_service.GroupAssetsResponse, - Awaitable[securitycenter_service.GroupAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Union[ - securitycenter_service.GroupFindingsResponse, - Awaitable[securitycenter_service.GroupFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Union[ - securitycenter_service.ListAssetsResponse, - Awaitable[securitycenter_service.ListAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Union[ - securitycenter_service.ListFindingsResponse, - Awaitable[securitycenter_service.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Union[ - securitycenter_service.ListNotificationConfigsResponse, - Awaitable[securitycenter_service.ListNotificationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Union[ - securitycenter_service.ListSourcesResponse, - Awaitable[securitycenter_service.ListSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - 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 test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Union[ - gcs_organization_settings.OrganizationSettings, - Awaitable[gcs_organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Union[ - gcs_security_marks.SecurityMarks, - Awaitable[gcs_security_marks.SecurityMarks] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SecurityCenterTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py deleted file mode 100644 index a2a5e40ef1f0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py +++ /dev/null @@ -1,895 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import 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.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -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 empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V1p1Beta1 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: 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 create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - ~.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_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - ~.GroupAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - 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.securitycenter.v1p1beta1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - ~.ListNotificationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - operations_pb2.Operation]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - ~.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 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - ~.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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SecurityCenterGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index 0743b78ddbd6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,1125 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -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 empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V1p1Beta1 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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._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 create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - 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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - 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_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Awaitable[notification_config.NotificationConfig]]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Awaitable[organization_settings.OrganizationSettings]]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Awaitable[securitycenter_service.GroupAssetsResponse]]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - Awaitable[~.GroupAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse]]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Awaitable[securitycenter_service.ListAssetsResponse]]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - 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.securitycenter.v1p1beta1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - Awaitable[~.ListNotificationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse]]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - 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 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - 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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.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.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - 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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Awaitable[gcs_organization_settings.OrganizationSettings]]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks]]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - 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_source: gapic_v1.method_async.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method_async.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method_async.wrap_method( - self.create_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method_async.wrap_method( - self.delete_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( - self.get_iam_policy, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_notification_config: gapic_v1.method_async.wrap_method( - self.get_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_organization_settings: gapic_v1.method_async.wrap_method( - self.get_organization_settings, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_source: gapic_v1.method_async.wrap_method( - self.get_source, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.group_assets: gapic_v1.method_async.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method_async.wrap_method( - self.group_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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method_async.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method_async.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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method_async.wrap_method( - self.list_notification_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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_sources: gapic_v1.method_async.wrap_method( - self.list_sources, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.run_asset_discovery: gapic_v1.method_async.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method_async.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( - self.test_iam_permissions, - 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=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_finding: gapic_v1.method_async.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method_async.wrap_method( - self.update_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method_async.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method_async.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method_async.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py deleted file mode 100644 index ea67cf703231..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/rest.py +++ /dev/null @@ -1,3197 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # 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 path_template -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 -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -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.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SecurityCenterRestInterceptor: - """Interceptor for SecurityCenter. - - 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 SecurityCenterRestTransport. - - .. code-block:: python - class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): - def pre_create_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_organization_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_organization_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_assets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_assets(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_notification_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_notification_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_sources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_sources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_run_asset_discovery(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_run_asset_discovery(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_finding_state(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_finding_state(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_organization_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_organization_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_security_marks(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_security_marks(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_source(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) - client = SecurityCenterClient(transport=transport) - - - """ - def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for create_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_notification_config(self, request: securitycenter_service.CreateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: - """Post-rpc interceptor for create_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for create_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_delete_notification_config(self, request: securitycenter_service.DeleteNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_notification_config(self, request: securitycenter_service.GetNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_notification_config(self, response: notification_config.NotificationConfig) -> notification_config.NotificationConfig: - """Post-rpc interceptor for get_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_organization_settings(self, request: securitycenter_service.GetOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_organization_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_organization_settings(self, response: organization_settings.OrganizationSettings) -> organization_settings.OrganizationSettings: - """Post-rpc interceptor for get_organization_settings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_source(self, response: source.Source) -> source.Source: - """Post-rpc interceptor for get_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_assets(self, request: securitycenter_service.GroupAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_assets(self, response: securitycenter_service.GroupAssetsResponse) -> securitycenter_service.GroupAssetsResponse: - """Post-rpc interceptor for group_assets - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: - """Post-rpc interceptor for group_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_assets(self, request: securitycenter_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_assets(self, response: securitycenter_service.ListAssetsResponse) -> securitycenter_service.ListAssetsResponse: - """Post-rpc interceptor for list_assets - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. - """ - return request, metadata - - def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: - """Post-rpc interceptor for list_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_notification_configs(self, request: securitycenter_service.ListNotificationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListNotificationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_notification_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_notification_configs(self, response: securitycenter_service.ListNotificationConfigsResponse) -> securitycenter_service.ListNotificationConfigsResponse: - """Post-rpc interceptor for list_notification_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_sources - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: - """Post-rpc interceptor for list_sources - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_run_asset_discovery(self, request: securitycenter_service.RunAssetDiscoveryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.RunAssetDiscoveryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for run_asset_discovery - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_run_asset_discovery(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for run_asset_discovery - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for update_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_notification_config(self, request: securitycenter_service.UpdateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: - """Post-rpc interceptor for update_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_organization_settings(self, request: securitycenter_service.UpdateOrganizationSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateOrganizationSettingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_organization_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_organization_settings(self, response: gcs_organization_settings.OrganizationSettings) -> gcs_organization_settings.OrganizationSettings: - """Post-rpc interceptor for update_organization_settings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: - """Post-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for update_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SecurityCenterRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SecurityCenterRestInterceptor - - -class SecurityCenterRestTransport(SecurityCenterTransport): - """REST backend transport for SecurityCenter. - - V1p1Beta1 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SecurityCenterRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 - 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 - ) - 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 SecurityCenterRestInterceptor() - 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': '/v1p1beta1/{name=organizations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1p1beta1/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1p1beta1/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1p1beta1/{name=organizations/*/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="v1p1beta1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "findingId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the create finding method over HTTP. - - Args: - request (~.securitycenter_service.CreateFindingRequest): - The request object. Request message for creating a - finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=organizations/*/sources/*}/findings', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_create_finding(request, metadata) - pb_request = securitycenter_service.CreateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_finding(resp) - return resp - - class _CreateNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "configId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_notification_config.NotificationConfig: - r"""Call the create notification - config method over HTTP. - - Args: - request (~.securitycenter_service.CreateNotificationConfigRequest): - The request object. Request message for creating a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=organizations/*}/notificationConfigs', - 'body': 'notification_config', - }, - ] - request, metadata = self._interceptor.pre_create_notification_config(request, metadata) - pb_request = securitycenter_service.CreateNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_notification_config.NotificationConfig() - pb_resp = gcs_notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_notification_config(resp) - return resp - - class _CreateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the create source method over HTTP. - - Args: - request (~.securitycenter_service.CreateSourceRequest): - The request object. Request message for creating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=organizations/*}/sources', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_create_source(request, metadata) - pb_request = securitycenter_service.CreateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_source(resp) - return resp - - class _DeleteNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete notification - config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteNotificationConfigRequest): - The request object. Request message for deleting a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1p1beta1/{name=organizations/*/notificationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_notification_config(request, metadata) - pb_request = securitycenter_service.DeleteNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _GetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{resource=organizations/*/sources/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _GetNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> notification_config.NotificationConfig: - r"""Call the get notification config method over HTTP. - - Args: - request (~.securitycenter_service.GetNotificationConfigRequest): - The request object. Request message for getting a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.notification_config.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{name=organizations/*/notificationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_notification_config(request, metadata) - pb_request = securitycenter_service.GetNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = notification_config.NotificationConfig() - pb_resp = notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_notification_config(resp) - return resp - - class _GetOrganizationSettings(SecurityCenterRestStub): - def __hash__(self): - return hash("GetOrganizationSettings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetOrganizationSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> organization_settings.OrganizationSettings: - r"""Call the get organization settings method over HTTP. - - Args: - request (~.securitycenter_service.GetOrganizationSettingsRequest): - The request object. Request message for getting - organization 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: - ~.organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{name=organizations/*/organizationSettings}', - }, - ] - request, metadata = self._interceptor.pre_get_organization_settings(request, metadata) - pb_request = securitycenter_service.GetOrganizationSettingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = organization_settings.OrganizationSettings() - pb_resp = organization_settings.OrganizationSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_organization_settings(resp) - return resp - - class _GetSource(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> source.Source: - r"""Call the get source method over HTTP. - - Args: - request (~.securitycenter_service.GetSourceRequest): - The request object. Request message for getting a source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{name=organizations/*/sources/*}', - }, - ] - request, metadata = self._interceptor.pre_get_source(request, metadata) - pb_request = securitycenter_service.GetSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = source.Source() - pb_resp = source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_source(resp) - return resp - - class _GroupAssets(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupAssets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupAssetsResponse: - r"""Call the group assets method over HTTP. - - Args: - request (~.securitycenter_service.GroupAssetsRequest): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupAssetsResponse: - Response message for grouping by - assets. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=organizations/*}/assets:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=folders/*}/assets:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=projects/*}/assets:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_assets(request, metadata) - pb_request = securitycenter_service.GroupAssetsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupAssetsResponse() - pb_resp = securitycenter_service.GroupAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_assets(resp) - return resp - - class _GroupFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupFindingsResponse: - r"""Call the group findings method over HTTP. - - Args: - request (~.securitycenter_service.GroupFindingsRequest): - The request object. Request message for grouping by - findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupFindingsResponse: - Response message for group by - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=organizations/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=folders/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=projects/*/sources/*}/findings:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_findings(request, metadata) - pb_request = securitycenter_service.GroupFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupFindingsResponse() - pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_findings(resp) - return resp - - class _ListAssets(SecurityCenterRestStub): - def __hash__(self): - return hash("ListAssets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListAssetsResponse: - r"""Call the list assets method over HTTP. - - Args: - request (~.securitycenter_service.ListAssetsRequest): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListAssetsResponse: - Response message for listing assets. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=organizations/*}/assets', - }, -{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=folders/*}/assets', - }, -{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=projects/*}/assets', - }, - ] - request, metadata = self._interceptor.pre_list_assets(request, metadata) - pb_request = securitycenter_service.ListAssetsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListAssetsResponse() - pb_resp = securitycenter_service.ListAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_assets(resp) - return resp - - class _ListFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("ListFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListFindingsResponse: - r"""Call the list findings method over HTTP. - - Args: - request (~.securitycenter_service.ListFindingsRequest): - The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListFindingsResponse: - Response message for listing - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=organizations/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=folders/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=projects/*/sources/*}/findings', - }, - ] - request, metadata = self._interceptor.pre_list_findings(request, metadata) - pb_request = securitycenter_service.ListFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListFindingsResponse() - pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_findings(resp) - return resp - - class _ListNotificationConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListNotificationConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListNotificationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListNotificationConfigsResponse: - r"""Call the list notification configs method over HTTP. - - Args: - request (~.securitycenter_service.ListNotificationConfigsRequest): - The request object. Request message for listing - notification configs. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListNotificationConfigsResponse: - Response message for listing - notification configs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=organizations/*}/notificationConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_notification_configs(request, metadata) - pb_request = securitycenter_service.ListNotificationConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListNotificationConfigsResponse() - pb_resp = securitycenter_service.ListNotificationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_notification_configs(resp) - return resp - - class _ListSources(SecurityCenterRestStub): - def __hash__(self): - return hash("ListSources") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListSourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListSourcesResponse: - r"""Call the list sources method over HTTP. - - Args: - request (~.securitycenter_service.ListSourcesRequest): - The request object. Request message for listing sources. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListSourcesResponse: - Response message for listing sources. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=organizations/*}/sources', - }, -{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=folders/*}/sources', - }, -{ - 'method': 'get', - 'uri': '/v1p1beta1/{parent=projects/*}/sources', - }, - ] - request, metadata = self._interceptor.pre_list_sources(request, metadata) - pb_request = securitycenter_service.ListSourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListSourcesResponse() - pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_sources(resp) - return resp - - class _RunAssetDiscovery(SecurityCenterRestStub): - def __hash__(self): - return hash("RunAssetDiscovery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.RunAssetDiscoveryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the run asset discovery method over HTTP. - - Args: - request (~.securitycenter_service.RunAssetDiscoveryRequest): - The request object. Request message for running asset - discovery for an organization. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{parent=organizations/*}/assets:runDiscovery', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_run_asset_discovery(request, metadata) - pb_request = securitycenter_service.RunAssetDiscoveryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_run_asset_discovery(resp) - return resp - - class _SetFindingState(SecurityCenterRestStub): - def __hash__(self): - return hash("SetFindingState") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SetFindingStateRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the set finding state method over HTTP. - - Args: - request (~.securitycenter_service.SetFindingStateRequest): - The request object. Request message for updating a - finding's state. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{name=organizations/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1p1beta1/{name=folders/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1p1beta1/{name=projects/*/sources/*/findings/*}:setState', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_finding_state(request, metadata) - pb_request = securitycenter_service.SetFindingStateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_set_finding_state(resp) - return resp - - class _SetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{resource=organizations/*/sources/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _TestIamPermissions(SecurityCenterRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p1beta1/{resource=organizations/*/sources/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UpdateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the update finding method over HTTP. - - Args: - request (~.securitycenter_service.UpdateFindingRequest): - The request object. Request message for updating or - creating a finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1p1beta1/{finding.name=organizations/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{finding.name=folders/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{finding.name=projects/*/sources/*/findings/*}', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_update_finding(request, metadata) - pb_request = securitycenter_service.UpdateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_finding(resp) - return resp - - class _UpdateNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_notification_config.NotificationConfig: - r"""Call the update notification - config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateNotificationConfigRequest): - The request object. Request message for updating a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1p1beta1/{notification_config.name=organizations/*/notificationConfigs/*}', - 'body': 'notification_config', - }, - ] - request, metadata = self._interceptor.pre_update_notification_config(request, metadata) - pb_request = securitycenter_service.UpdateNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_notification_config.NotificationConfig() - pb_resp = gcs_notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_notification_config(resp) - return resp - - class _UpdateOrganizationSettings(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateOrganizationSettings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateOrganizationSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Call the update organization - settings method over HTTP. - - Args: - request (~.securitycenter_service.UpdateOrganizationSettingsRequest): - The request object. Request message for updating an - organization's 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: - ~.gcs_organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1p1beta1/{organization_settings.name=organizations/*/organizationSettings}', - 'body': 'organization_settings', - }, - ] - request, metadata = self._interceptor.pre_update_organization_settings(request, metadata) - pb_request = securitycenter_service.UpdateOrganizationSettingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_organization_settings.OrganizationSettings() - pb_resp = gcs_organization_settings.OrganizationSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_organization_settings(resp) - return resp - - class _UpdateSecurityMarks(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSecurityMarks") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSecurityMarksRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_security_marks.SecurityMarks: - r"""Call the update security marks method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSecurityMarksRequest): - The request object. Request message for updating a - SecurityMarks resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1p1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{security_marks.name=folders/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{security_marks.name=projects/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v1p1beta1/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, - ] - request, metadata = self._interceptor.pre_update_security_marks(request, metadata) - pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_security_marks.SecurityMarks() - pb_resp = gcs_security_marks.SecurityMarks.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_security_marks(resp) - return resp - - class _UpdateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the update source method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSourceRequest): - The request object. Request message for updating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1p1beta1/{source.name=organizations/*/sources/*}', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_update_source(request, metadata) - pb_request = securitycenter_service.UpdateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_source(resp) - return resp - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - 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._DeleteNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.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_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListNotificationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSources(self._session, self._host, self._interceptor) # type: ignore - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - 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._RunAssetDiscovery(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateOrganizationSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SecurityCenterRestTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py deleted file mode 100644 index 9f0c2b8e8129..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__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 .asset import ( - Asset, -) -from .finding import ( - Finding, -) -from .folder import ( - Folder, -) -from .notification_config import ( - NotificationConfig, -) -from .notification_message import ( - NotificationMessage, -) -from .organization_settings import ( - OrganizationSettings, -) -from .resource import ( - Resource, -) -from .run_asset_discovery_response import ( - RunAssetDiscoveryResponse, -) -from .security_marks import ( - SecurityMarks, -) -from .securitycenter_service import ( - CreateFindingRequest, - CreateNotificationConfigRequest, - CreateSourceRequest, - DeleteNotificationConfigRequest, - GetNotificationConfigRequest, - GetOrganizationSettingsRequest, - GetSourceRequest, - GroupAssetsRequest, - GroupAssetsResponse, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListAssetsRequest, - ListAssetsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListNotificationConfigsRequest, - ListNotificationConfigsResponse, - ListSourcesRequest, - ListSourcesResponse, - RunAssetDiscoveryRequest, - SetFindingStateRequest, - UpdateFindingRequest, - UpdateNotificationConfigRequest, - UpdateOrganizationSettingsRequest, - UpdateSecurityMarksRequest, - UpdateSourceRequest, -) -from .source import ( - Source, -) - -__all__ = ( - 'Asset', - 'Finding', - 'Folder', - 'NotificationConfig', - 'NotificationMessage', - 'OrganizationSettings', - 'Resource', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateNotificationConfigRequest', - 'CreateSourceRequest', - 'DeleteNotificationConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py deleted file mode 100644 index 2250330a504d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py +++ /dev/null @@ -1,227 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1p1beta1.types import folder -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'Asset', - }, -) - - -class Asset(proto.Message): - r"""Security Command Center representation of a Google Cloud - resource. - - The Asset is a Security Command Center resource that captures - information about a single Google Cloud resource. All - modifications to an Asset are only within the context of - Security Command Center and don't affect the referenced Google - Cloud resource. - - Attributes: - name (str): - The relative resource name of this asset. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (google.cloud.securitycenter_v1p1beta1.types.Asset.SecurityCenterProperties): - Security Command Center managed properties. - These properties are managed by Security Command - Center and cannot be modified by the user. - resource_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Resource managed properties. These properties - are managed and defined by the Google Cloud - resource and cannot be modified by the user. - security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): - User specified security marks. These marks - are entirely managed by the user and come from - the SecurityMarks resource that belongs to the - asset. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was created in - Security Command Center. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was last updated - or added in Cloud SCC. - iam_policy (google.cloud.securitycenter_v1p1beta1.types.Asset.IamPolicy): - Cloud IAM Policy information associated with - the Google Cloud resource described by the - Security Command Center asset. This information - is managed and defined by the Google Cloud - resource and cannot be modified by the user. - canonical_name (str): - The canonical name of the resource. It's either - "organizations/{organization_id}/assets/{asset_id}", - "folders/{folder_id}/assets/{asset_id}" or - "projects/{project_number}/assets/{asset_id}", depending on - the closest CRM ancestor of the resource. - """ - - class SecurityCenterProperties(proto.Message): - r"""Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified by - the user. - - Attributes: - resource_name (str): - The full resource name of the Google Cloud resource this - asset represents. This field is immutable after create time. - See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_type (str): - The type of the Google Cloud resource. - Examples include: APPLICATION, PROJECT, and - ORGANIZATION. This is a case insensitive field - defined by Security Command Center and/or the - producer of the resource and is immutable after - create time. - resource_parent (str): - The full resource name of the immediate parent of the - resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_project (str): - The full resource name of the project the resource belongs - to. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_owners (MutableSequence[str]): - Owners of the Google Cloud resource. - resource_display_name (str): - The user defined display name for this - resource. - resource_parent_display_name (str): - The user defined display name for the parent - of this resource. - resource_project_display_name (str): - The user defined display name for the project - of this resource. - folders (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): - Contains a Folder message for each folder in - the assets ancestry. The first folder is the - deepest nested folder, and the last folder is - the folder directly under the Organization. - """ - - resource_name: str = proto.Field( - proto.STRING, - number=1, - ) - resource_type: str = proto.Field( - proto.STRING, - number=2, - ) - resource_parent: str = proto.Field( - proto.STRING, - number=3, - ) - resource_project: str = proto.Field( - proto.STRING, - number=4, - ) - resource_owners: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - resource_display_name: str = proto.Field( - proto.STRING, - number=6, - ) - resource_parent_display_name: str = proto.Field( - proto.STRING, - number=7, - ) - resource_project_display_name: str = proto.Field( - proto.STRING, - number=8, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=folder.Folder, - ) - - class IamPolicy(proto.Message): - r"""Cloud IAM Policy information associated with the Google Cloud - resource described by the Security Command Center asset. This - information is managed and defined by the Google Cloud resource - and cannot be modified by the user. - - Attributes: - policy_blob (str): - The JSON representation of the Policy - associated with the asset. See - https://cloud.google.com/iam/docs/reference/rest/v1/Policy - for format details. - """ - - policy_blob: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - security_center_properties: SecurityCenterProperties = proto.Field( - proto.MESSAGE, - number=2, - message=SecurityCenterProperties, - ) - resource_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - iam_policy: IamPolicy = proto.Field( - proto.MESSAGE, - number=11, - message=IamPolicy, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=13, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py deleted file mode 100644 index 8fe9a48e3cfb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - - A finding is a record of assessment data (security, risk, health - or privacy) ingested into Security Command Center for - presentation, notification, analysis, policy testing, and - enforcement. For example, an XSS vulnerability in an App Engine - application is a finding. - - Attributes: - name (str): - The relative resource name of this finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". - parent (str): - The relative resource name of the source the finding belongs - to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. For example: - "organizations/{organization_id}/sources/{source_id}". - resource_name (str): - For findings on Google Cloud resources, the full resource - name of the Google Cloud resource this finding is for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - This field is immutable after creation time. - state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): - The state of the finding. - category (str): - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. - Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the event took place, or - when an update to the finding occurred. For - example, if the finding represents an open - firewall it would capture the time the detector - believes the firewall became open. The accuracy - is determined by the detector. If the finding - were to be resolved afterward, this time would - reflect when the finding was resolved. Must not - be set to a value greater than the current - timestamp. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the finding was created in - Security Command Center. - severity (google.cloud.securitycenter_v1p1beta1.types.Finding.Severity): - The severity of the finding. This field is - managed by the source that writes the finding. - canonical_name (str): - The canonical name of the finding. It's either - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" - or - "projects/{project_number}/sources/{source_id}/findings/{finding_id}", - depending on the closest CRM ancestor of the resource - associated with the finding. - """ - class State(proto.Enum): - r"""The state of the finding. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - ACTIVE (1): - The finding requires attention and has not - been addressed yet. - INACTIVE (2): - The finding has been fixed, triaged as a - non-issue or otherwise addressed and is no - longer active. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - class Severity(proto.Enum): - r"""The severity of the finding. This field is managed by the - source that writes the finding. - - 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, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - resource_name: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - category: str = proto.Field( - proto.STRING, - number=5, - ) - external_uri: str = proto.Field( - proto.STRING, - number=6, - ) - source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - severity: Severity = proto.Field( - proto.ENUM, - number=13, - enum=Severity, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=14, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py deleted file mode 100644 index 17d1a3c450ed..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.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.securitycenter.v1p1beta1', - manifest={ - 'Folder', - }, -) - - -class Folder(proto.Message): - r"""Message that contains the resource name and display name of a - folder resource. - - Attributes: - resource_folder (str): - Full resource name of this folder. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_folder_display_name (str): - The user defined display name for this - folder. - """ - - resource_folder: str = proto.Field( - proto.STRING, - number=1, - ) - resource_folder_display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py deleted file mode 100644 index 8b92401c657b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'NotificationConfig', - }, -) - - -class NotificationConfig(proto.Message): - r"""Security Command Center notification configs. - - A notification config is a Security Command Center resource that - contains the configuration to send notifications for - create/update events of findings, assets and etc. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The relative resource name of this notification config. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/notificationConfigs/notify_public_bucket". - description (str): - The description of the notification config - (max of 1024 characters). - event_type (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.EventType): - The type of events the config is for, e.g. - FINDING. - pubsub_topic (str): - The Pub/Sub topic to send notifications to. Its format is - "projects/[project_id]/topics/[topic]". - service_account (str): - Output only. The service account that needs - "pubsub.topics.publish" permission to publish to - the Pub/Sub topic. - streaming_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.StreamingConfig): - The config for triggering streaming-based - notifications. - - This field is a member of `oneof`_ ``notify_config``. - """ - class EventType(proto.Enum): - r"""The type of events. - - Values: - EVENT_TYPE_UNSPECIFIED (0): - Unspecified event type. - FINDING (1): - Events for findings. - """ - EVENT_TYPE_UNSPECIFIED = 0 - FINDING = 1 - - class StreamingConfig(proto.Message): - r"""The config for streaming-based notifications, which send each - event as soon as it is detected. - - Attributes: - filter (str): - Expression that defines the filter to apply across - create/update events of assets or findings as specified by - the event type. The expression is a list of zero or more - restrictions combined via logical operators ``AND`` and - ``OR``. Parentheses are supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - """ - - filter: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - event_type: EventType = proto.Field( - proto.ENUM, - number=3, - enum=EventType, - ) - pubsub_topic: str = proto.Field( - proto.STRING, - number=4, - ) - service_account: str = proto.Field( - proto.STRING, - number=5, - ) - streaming_config: StreamingConfig = proto.Field( - proto.MESSAGE, - number=6, - oneof='notify_config', - message=StreamingConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py deleted file mode 100644 index 5572db1a6d80..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.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.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import resource as gcs_resource - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'NotificationMessage', - }, -) - - -class NotificationMessage(proto.Message): - r"""Security Command Center's Notification - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - notification_config_name (str): - Name of the notification config that - generated current notification. - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - If it's a Finding based notification config, - this field will be populated. - - This field is a member of `oneof`_ ``event``. - resource (google.cloud.securitycenter_v1p1beta1.types.Resource): - The Cloud resource tied to the notification. - """ - - notification_config_name: str = proto.Field( - proto.STRING, - number=1, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=2, - oneof='event', - message=gcs_finding.Finding, - ) - resource: gcs_resource.Resource = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_resource.Resource, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py deleted file mode 100644 index e8a49050b4aa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'OrganizationSettings', - }, -) - - -class OrganizationSettings(proto.Message): - r"""User specified settings that are attached to the Security - Command Center organization. - - Attributes: - name (str): - The relative resource name of the settings. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/organizationSettings". - enable_asset_discovery (bool): - A flag that indicates if Asset Discovery should be enabled. - If the flag is set to ``true``, then discovery of assets - will occur. If it is set to \`false, all historical assets - will remain, but discovery of future assets will not occur. - asset_discovery_config (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig): - The configuration used for Asset Discovery - runs. - """ - - class AssetDiscoveryConfig(proto.Message): - r"""The configuration used for Asset Discovery runs. - - Attributes: - project_ids (MutableSequence[str]): - The project ids to use for filtering asset - discovery. - inclusion_mode (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): - The mode to use for filtering asset - discovery. - folder_ids (MutableSequence[str]): - The folder ids to use for filtering asset - discovery. It consists of only digits, e.g., - 756619654966. - """ - class InclusionMode(proto.Enum): - r"""The mode of inclusion when running Asset Discovery. Asset discovery - can be limited by explicitly identifying projects to be included or - excluded. If INCLUDE_ONLY is set, then only those projects within - the organization and their children are discovered during asset - discovery. If EXCLUDE is set, then projects that don't match those - projects are discovered during asset discovery. If neither are set, - then all projects within the organization are discovered during - asset discovery. - - Values: - INCLUSION_MODE_UNSPECIFIED (0): - Unspecified. Setting the mode with this value - will disable inclusion/exclusion filtering for - Asset Discovery. - INCLUDE_ONLY (1): - Asset Discovery will capture only the - resources within the projects specified. All - other resources will be ignored. - EXCLUDE (2): - Asset Discovery will ignore all resources - under the projects specified. All other - resources will be retrieved. - """ - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - project_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - inclusion_mode: 'OrganizationSettings.AssetDiscoveryConfig.InclusionMode' = proto.Field( - proto.ENUM, - number=2, - enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', - ) - folder_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - enable_asset_discovery: bool = proto.Field( - proto.BOOL, - number=2, - ) - asset_discovery_config: AssetDiscoveryConfig = proto.Field( - proto.MESSAGE, - number=3, - message=AssetDiscoveryConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py deleted file mode 100644 index 2fd5e7836be1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py +++ /dev/null @@ -1,85 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1p1beta1.types import folder - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'Resource', - }, -) - - -class Resource(proto.Message): - r"""Information related to the Google Cloud resource. - - Attributes: - name (str): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - project (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The human readable name of project that the - resource belongs to. - parent (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): - Output only. Contains a Folder message for - each folder in the assets ancestry. The first - folder is the deepest nested folder, and the - last folder is the folder directly under the - Organization. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - project: str = proto.Field( - proto.STRING, - number=2, - ) - project_display_name: str = proto.Field( - proto.STRING, - number=3, - ) - parent: str = proto.Field( - proto.STRING, - number=4, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=5, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=folder.Folder, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py deleted file mode 100644 index 10769c100399..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.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 - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'RunAssetDiscoveryResponse', - }, -) - - -class RunAssetDiscoveryResponse(proto.Message): - r"""Response of asset discovery run - - Attributes: - state (google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse.State): - The state of an asset discovery run. - duration (google.protobuf.duration_pb2.Duration): - The duration between asset discovery run - start and end - """ - class State(proto.Enum): - r"""The state of an asset discovery run. - - Values: - STATE_UNSPECIFIED (0): - Asset discovery run state was unspecified. - COMPLETED (1): - Asset discovery run completed successfully. - SUPERSEDED (2): - Asset discovery run was cancelled with tasks - still pending, as another run for the same - organization was started with a higher priority. - TERMINATED (3): - Asset discovery run was killed and - terminated. - """ - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py deleted file mode 100644 index 8473d65602f2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'SecurityMarks', - }, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (MutableMapping[str, str]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - canonical_name (str): - The canonical name of the marks. Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "folders/{folder_id}/assets/{asset_id}/securityMarks" - "projects/{project_number}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" - "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - marks: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py deleted file mode 100644 index 42ec8bf37842..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py +++ /dev/null @@ -1,1641 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v1p1beta1.types import asset as gcs_asset -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import folder -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'CreateFindingRequest', - 'CreateNotificationConfigRequest', - 'CreateSourceRequest', - 'DeleteNotificationConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'SetFindingStateRequest', - 'RunAssetDiscoveryRequest', - 'UpdateFindingRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSourceRequest', - 'UpdateSecurityMarksRequest', - }, -) - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - - Attributes: - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - finding_id: str = proto.Field( - proto.STRING, - number=2, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_finding.Finding, - ) - - -class CreateNotificationConfigRequest(proto.Message): - r"""Request message for creating a notification config. - - Attributes: - parent (str): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - config_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - between 1 and 128 characters, and contains - alphanumeric characters, underscores or hyphens - only. - notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): - Required. The notification config being - created. The name and the service account will - be ignored as they are both output only fields - on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - config_id: str = proto.Field( - proto.STRING, - number=2, - ) - notification_config: gcs_notification_config.NotificationConfig = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_notification_config.NotificationConfig, - ) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - source (google.cloud.securitycenter_v1p1beta1.types.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_source.Source, - ) - - -class DeleteNotificationConfigRequest(proto.Message): - r"""Request message for deleting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetNotificationConfigRequest(proto.Message): - r"""Request message for getting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to get. Its format - is - "organizations/[organization_id]/notificationConfigs/[config_id]". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetOrganizationSettingsRequest(proto.Message): - r"""Request message for getting organization settings. - - Attributes: - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is "organizations/[organization_id]/source/[source_id]". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GroupAssetsRequest(proto.Message): - r"""Request message for grouping by assets. - - Attributes: - parent (str): - Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id], folders/[folder_id], or - projects/[project_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_name_display_name: - ``=``, ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is - not set: - - - security_center_properties.resource_project - - security_center_properties.resource_project_display_name - - security_center_properties.resource_type - - security_center_properties.resource_parent - - security_center_properties.resource_parent_display_name - - The following fields are supported when compare_duration is - set: - - - security_center_properties.resource_type - - security_center_properties.resource_project_display_name - - security_center_properties.resource_parent_display_name - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the GroupResult's - "state_change" property is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at - reference_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and reference_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupAssetsResponse``; - indicates that this is a continuation of a prior - ``GroupAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - page_size: int = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupAssetsResponse(proto.Message): - r"""Response message for grouping by assets. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - - Attributes: - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]", - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]. To groupBy across - all sources provide a source_id of ``-``. For example: - organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/-, or - projects/{project_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - - severity: ``=``, ``:`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - security_marks.marks: ``=``, ``:`` - - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping (including ``state_change``). The string value - should follow SQL syntax: comma separated list of fields. - For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - severity - - The following fields are supported when compare_duration is - set: - - - state_change - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the GroupResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - page_size: int = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message=struct_pb2.Value, - ) - count: int = proto.Field( - proto.INT64, - number=2, - ) - - -class ListNotificationConfigsRequest(proto.Message): - r"""Request message for listing notification configs. - - Attributes: - parent (str): - Required. Name of the organization to list notification - configs. Its format is "organizations/[organization_id]". - page_token (str): - The value returned by the last - ``ListNotificationConfigsResponse``; indicates that this is - a continuation of a prior ``ListNotificationConfigs`` call, - and that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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 ListNotificationConfigsResponse(proto.Message): - r"""Response message for listing notification configs. - - Attributes: - notification_configs (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.NotificationConfig]): - Notification configs belonging to the - requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - notification_configs: MutableSequence[gcs_notification_config.NotificationConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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=7, - ) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - - Attributes: - sources (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListAssetsRequest(proto.Message): - r"""Request message for listing assets. - - Attributes: - parent (str): - Required. Name of the organization assets should belong to. - Its format is "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following are the allowed field and operator - combinations: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, - ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,resource_properties.a_property". - Redundant space characters in the syntax are insignificant. - "name desc,resource_properties.a_property" and " name desc , - resource_properties.a_property " are equivalent. - - The following fields are supported: name update_time - resource_properties security_marks.marks - security_center_properties.resource_name - security_center_properties.resource_display_name - security_center_properties.resource_parent - security_center_properties.resource_parent_display_name - security_center_properties.resource_project - security_center_properties.resource_project_display_name - security_center_properties.resource_type - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListAssetsResult's - "state_change" attribute is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at read_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at read_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the ListAssetsResult - fields to be listed in the response. - An empty field mask will list all fields. - page_token (str): - The value returned by the last ``ListAssetsResponse``; - indicates that this is a continuation of a prior - ``ListAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=8, - ) - page_size: int = proto.Field( - proto.INT32, - number=9, - ) - - -class ListAssetsResponse(proto.Message): - r"""Response message for listing assets. - - Attributes: - list_assets_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult]): - Assets matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of assets matching the - query. - """ - - class ListAssetsResult(proto.Message): - r"""Result containing the Asset and its State. - - Attributes: - asset (google.cloud.securitycenter_v1p1beta1.types.Asset): - Asset matching the search request. - state_change (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult.StateChange): - State change of the asset between the points - in time. - """ - class StateChange(proto.Enum): - r"""The change in state of the asset. - - When querying across two points in time this describes the change - between the two points: ADDED, REMOVED, or ACTIVE. If there was no - compare_duration supplied in the request the state change will be: - UNUSED - - Values: - UNUSED (0): - State change is unused, this is the canonical - default for this enum. - ADDED (1): - Asset was added between the points in time. - REMOVED (2): - Asset was removed between the points in time. - ACTIVE (3): - Asset was present at both point(s) in time. - """ - UNUSED = 0 - ADDED = 1 - REMOVED = 2 - ACTIVE = 3 - - asset: gcs_asset.Asset = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_asset.Asset, - ) - state_change: 'ListAssetsResponse.ListAssetsResult.StateChange' = proto.Field( - proto.ENUM, - number=2, - enum='ListAssetsResponse.ListAssetsResult.StateChange', - ) - - @property - def raw_page(self): - return self - - list_assets_results: MutableSequence[ListAssetsResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListAssetsResult, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - - Attributes: - parent (str): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id], - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]". To list across - all sources provide a source_id of ``-``. For example: - organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/- or - projects/{projects_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - - severity: ``=``, ``:`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - security_marks.marks: ``=``, ``:`` source_properties: ``=``, - ``:``, ``>``, ``<``, ``>=``, ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,source_properties.a_property". Redundant - space characters in the syntax are insignificant. "name - desc,source_properties.a_property" and " name desc , - source_properties.a_property " are equivalent. - - The following fields are supported: name parent state - category resource_name event_time source_properties - security_marks.marks - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListFindingsResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added in any state during - the compare_duration period of time that precedes the - read_time. This is the time between (read_time - - compare_duration) and read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the Finding fields to - be listed in the response. An empty field mask - will list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=8, - ) - page_size: int = proto.Field( - proto.INT32, - number=9, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - - Attributes: - list_findings_results (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult]): - Findings matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - class ListFindingsResult(proto.Message): - r"""Result containing the Finding and its StateChange. - - Attributes: - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Finding matching the search request. - state_change (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.StateChange): - State change of the finding between the - points in time. - resource (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.Resource): - Output only. Resource that is associated with - this finding. - """ - class StateChange(proto.Enum): - r"""The change in state of the finding. - - When querying across two points in time this describes the change in - the finding between the two points: CHANGED, UNCHANGED, ADDED, or - REMOVED. Findings can not be deleted, so REMOVED implies that the - finding at timestamp does not match the filter specified, but it did - at timestamp - compare_duration. If there was no compare_duration - supplied in the request the state change will be: UNUSED - - Values: - UNUSED (0): - State change is unused, this is the canonical - default for this enum. - CHANGED (1): - The finding has changed state in some way - between the points in time and existed at both - points. - UNCHANGED (2): - The finding has not changed state between the - points in time and existed at both points. - ADDED (3): - The finding was created between the points in - time. - REMOVED (4): - The finding at timestamp does not match the filter - specified, but it did at timestamp - compare_duration. - """ - UNUSED = 0 - CHANGED = 1 - UNCHANGED = 2 - ADDED = 3 - REMOVED = 4 - - class Resource(proto.Message): - r"""Information related to the Google Cloud resource that is - associated with this finding. - - Attributes: - name (str): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - project_name (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The human readable name of project that the - resource belongs to. - parent_name (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (MutableSequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): - Contains a Folder message for each folder in - the assets ancestry. The first folder is the - deepest nested folder, and the last folder is - the folder directly under the Organization. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - project_name: str = proto.Field( - proto.STRING, - number=2, - ) - project_display_name: str = proto.Field( - proto.STRING, - number=3, - ) - parent_name: str = proto.Field( - proto.STRING, - number=4, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=5, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=folder.Folder, - ) - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - state_change: 'ListFindingsResponse.ListFindingsResult.StateChange' = proto.Field( - proto.ENUM, - number=2, - enum='ListFindingsResponse.ListFindingsResult.StateChange', - ) - resource: 'ListFindingsResponse.ListFindingsResult.Resource' = proto.Field( - proto.MESSAGE, - number=3, - message='ListFindingsResponse.ListFindingsResult.Resource', - ) - - @property - def raw_page(self): - return self - - list_findings_results: MutableSequence[ListFindingsResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListFindingsResult, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - - Attributes: - name (str): - Required. The relative resource name of the finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): - Required. The desired State of the finding. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the updated state - takes effect. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: gcs_finding.Finding.State = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.State, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class RunAssetDiscoveryRequest(proto.Message): - r"""Request message for running asset discovery for an - organization. - - Attributes: - parent (str): - Required. Name of the organization to run asset discovery - for. Its format is "organizations/[organization_id]". - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - - Attributes: - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must be alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing source_properties. - Individual source_properties can be added/updated by using - "source_properties." in the field mask. - """ - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateNotificationConfigRequest(proto.Message): - r"""Request message for updating a notification config. - - Attributes: - notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): - Required. The notification config to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - notification config. - If empty all mutable fields will be updated. - """ - - notification_config: gcs_notification_config.NotificationConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateOrganizationSettingsRequest(proto.Message): - r"""Request message for updating an organization's settings. - - Attributes: - organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): - Required. The organization settings resource - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - settings resource. - If empty all mutable fields will be updated. - """ - - organization_settings: gcs_organization_settings.OrganizationSettings = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_organization_settings.OrganizationSettings, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - - Attributes: - source (google.cloud.securitycenter_v1p1beta1.types.Source): - Required. The source resource to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the source - resource. - If empty all mutable fields will be updated. - """ - - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - - Attributes: - security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): - Required. The security marks resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If empty - or set to "marks", all marks will be replaced. Individual - marks can be updated using "marks.". - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the updated SecurityMarks - take effect. If not set uses current server - time. Updates will be applied to the - SecurityMarks that are active immediately - preceding this time. - """ - - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_security_marks.SecurityMarks, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - start_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-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py deleted file mode 100644 index 53b3d04fda40..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'Source', - }, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, etc. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and - outdated/insecure libraries.". - canonical_name (str): - The canonical name of the finding. It's either - "organizations/{organization_id}/sources/{source_id}", - "folders/{folder_id}/sources/{source_id}" or - "projects/{project_number}/sources/{source_id}", depending - on the closest CRM ancestor of the resource associated with - the finding. - """ - - 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, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=14, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/noxfile.py deleted file mode 100644 index 32b130e85f33..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-securitycenter' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -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"): - 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/securitycenter_v1p1beta1/', - '--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"): - 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", - "grpcio", - "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/securitycenter_v1p1beta1/', - '--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( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): - # Ignore release of mypy 1.11.0 which may have a regression - 'mypy!=1.11.0', - '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-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_async.py deleted file mode 100644 index 9609719bb2ab..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_create_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py deleted file mode 100644 index a908f103062d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_create_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py deleted file mode 100644 index ce18ebfeab2a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_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 CreateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_create_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.create_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py deleted file mode 100644 index ec4621a56f92..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_notification_config_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 CreateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_create_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = client.create_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_async.py deleted file mode 100644 index a05525b26ae5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_create_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_source_sync.py deleted file mode 100644 index 53a2606db659..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_create_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py deleted file mode 100644 index 77696925a3b2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_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 DeleteNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_config(request=request) - - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py deleted file mode 100644 index 697bd5dc58b7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_delete_notification_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 DeleteNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_delete_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_config(request=request) - - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py deleted file mode 100644 index 0143835b3615..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py deleted file mode 100644 index fc6a2f9ecd38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py deleted file mode 100644 index beffb7197acc..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_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 GetNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_get_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py deleted file mode 100644 index e0bf761c0629..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_notification_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 GetNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_get_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py deleted file mode 100644 index 25b7d03ebdb4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_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 GetOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py deleted file mode 100644 index 94cd60452455..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_organization_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 GetOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_get_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetOrganizationSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_async.py deleted file mode 100644 index 1210ba0c3e4e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_get_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_source_sync.py deleted file mode 100644 index 942cc4b79272..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_get_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_async.py deleted file mode 100644 index a487bea8e359..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_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 GroupAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_group_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py deleted file mode 100644 index c99f19c6389b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_assets_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 GroupAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_group_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupAssetsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_async.py deleted file mode 100644 index 3f65d770b14b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_group_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py deleted file mode 100644 index f70d29e29a1d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_group_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_async.py deleted file mode 100644 index 55dec3edae30..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_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 ListAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_list_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py deleted file mode 100644 index 150f9240dedb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_assets_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 ListAssets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_list_assets(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_async.py deleted file mode 100644 index 6b7785c3b4f1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_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 securitycenter_v1p1beta1 - - -async def sample_list_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py deleted file mode 100644 index 5a8b07c8466d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_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 securitycenter_v1p1beta1 - - -def sample_list_findings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py deleted file mode 100644 index 41cdb54d0669..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_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 ListNotificationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py deleted file mode 100644 index 8d8286a62581..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_notification_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 ListNotificationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_list_notification_configs(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_async.py deleted file mode 100644 index 261f3b9fcb73..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_list_sources(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py deleted file mode 100644 index 847e73dd0797..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_list_sources(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py deleted file mode 100644 index 47e5c5bb61d7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py deleted file mode 100644 index fa965b321439..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_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 RunAssetDiscovery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_run_asset_discovery(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.RunAssetDiscoveryRequest( - parent="parent_value", - ) - - # Make the request - operation = client.run_asset_discovery(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py deleted file mode 100644 index 4d10d033f247..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_set_finding_state(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py deleted file mode 100644 index a77fb9ce8347..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_set_finding_state(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py deleted file mode 100644 index 3cd28543769f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py deleted file mode 100644 index 29ba6d93636e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py deleted file mode 100644 index 8b663d640a2f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py deleted file mode 100644 index b484fc5c8e69..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_async.py deleted file mode 100644 index 6fbcfd65b541..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_update_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py deleted file mode 100644 index 11a3b6e7fac8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_update_finding(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py deleted file mode 100644 index cc60d07059d3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_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 UpdateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_update_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = await client.update_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py deleted file mode 100644 index 1ad9f8ee9c1c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_notification_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 UpdateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_update_notification_config(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateNotificationConfigRequest( - ) - - # Make the request - response = client.update_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py deleted file mode 100644 index 962efe30b0e6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = await client.update_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py deleted file mode 100644 index 007047607a2f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_organization_settings_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 UpdateOrganizationSettings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_update_organization_settings(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateOrganizationSettingsRequest( - ) - - # Make the request - response = client.update_organization_settings(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py deleted file mode 100644 index 6f9484b9d009..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_update_security_marks(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py deleted file mode 100644 index 091847a4ef33..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_update_security_marks(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_async.py deleted file mode 100644 index 559623a451be..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -async def sample_update_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_sync.py deleted file mode 100644 index 5f72d8dd2b64..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/securitycenter_v1p1beta1_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v1p1beta1 - - -def sample_update_source(): - # Create a client - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v1p1beta1.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json deleted file mode 100644 index 774592ce11f7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json +++ /dev/null @@ -1,3808 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.securitycenter.v1p1beta1", - "version": "v1p1beta1" - } - ], - "language": "PYTHON", - "name": "google-cloud-securitycenter", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v1p1beta1_generated_security_center_create_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1p1beta1_generated_security_center_create_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateFinding_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": "securitycenter_v1p1beta1_generated_security_center_create_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.create_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "config_id", - "type": "str" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig", - "shortName": "create_notification_config" - }, - "description": "Sample for CreateNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.create_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "config_id", - "type": "str" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig", - "shortName": "create_notification_config" - }, - "description": "Sample for CreateNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_create_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1p1beta1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v1p1beta1_generated_security_center_create_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_create_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1p1beta1.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v1p1beta1_generated_security_center_create_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_CreateSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_create_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.delete_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.DeleteNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest" - }, - { - "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_config" - }, - "description": "Sample for DeleteNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.delete_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.DeleteNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest" - }, - { - "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_config" - }, - "description": "Sample for DeleteNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_delete_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest" - }, - { - "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.securitycenter_v1p1beta1.types.NotificationConfig", - "shortName": "get_notification_config" - }, - "description": "Sample for GetNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest" - }, - { - "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.securitycenter_v1p1beta1.types.NotificationConfig", - "shortName": "get_notification_config" - }, - "description": "Sample for GetNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetNotificationConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest" - }, - { - "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.securitycenter_v1p1beta1.types.OrganizationSettings", - "shortName": "get_organization_settings" - }, - "description": "Sample for GetOrganizationSettings", - "file": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest" - }, - { - "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.securitycenter_v1p1beta1.types.OrganizationSettings", - "shortName": "get_organization_settings" - }, - "description": "Sample for GetOrganizationSettings", - "file": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetOrganizationSettings_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_organization_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest" - }, - { - "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.securitycenter_v1p1beta1.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v1p1beta1_generated_security_center_get_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest" - }, - { - "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.securitycenter_v1p1beta1.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v1p1beta1_generated_security_center_get_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GetSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_get_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.group_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsAsyncPager", - "shortName": "group_assets" - }, - "description": "Sample for GroupAssets", - "file": "securitycenter_v1p1beta1_generated_security_center_group_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1p1beta1_generated_security_center_group_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.group_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsPager", - "shortName": "group_assets" - }, - "description": "Sample for GroupAssets", - "file": "securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupAssets_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": "securitycenter_v1p1beta1_generated_security_center_group_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsAsyncPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v1p1beta1_generated_security_center_group_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1p1beta1_generated_security_center_group_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_GroupFindings_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": "securitycenter_v1p1beta1_generated_security_center_group_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsAsyncPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "securitycenter_v1p1beta1_generated_security_center_list_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1p1beta1_generated_security_center_list_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_assets", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListAssets", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_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": "securitycenter_v1p1beta1_generated_security_center_list_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsAsyncPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v1p1beta1_generated_security_center_list_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1p1beta1_generated_security_center_list_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListFindings_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": "securitycenter_v1p1beta1_generated_security_center_list_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_notification_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListNotificationConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListNotificationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsAsyncPager", - "shortName": "list_notification_configs" - }, - "description": "Sample for ListNotificationConfigs", - "file": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_notification_configs", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListNotificationConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListNotificationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsPager", - "shortName": "list_notification_configs" - }, - "description": "Sample for ListNotificationConfigs", - "file": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v1p1beta1_generated_security_center_list_notification_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesAsyncPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v1p1beta1_generated_security_center_list_sources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1p1beta1_generated_security_center_list_sources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest" - }, - { - "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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_ListSources_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": "securitycenter_v1p1beta1_generated_security_center_list_sources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.run_asset_discovery", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.RunAssetDiscovery", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "RunAssetDiscovery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "run_asset_discovery" - }, - "description": "Sample for RunAssetDiscovery", - "file": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.run_asset_discovery", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.RunAssetDiscovery", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "RunAssetDiscovery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "run_asset_discovery" - }, - "description": "Sample for RunAssetDiscovery", - "file": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_RunAssetDiscovery_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": "securitycenter_v1p1beta1_generated_security_center_run_asset_discovery_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v1p1beta1.types.Finding.State" - }, - { - "name": "start_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v1p1beta1.types.Finding.State" - }, - { - "name": "start_time", - "type": "google.protobuf.timestamp_pb2.Timestamp" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetFindingState_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": "securitycenter_v1p1beta1_generated_security_center_set_finding_state_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v1p1beta1_generated_security_center_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" - }, - { - "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.securitycenter_v1p1beta1.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v1p1beta1_generated_security_center_update_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1p1beta1_generated_security_center_update_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v1p1beta1.types.Finding" - }, - { - "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.securitycenter_v1p1beta1.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v1p1beta1_generated_security_center_update_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" - }, - { - "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.securitycenter_v1p1beta1.types.NotificationConfig", - "shortName": "update_notification_config" - }, - "description": "Sample for UpdateNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v1p1beta1.types.NotificationConfig" - }, - { - "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.securitycenter_v1p1beta1.types.NotificationConfig", - "shortName": "update_notification_config" - }, - "description": "Sample for UpdateNotificationConfig", - "file": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v1p1beta1_generated_security_center_update_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest" - }, - { - "name": "organization_settings", - "type": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings", - "shortName": "update_organization_settings" - }, - "description": "Sample for UpdateOrganizationSettings", - "file": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_organization_settings", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateOrganizationSettings", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateOrganizationSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest" - }, - { - "name": "organization_settings", - "type": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings", - "shortName": "update_organization_settings" - }, - "description": "Sample for UpdateOrganizationSettings", - "file": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateOrganizationSettings_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": "securitycenter_v1p1beta1_generated_security_center_update_organization_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v1p1beta1.types.SecurityMarks" - }, - { - "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.securitycenter_v1p1beta1.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v1p1beta1.types.SecurityMarks" - }, - { - "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.securitycenter_v1p1beta1.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v1p1beta1_generated_security_center_update_security_marks_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterAsyncClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1p1beta1.types.Source" - }, - { - "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.securitycenter_v1p1beta1.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v1p1beta1_generated_security_center_update_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1p1beta1_generated_security_center_update_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v1p1beta1.SecurityCenterClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v1p1beta1.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v1p1beta1.types.Source" - }, - { - "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.securitycenter_v1p1beta1.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v1p1beta1_generated_security_center_update_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v1p1beta1_generated_SecurityCenter_UpdateSource_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": "securitycenter_v1p1beta1_generated_security_center_update_source_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py deleted file mode 100644 index 51a5e411dcfb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py +++ /dev/null @@ -1,198 +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 securitycenterCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_notification_config': ('parent', 'config_id', 'notification_config', ), - 'create_source': ('parent', 'source', ), - 'delete_notification_config': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_notification_config': ('name', ), - 'get_organization_settings': ('name', ), - 'get_source': ('name', ), - 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), - 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), - 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_notification_configs': ('parent', 'page_token', 'page_size', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'run_asset_discovery': ('parent', ), - 'set_finding_state': ('name', 'state', 'start_time', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_notification_config': ('notification_config', 'update_mask', ), - 'update_organization_settings': ('organization_settings', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), - 'update_source': ('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=securitycenterCallTransformer(), -): - """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 securitycenter 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-securitycenter/v1p1beta1/setup.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/setup.py deleted file mode 100644 index c4538ec101f3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/setup.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. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-securitycenter' - - -description = "Google Cloud Securitycenter API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/securitycenter/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", - "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", -] -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" - -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/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-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__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-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py deleted file mode 100644 index 8de42633a7ea..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py +++ /dev/null @@ -1,18405 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -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 - -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.securitycenter_v1p1beta1.services.security_center import SecurityCenterAsyncClient -from google.cloud.securitycenter_v1p1beta1.services.security_center import SecurityCenterClient -from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1p1beta1.services.security_center import transports -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1p1beta1.types import security_marks -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -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 duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None - assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert SecurityCenterClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SecurityCenterGrpcTransport, "grpc"), - (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - 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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -def test_security_center_client_get_transport_class(): - transport = SecurityCenterClient.get_transport_class() - available_transports = [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterRestTransport, - ] - assert transport in available_transports - - transport = SecurityCenterClient.get_transport_class("grpc") - assert transport == transports.SecurityCenterGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, 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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), -]) -def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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_security_center_client_client_options_from_dict(): - with mock.patch('google.cloud.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_create_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object - - request = {} - await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_create_source_async_from_dict(): - await test_create_source_async(request_type=dict) - - -def test_create_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.create_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - - -def test_create_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - response = client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -def test_create_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.create_finding] = mock_rpc - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object - - request = {} - await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_create_finding_async_from_dict(): - await test_create_finding_async(request_type=dict) - - -def test_create_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - arg = args[0].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - - -def test_create_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - arg = args[0].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateNotificationConfigRequest, - dict, -]) -def test_create_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_create_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateNotificationConfigRequest( - parent='parent_value', - config_id='config_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest( - parent='parent_value', - config_id='config_id_value', - ) - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_create_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_notification_config] = mock_object - - request = {} - await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_create_notification_config_async_from_dict(): - await test_create_notification_config_async(request_type=dict) - - -def test_create_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.create_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.create_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_notification_config( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - # Establish that the 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].config_id - mock_val = 'config_id_value' - assert arg == mock_val - arg = args[0].notification_config - mock_val = gcs_notification_config.NotificationConfig(name='name_value') - assert arg == mock_val - - -def test_create_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_notification_config( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - # Establish that 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].config_id - mock_val = 'config_id_value' - assert arg == mock_val - arg = args[0].notification_config - mock_val = gcs_notification_config.NotificationConfig(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_notification_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteNotificationConfigRequest, - dict, -]) -def test_delete_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteNotificationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest( - name='name_value', - ) - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_delete_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_notification_config] = mock_object - - request = {} - await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteNotificationConfigRequest() - 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_config_async_from_dict(): - await test_delete_notification_config_async(request_type=dict) - - -def test_delete_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = None - client.delete_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_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_notification_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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_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_notification_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_notification_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.GetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest( - resource='resource_value', - ) - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object - - request = {} - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_get_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetNotificationConfigRequest, - dict, -]) -def test_get_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_get_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetNotificationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest( - name='name_value', - ) - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_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_notification_config] = mock_rpc - request = {} - client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_get_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_notification_config] = mock_object - - request = {} - await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_get_notification_config_async_from_dict(): - await test_get_notification_config_async(request_type=dict) - - -def test_get_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = notification_config.NotificationConfig() - client.get_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - await client.get_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_notification_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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_notification_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_notification_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetOrganizationSettingsRequest, - dict, -]) -def test_get_organization_settings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_get_organization_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetOrganizationSettingsRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_organization_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest( - name='name_value', - ) - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_organization_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_organization_settings] = mock_rpc - request = {} - client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_organization_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_organization_settings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - -@pytest.mark.asyncio -async def test_get_organization_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_organization_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_organization_settings] = mock_object - - request = {} - await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_organization_settings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_get_organization_settings_async_from_dict(): - await test_get_organization_settings_async(request_type=dict) - - -def test_get_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = organization_settings.OrganizationSettings() - client.get_organization_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_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - await client.get_organization_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_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_organization_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_organization_settings_flattened_error(): - client = SecurityCenterClient( - credentials=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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_organization_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_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_get_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest( - name='name_value', - ) - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - -@pytest.mark.asyncio -async def test_get_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object - - request = {} - await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_get_source_async_from_dict(): - await test_get_source_async(request_type=dict) - - -def test_get_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = source.Source() - client.get_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_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_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_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_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupAssetsRequest, - dict, -]) -def test_group_assets(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_assets_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - -def test_group_assets_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupAssetsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_assets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_assets_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc - request = {} - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_group_assets_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - -@pytest.mark.asyncio -async def test_group_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_assets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_assets] = mock_object - - request = {} - await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_assets_async_from_dict(): - await test_group_assets_async(request_type=dict) - - -def test_group_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = securitycenter_service.GroupAssetsResponse() - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_group_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) - await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_group_assets_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_assets(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, securitycenter_service.GroupResult) - for i in results) -def test_group_assets_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_assets(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_group_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_assets(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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_assets(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", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - -@pytest.mark.asyncio -async def test_group_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_findings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object - - request = {} - await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_findings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_findings_async_from_dict(): - await test_group_findings_async(request_type=dict) - - -def test_group_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_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_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - await client.group_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_group_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that the 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - - -def test_group_findings_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - -@pytest.mark.asyncio -async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_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, securitycenter_service.GroupResult) - for i in results) -def test_group_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_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_group_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_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", [ - securitycenter_service.ListAssetsRequest, - dict, -]) -def test_list_assets(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_assets_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - -def test_list_assets_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListAssetsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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_assets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_assets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_value', - page_token='page_token_value', - ) - -def test_list_assets_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc - request = {} - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_assets_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - -@pytest.mark.asyncio -async def test_list_assets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_assets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_assets] = mock_object - - request = {} - await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAssetsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_assets_async_from_dict(): - await test_list_assets_async(request_type=dict) - - -def test_list_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = securitycenter_service.ListAssetsResponse() - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) - await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_assets_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_assets( - 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_assets_flattened_error(): - client = SecurityCenterClient( - credentials=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_assets( - securitycenter_service.ListAssetsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_assets_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_assets( - 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_assets_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_assets( - securitycenter_service.ListAssetsRequest(), - parent='parent_value', - ) - - -def test_list_assets_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) -def test_list_assets_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_assets(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_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - 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_assets(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", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -def test_list_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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] == securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - -@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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object - - request = {} - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -@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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( - 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 = securitycenter_service.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', - ) - - # Establish that the 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_findings_flattened_error(): - client = SecurityCenterClient( - credentials=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( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_findings_flattened_async(): - client = SecurityCenterAsyncClient( - 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 = securitycenter_service.ListFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.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', - ) - - # Establish that 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_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_findings( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - - -def test_list_findings_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in results) -def test_list_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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 = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_findings_async_pages(): - client = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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", [ - securitycenter_service.ListNotificationConfigsRequest, - dict, -]) -def test_list_notification_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListNotificationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_notification_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListNotificationConfigsRequest( - 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_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notification_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_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_notification_configs] = mock_rpc - request = {} - client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_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_notification_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - -@pytest.mark.asyncio -async def test_list_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_notification_configs] = mock_object - - request = {} - await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_notification_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListNotificationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_from_dict(): - await test_list_notification_configs_async(request_type=dict) - - -def test_list_notification_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - 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_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - client.list_notification_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_notification_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - 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_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - await client.list_notification_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_notification_configs_flattened(): - client = SecurityCenterClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_notification_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_notification_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_notification_configs_flattened_async(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_notification_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_notification_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_notification_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - 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_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, notification_config.NotificationConfig) - for i in results) -def test_list_notification_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_notification_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_notification_configs_async_pager(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_notification_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, notification_config.NotificationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_pages(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - 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_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", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_sources_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListSourcesRequest( - 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_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - -@pytest.mark.asyncio -async def test_list_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_sources in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object - - request = {} - await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_sources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_sources_async_from_dict(): - await test_list_sources_async(request_type=dict) - - -def test_list_sources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = securitycenter_service.ListSourcesResponse() - client.list_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_sources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - await client.list_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_sources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_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_sources_flattened_error(): - client = SecurityCenterClient( - credentials=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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_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_sources_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_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, source.Source) - for i in results) -def test_list_sources_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = list(client.list_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_sources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_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, source.Source) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - 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_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", [ - securitycenter_service.RunAssetDiscoveryRequest, - dict, -]) -def test_run_asset_discovery(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.RunAssetDiscoveryRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_run_asset_discovery_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - -def test_run_asset_discovery_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.RunAssetDiscoveryRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.run_asset_discovery(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest( - parent='parent_value', - ) - -def test_run_asset_discovery_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.run_asset_discovery in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc - request = {} - client.run_asset_discovery(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.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_run_asset_discovery_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - -@pytest.mark.asyncio -async def test_run_asset_discovery_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.run_asset_discovery in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.run_asset_discovery] = mock_object - - request = {} - await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.RunAssetDiscoveryRequest() - 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_run_asset_discovery_async_from_dict(): - await test_run_asset_discovery_async(request_type=dict) - - -def test_run_asset_discovery_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_run_asset_discovery_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_run_asset_discovery_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery( - 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_run_asset_discovery_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_run_asset_discovery_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__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.run_asset_discovery( - 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_run_asset_discovery_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - response = client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -def test_set_finding_state_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - -@pytest.mark.asyncio -async def test_set_finding_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object - - request = {} - await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_finding_state(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_set_finding_state_async_from_dict(): - await test_set_finding_state_async(request_type=dict) - - -def test_set_finding_state_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = finding.Finding() - client.set_finding_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_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_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_set_finding_state_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - - -def test_set_finding_state_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.SetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest( - resource='resource_value', - ) - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object - - request = {} - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = SecurityCenterClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.TestIamPermissionsRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( - resource='resource_value', - ) - -def test_test_iam_permissions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object - - request = {} - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - response = client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -def test_update_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateFindingRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.update_finding] = mock_rpc - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object - - request = {} - await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_finding_async_from_dict(): - await test_update_finding_async(request_type=dict) - - -def test_update_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -def test_update_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_finding( - finding=gcs_finding.Finding(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].finding - mock_val = gcs_finding.Finding(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_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_finding( - finding=gcs_finding.Finding(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].finding - mock_val = gcs_finding.Finding(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_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateNotificationConfigRequest, - dict, -]) -def test_update_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_update_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateNotificationConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest( - ) - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_update_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_notification_config] = mock_object - - request = {} - await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_update_notification_config_async_from_dict(): - await test_update_notification_config_async(request_type=dict) - - -def test_update_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.update_notification_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', - 'notification_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.update_notification_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', - 'notification_config.name=name_value', - ) in kw['metadata'] - - -def test_update_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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].notification_config - mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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].notification_config - mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_notification_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateOrganizationSettingsRequest, - dict, -]) -def test_update_organization_settings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_update_organization_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateOrganizationSettingsRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_organization_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest( - ) - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_organization_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_organization_settings] = mock_rpc - request = {} - client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_organization_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_organization_settings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - -@pytest.mark.asyncio -async def test_update_organization_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_organization_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_organization_settings] = mock_object - - request = {} - await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_organization_settings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateOrganizationSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_update_organization_settings_async_from_dict(): - await test_update_organization_settings_async(request_type=dict) - - -def test_update_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = gcs_organization_settings.OrganizationSettings() - client.update_organization_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', - 'organization_settings.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - await client.update_organization_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', - 'organization_settings.name=name_value', - ) in kw['metadata'] - - -def test_update_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].organization_settings - mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') - assert arg == mock_val - - -def test_update_organization_settings_flattened_error(): - client = SecurityCenterClient( - credentials=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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].organization_settings - mock_val = gcs_organization_settings.OrganizationSettings(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSourceRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object - - request = {} - await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_source_async_from_dict(): - await test_update_source_async(request_type=dict) - - -def test_update_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -def test_update_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_source( - source=gcs_source.Source(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].source - mock_val = gcs_source.Source(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_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_source( - source=gcs_source.Source(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].source - mock_val = gcs_source.Source(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_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - response = client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_security_marks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - -def test_update_security_marks_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSecurityMarksRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( - ) - -def test_update_security_marks_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish that a new wrapper 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_security_marks_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - -@pytest.mark.asyncio -async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_marks in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object - - request = {} - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_security_marks(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_security_marks_async_from_dict(): - await test_update_security_marks_async(request_type=dict) - - -def test_update_security_marks_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -def test_update_security_marks_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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].security_marks - mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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].security_marks - mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.CreateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_source(request) - - -def test_create_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1p1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_create_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -def test_create_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request_init["finding"] = {'name': 'name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.create_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.create_finding] = mock_rpc - - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["finding_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 "findingId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "findingId" in jsonified_request - assert jsonified_request["findingId"] == request_init["finding_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["findingId"] = 'finding_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request - assert jsonified_request["findingId"] == 'finding_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.create_finding(request) - - expected_params = [ - ( - "findingId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.CreateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_finding(request) - - -def test_create_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(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 = gcs_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.create_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/v1p1beta1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) - - -def test_create_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_create_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateNotificationConfigRequest, - dict, -]) -def test_create_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["notification_config"] = {'name': 'name_value', 'description': 'description_value', 'event_type': 1, 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.CreateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): - del request_init["notification_config"][field][i][subfield] - else: - del request_init["notification_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 = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.CreateNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["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 "configId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "configId" in jsonified_request - assert jsonified_request["configId"] == request_init["config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["configId"] = 'config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("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 "configId" in jsonified_request - assert jsonified_request["configId"] == 'config_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ( - "configId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("configId", )) & set(("parent", "configId", "notificationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateNotificationConfigRequest.pb(securitycenter_service.CreateNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) - - request = securitycenter_service.CreateNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_notification_config.NotificationConfig() - - client.create_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_notification_config(request) - - -def test_create_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/v1p1beta1/{parent=organizations/*}/notificationConfigs" % client.transport._host, args[1]) - - -def test_create_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - -def test_create_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteNotificationConfigRequest, - dict, -]) -def test_delete_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/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 = 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_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.DeleteNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_notification_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteNotificationConfigRequest.pb(securitycenter_service.DeleteNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_notification_config(request) - - -def test_delete_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/notificationConfigs/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_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/v1p1beta1/{name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -def test_delete_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.get_iam_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/v1p1beta1/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetNotificationConfigRequest, - dict, -]) -def test_get_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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_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_notification_config] = mock_rpc - - request = {} - client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.GetNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetNotificationConfigRequest.pb(securitycenter_service.GetNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = notification_config.NotificationConfig.to_json(notification_config.NotificationConfig()) - - request = securitycenter_service.GetNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = notification_config.NotificationConfig() - - client.get_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/notificationConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_notification_config(request) - - -def test_get_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/notificationConfigs/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 = notification_config.NotificationConfig.pb(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_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/v1p1beta1/{name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_get_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -def test_get_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetOrganizationSettingsRequest, - dict, -]) -def test_get_organization_settings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/organizationSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - -def test_get_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_organization_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_organization_settings] = mock_rpc - - request = {} - client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.GetOrganizationSettingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_organization_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_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_organization_settings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_organization_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_organization_settings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_organization_settings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_organization_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetOrganizationSettingsRequest.pb(securitycenter_service.GetOrganizationSettingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = organization_settings.OrganizationSettings.to_json(organization_settings.OrganizationSettings()) - - request = securitycenter_service.GetOrganizationSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = organization_settings.OrganizationSettings() - - client.get_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/organizationSettings'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_organization_settings(request) - - -def test_get_organization_settings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organization_settings.OrganizationSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/organizationSettings'} - - # get truthy value for each flattened field - mock_args = dict( - 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 = organization_settings.OrganizationSettings.pb(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_organization_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/v1p1beta1/{name=organizations/*/organizationSettings}" % client.transport._host, args[1]) - - -def test_get_organization_settings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -def test_get_organization_settings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/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 = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = source.Source.to_json(source.Source()) - - request = securitycenter_service.GetSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = source.Source() - - client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_source(request) - - -def test_get_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v1p1beta1/{name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_get_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -def test_get_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupAssetsRequest, - dict, -]) -def test_group_assets_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_group_assets_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.group_assets] = mock_rpc - - request = {} - client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_assets(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_group_assets_rest_required_fields(request_type=securitycenter_service.GroupAssetsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_assets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupAssetsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_assets_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_assets_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_assets") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupAssetsRequest.pb(securitycenter_service.GroupAssetsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupAssetsResponse.to_json(securitycenter_service.GroupAssetsResponse()) - - request = securitycenter_service.GroupAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupAssetsResponse() - - client.group_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_assets(request) - - -def test_group_assets_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupAssetsResponse.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': 'organizations/sample1'} - - pager = client.group_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_findings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_findings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_findings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) - - request = securitycenter_service.GroupFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupFindingsResponse() - - client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_findings(request) - - -def test_group_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - group_by='group_by_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v1p1beta1/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) - - -def test_group_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} - - pager = client.group_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_findings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListAssetsRequest, - dict, -]) -def test_list_assets_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListAssetsResponse.pb(return_value) - 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_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_list_assets_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_assets in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_assets] = mock_rpc - - request = {} - client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_assets(request) - - # Establish 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_assets_rest_required_fields(request_type=securitycenter_service.ListAssetsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_assets._get_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_assets._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) - jsonified_request.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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAssetsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListAssetsResponse.pb(return_value) - 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_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_assets_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_assets_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_assets") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListAssetsRequest.pb(securitycenter_service.ListAssetsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListAssetsResponse.to_json(securitycenter_service.ListAssetsResponse()) - - request = securitycenter_service.ListAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListAssetsResponse() - - client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_assets(request) - - -def test_list_assets_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAssetsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListAssetsResponse.pb(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_assets(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1p1beta1/{parent=organizations/*}/assets" % client.transport._host, args[1]) - - -def test_list_assets_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_assets( - securitycenter_service.ListAssetsRequest(), - parent='parent_value', - ) - - -def test_list_assets_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListAssetsResponse.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': 'organizations/sample1'} - - pager = client.list_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) - - pages = list(client.list_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.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' - assert response.total_size == 1086 - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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=securitycenter_service.ListFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("compare_duration", "field_mask", "filter", "order_by", "page_size", "page_token", "read_time", )) - jsonified_request.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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.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 = securitycenter_service.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 = [ - ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("compareDuration", "fieldMask", "filter", "orderBy", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) - - request = securitycenter_service.ListFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListFindingsResponse() - - client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_findings(request) - - -def test_list_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.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/v1p1beta1/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) - - -def test_list_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - - -def test_list_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} - - pager = client.list_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) - 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 - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListNotificationConfigsRequest, - dict, -]) -def test_list_notification_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) - 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_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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_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_notification_configs] = mock_rpc - - request = {} - client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_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_notification_configs_rest_required_fields(request_type=securitycenter_service.ListNotificationConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListNotificationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) - 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_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_notification_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_notification_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_notification_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_notification_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_notification_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListNotificationConfigsRequest.pb(securitycenter_service.ListNotificationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListNotificationConfigsResponse.to_json(securitycenter_service.ListNotificationConfigsResponse()) - - request = securitycenter_service.ListNotificationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListNotificationConfigsResponse() - - client.list_notification_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_notification_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_notification_configs(request) - - -def test_list_notification_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListNotificationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse.pb(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_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/v1p1beta1/{parent=organizations/*}/notificationConfigs" % client.transport._host, args[1]) - - -def test_list_notification_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListNotificationConfigsResponse.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': 'organizations/sample1'} - - pager = client.list_notification_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, notification_config.NotificationConfig) - for i in results) - - pages = list(client.list_notification_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_sources_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_sources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_sources_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) - - request = securitycenter_service.ListSourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListSourcesResponse() - - client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_sources(request) - - -def test_list_sources_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v1p1beta1/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_list_sources_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} - - pager = client.list_sources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, source.Source) - for i in results) - - pages = list(client.list_sources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.RunAssetDiscoveryRequest, - dict, -]) -def test_run_asset_discovery_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') - - # 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 - response = client.run_asset_discovery(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_run_asset_discovery_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.run_asset_discovery in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.run_asset_discovery] = mock_rpc - - request = {} - client.run_asset_discovery(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.run_asset_discovery(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_run_asset_discovery_rest_required_fields(request_type=securitycenter_service.RunAssetDiscoveryRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).run_asset_discovery._get_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()).run_asset_discovery._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 = SecurityCenterClient( - 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.run_asset_discovery(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_run_asset_discovery_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.run_asset_discovery._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_run_asset_discovery_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_run_asset_discovery") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_run_asset_discovery") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.RunAssetDiscoveryRequest.pb(securitycenter_service.RunAssetDiscoveryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = securitycenter_service.RunAssetDiscoveryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.run_asset_discovery(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_run_asset_discovery_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.run_asset_discovery(request) - - -def test_run_asset_discovery_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.run_asset_discovery(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1p1beta1/{parent=organizations/*}/assets:runDiscovery" % client.transport._host, args[1]) - - -def test_run_asset_discovery_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -def test_run_asset_discovery_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - - # 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 - response = client.set_finding_state(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( - 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': "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 = 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.set_finding_state(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_finding_state_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_finding_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "state", "startTime", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_finding_state_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = finding.Finding.to_json(finding.Finding()) - - request = securitycenter_service.SetFindingStateRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_finding_state(request) - - -def test_set_finding_state_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - mock_args.update(sample_request) - - # 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.set_finding_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/v1p1beta1/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) - - -def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -def test_set_finding_state_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.set_iam_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/v1p1beta1/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # 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 - response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_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.test_iam_permissions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1p1beta1/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.update_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.update_finding] = mock_rpc - - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_finding._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_finding._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.update_finding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.UpdateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_finding(request) - - -def test_update_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - finding=gcs_finding.Finding(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 = gcs_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.update_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/v1p1beta1/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) - - -def test_update_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateNotificationConfigRequest, - dict, -]) -def test_update_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} - request_init["notification_config"] = {'name': 'organizations/sample1/notificationConfigs/sample2', 'description': 'description_value', 'event_type': 1, 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.UpdateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): - del request_init["notification_config"][field][i][subfield] - else: - del request_init["notification_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 = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.UpdateNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("notificationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateNotificationConfigRequest.pb(securitycenter_service.UpdateNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) - - request = securitycenter_service.UpdateNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_notification_config.NotificationConfig() - - client.update_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_notification_config(request) - - -def test_update_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'notification_config': {'name': 'organizations/sample1/notificationConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/v1p1beta1/{notification_config.name=organizations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_update_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateOrganizationSettingsRequest, - dict, -]) -def test_update_organization_settings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - request_init["organization_settings"] = {'name': 'organizations/sample1/organizationSettings', 'enable_asset_discovery': True, 'asset_discovery_config': {'project_ids': ['project_ids_value1', 'project_ids_value2'], 'inclusion_mode': 1, 'folder_ids': ['folder_ids_value1', 'folder_ids_value2']}} - # The version of a generated dependency at test runtime may differ from the version used 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 = securitycenter_service.UpdateOrganizationSettingsRequest.meta.fields["organization_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["organization_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["organization_settings"][field])): - del request_init["organization_settings"][field][i][subfield] - else: - del request_init["organization_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 = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - -def test_update_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_organization_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_organization_settings] = mock_rpc - - request = {} - client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_organization_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_organization_settings_rest_required_fields(request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_organization_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_organization_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_organization_settings.OrganizationSettings() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_organization_settings.OrganizationSettings.pb(return_value) - 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_organization_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_organization_settings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_organization_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("organizationSettings", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_organization_settings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_organization_settings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_organization_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateOrganizationSettingsRequest.pb(securitycenter_service.UpdateOrganizationSettingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_organization_settings.OrganizationSettings.to_json(gcs_organization_settings.OrganizationSettings()) - - request = securitycenter_service.UpdateOrganizationSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_organization_settings.OrganizationSettings() - - client.update_organization_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_organization_settings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_organization_settings(request) - - -def test_update_organization_settings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_organization_settings.OrganizationSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'organization_settings': {'name': 'organizations/sample1/organizationSettings'}} - - # get truthy value for each flattened field - mock_args = dict( - organization_settings=gcs_organization_settings.OrganizationSettings(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 = gcs_organization_settings.OrganizationSettings.pb(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_organization_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/v1p1beta1/{organization_settings.name=organizations/*/organizationSettings}" % client.transport._host, args[1]) - - -def test_update_organization_settings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -def test_update_organization_settings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.UpdateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_source(request) - - -def test_update_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v1p1beta1/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_update_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - request_init["security_marks"] = {'name': 'organizations/sample1/assets/sample2/securityMarks', 'marks': {}, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] - - 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["security_marks"].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["security_marks"][field])): - del request_init["security_marks"][field][i][subfield] - else: - del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - -def test_update_security_marks_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_security_marks._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_security_marks._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("start_time", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_security_marks_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_security_marks._get_unset_required_fields({}) - assert set(unset_fields) == (set(("startTime", "updateMask", )) & set(("securityMarks", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_security_marks_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) - - request = securitycenter_service.UpdateSecurityMarksRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_security_marks.SecurityMarks() - - client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_security_marks(request) - - -def test_update_security_marks_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - - # get arguments that satisfy an http rule for this method - sample_request = {'security_marks': {'name': 'organizations/sample1/assets/sample2/securityMarks'}} - - # get truthy value for each flattened field - mock_args = dict( - security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1p1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}" % client.transport._host, args[1]) - - -def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_security_marks_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SecurityCenterClient( - 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 = SecurityCenterClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SecurityCenterClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SecurityCenterClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SecurityCenterGrpcTransport, - ) - -def test_security_center_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_security_center_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_source', - 'create_finding', - 'create_notification_config', - 'delete_notification_config', - 'get_iam_policy', - 'get_notification_config', - 'get_organization_settings', - 'get_source', - 'group_assets', - 'group_findings', - 'list_assets', - 'list_findings', - 'list_notification_configs', - 'list_sources', - 'run_asset_discovery', - 'set_finding_state', - 'set_iam_policy', - 'test_iam_permissions', - 'update_finding', - 'update_notification_config', - 'update_organization_settings', - 'update_source', - 'update_security_marks', - ) - 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_security_center_base_transport_with_credentials_file(): - # Instantiate the 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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - 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_security_center_base_transport_with_adc(): - # Test the default 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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport() - adc.assert_called_once() - - -def test_security_center_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) - SecurityCenterClient() - 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -def test_security_center_transport_auth_adc(transport_class): - # If 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, - ], -) -def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), - (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_security_center_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host 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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_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.SecurityCenterRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_security_center_rest_lro_client(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a 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 - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_no_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_with_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_security_center_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SecurityCenterClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SecurityCenterClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_source._session - session2 = client2.transport.create_source._session - assert session1 != session2 - session1 = client1.transport.create_finding._session - session2 = client2.transport.create_finding._session - assert session1 != session2 - session1 = client1.transport.create_notification_config._session - session2 = client2.transport.create_notification_config._session - assert session1 != session2 - session1 = client1.transport.delete_notification_config._session - session2 = client2.transport.delete_notification_config._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.get_notification_config._session - session2 = client2.transport.get_notification_config._session - assert session1 != session2 - session1 = client1.transport.get_organization_settings._session - session2 = client2.transport.get_organization_settings._session - assert session1 != session2 - session1 = client1.transport.get_source._session - session2 = client2.transport.get_source._session - assert session1 != session2 - session1 = client1.transport.group_assets._session - session2 = client2.transport.group_assets._session - assert session1 != session2 - session1 = client1.transport.group_findings._session - session2 = client2.transport.group_findings._session - assert session1 != session2 - session1 = client1.transport.list_assets._session - session2 = client2.transport.list_assets._session - assert session1 != session2 - session1 = client1.transport.list_findings._session - session2 = client2.transport.list_findings._session - assert session1 != session2 - session1 = client1.transport.list_notification_configs._session - session2 = client2.transport.list_notification_configs._session - assert session1 != session2 - session1 = client1.transport.list_sources._session - session2 = client2.transport.list_sources._session - assert session1 != session2 - session1 = client1.transport.run_asset_discovery._session - session2 = client2.transport.run_asset_discovery._session - assert session1 != session2 - session1 = client1.transport.set_finding_state._session - session2 = client2.transport.set_finding_state._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 - session1 = client1.transport.update_finding._session - session2 = client2.transport.update_finding._session - assert session1 != session2 - session1 = client1.transport.update_notification_config._session - session2 = client2.transport.update_notification_config._session - assert session1 != session2 - session1 = client1.transport.update_organization_settings._session - session2 = client2.transport.update_organization_settings._session - assert session1 != session2 - session1 = client1.transport.update_source._session - session2 = client2.transport.update_source._session - assert session1 != session2 - session1 = client1.transport.update_security_marks._session - session2 = client2.transport.update_security_marks._session - assert session1 != session2 -def test_security_center_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcTransport( - 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_security_center_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcAsyncIOTransport( - 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(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_security_center_grpc_lro_client(): - client = SecurityCenterClient( - 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_security_center_grpc_lro_async_client(): - client = SecurityCenterAsyncClient( - 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_asset_path(): - organization = "squid" - asset = "clam" - expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.asset_path(organization, asset) - assert expected == actual - - -def test_parse_asset_path(): - expected = { - "organization": "whelk", - "asset": "octopus", - } - path = SecurityCenterClient.asset_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_asset_path(path) - assert expected == actual - -def test_finding_path(): - organization = "oyster" - source = "nudibranch" - finding = "cuttlefish" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - actual = SecurityCenterClient.finding_path(organization, source, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "organization": "mussel", - "source": "winkle", - "finding": "nautilus", - } - path = SecurityCenterClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_finding_path(path) - assert expected == actual - -def test_notification_config_path(): - organization = "scallop" - notification_config = "abalone" - expected = "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) - actual = SecurityCenterClient.notification_config_path(organization, notification_config) - assert expected == actual - - -def test_parse_notification_config_path(): - expected = { - "organization": "squid", - "notification_config": "clam", - } - path = SecurityCenterClient.notification_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_notification_config_path(path) - assert expected == actual - -def test_organization_settings_path(): - organization = "whelk" - expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) - actual = SecurityCenterClient.organization_settings_path(organization) - assert expected == actual - - -def test_parse_organization_settings_path(): - expected = { - "organization": "octopus", - } - path = SecurityCenterClient.organization_settings_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_organization_settings_path(path) - assert expected == actual - -def test_security_marks_path(): - organization = "oyster" - asset = "nudibranch" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.security_marks_path(organization, asset) - assert expected == actual - - -def test_parse_security_marks_path(): - expected = { - "organization": "cuttlefish", - "asset": "mussel", - } - path = SecurityCenterClient.security_marks_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_security_marks_path(path) - assert expected == actual - -def test_source_path(): - organization = "winkle" - source = "nautilus" - expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - actual = SecurityCenterClient.source_path(organization, source) - assert expected == actual - - -def test_parse_source_path(): - expected = { - "organization": "scallop", - "source": "abalone", - } - path = SecurityCenterClient.source_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_source_path(path) - assert expected == actual - -def test_topic_path(): - project = "squid" - topic = "clam" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = SecurityCenterClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "whelk", - "topic": "octopus", - } - path = SecurityCenterClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_topic_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SecurityCenterClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = SecurityCenterClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = SecurityCenterClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = SecurityCenterClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SecurityCenterClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = SecurityCenterClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = SecurityCenterClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = SecurityCenterClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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 = SecurityCenterClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = SecurityCenterClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - transport_class = SecurityCenterClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), -]) -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-securitycenter/v2/.coveragerc b/owl-bot-staging/google-cloud-securitycenter/v2/.coveragerc deleted file mode 100644 index 45cb273f8f7c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/securitycenter/__init__.py - google/cloud/securitycenter/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-securitycenter/v2/.flake8 b/owl-bot-staging/google-cloud-securitycenter/v2/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/MANIFEST.in b/owl-bot-staging/google-cloud-securitycenter/v2/MANIFEST.in deleted file mode 100644 index 7d0a7010fae0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/securitycenter *.py -recursive-include google/cloud/securitycenter_v2 *.py diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/README.rst b/owl-bot-staging/google-cloud-securitycenter/v2/README.rst deleted file mode 100644 index f8c63f4cb48a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Securitycenter 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 Securitycenter 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-securitycenter/v2/docs/_static/custom.css b/owl-bot-staging/google-cloud-securitycenter/v2/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/docs/conf.py b/owl-bot-staging/google-cloud-securitycenter/v2/docs/conf.py deleted file mode 100644 index 8e92d2319721..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter 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-securitycenter" -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-securitycenter-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-securitycenter.tex", - u"google-cloud-securitycenter 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-securitycenter", - u"Google Cloud Securitycenter 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-securitycenter", - u"google-cloud-securitycenter Documentation", - author, - "google-cloud-securitycenter", - "GAPIC library for Google Cloud Securitycenter 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-securitycenter/v2/docs/index.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/index.rst deleted file mode 100644 index af3ca0f134f0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - securitycenter_v2/services - securitycenter_v2/types diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst deleted file mode 100644 index 6b9d3b9b1795..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/security_center.rst +++ /dev/null @@ -1,10 +0,0 @@ -SecurityCenter --------------------------------- - -.. automodule:: google.cloud.securitycenter_v2.services.security_center - :members: - :inherited-members: - -.. automodule:: google.cloud.securitycenter_v2.services.security_center.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst deleted file mode 100644 index adb8a6096090..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Securitycenter v2 API -=============================================== -.. toctree:: - :maxdepth: 2 - - security_center diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst b/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst deleted file mode 100644 index 3210d372fb24..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/docs/securitycenter_v2/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Securitycenter v2 API -============================================ - -.. automodule:: google.cloud.securitycenter_v2.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py deleted file mode 100644 index 121fb285646b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/__init__.py +++ /dev/null @@ -1,257 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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.securitycenter import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.securitycenter_v2.services.security_center.client import SecurityCenterClient -from google.cloud.securitycenter_v2.services.security_center.async_client import SecurityCenterAsyncClient - -from google.cloud.securitycenter_v2.types.access import Access -from google.cloud.securitycenter_v2.types.access import Geolocation -from google.cloud.securitycenter_v2.types.access import ServiceAccountDelegationInfo -from google.cloud.securitycenter_v2.types.application import Application -from google.cloud.securitycenter_v2.types.attack_exposure import AttackExposure -from google.cloud.securitycenter_v2.types.attack_path import AttackPath -from google.cloud.securitycenter_v2.types.backup_disaster_recovery import BackupDisasterRecovery -from google.cloud.securitycenter_v2.types.bigquery_export import BigQueryExport -from google.cloud.securitycenter_v2.types.cloud_armor import AdaptiveProtection -from google.cloud.securitycenter_v2.types.cloud_armor import Attack -from google.cloud.securitycenter_v2.types.cloud_armor import CloudArmor -from google.cloud.securitycenter_v2.types.cloud_armor import Requests -from google.cloud.securitycenter_v2.types.cloud_armor import SecurityPolicy -from google.cloud.securitycenter_v2.types.cloud_dlp_data_profile import CloudDlpDataProfile -from google.cloud.securitycenter_v2.types.cloud_dlp_inspection import CloudDlpInspection -from google.cloud.securitycenter_v2.types.compliance import Compliance -from google.cloud.securitycenter_v2.types.connection import Connection -from google.cloud.securitycenter_v2.types.contact_details import Contact -from google.cloud.securitycenter_v2.types.contact_details import ContactDetails -from google.cloud.securitycenter_v2.types.container import Container -from google.cloud.securitycenter_v2.types.database import Database -from google.cloud.securitycenter_v2.types.exfiltration import ExfilResource -from google.cloud.securitycenter_v2.types.exfiltration import Exfiltration -from google.cloud.securitycenter_v2.types.external_system import ExternalSystem -from google.cloud.securitycenter_v2.types.file import File -from google.cloud.securitycenter_v2.types.finding import Finding -from google.cloud.securitycenter_v2.types.folder import Folder -from google.cloud.securitycenter_v2.types.group_membership import GroupMembership -from google.cloud.securitycenter_v2.types.iam_binding import IamBinding -from google.cloud.securitycenter_v2.types.indicator import Indicator -from google.cloud.securitycenter_v2.types.kernel_rootkit import KernelRootkit -from google.cloud.securitycenter_v2.types.kubernetes import Kubernetes -from google.cloud.securitycenter_v2.types.label import Label -from google.cloud.securitycenter_v2.types.load_balancer import LoadBalancer -from google.cloud.securitycenter_v2.types.log_entry import CloudLoggingEntry -from google.cloud.securitycenter_v2.types.log_entry import LogEntry -from google.cloud.securitycenter_v2.types.mitre_attack import MitreAttack -from google.cloud.securitycenter_v2.types.mute_config import MuteConfig -from google.cloud.securitycenter_v2.types.notebook import Notebook -from google.cloud.securitycenter_v2.types.notification_config import NotificationConfig -from google.cloud.securitycenter_v2.types.notification_message import NotificationMessage -from google.cloud.securitycenter_v2.types.org_policy import OrgPolicy -from google.cloud.securitycenter_v2.types.process import EnvironmentVariable -from google.cloud.securitycenter_v2.types.process import Process -from google.cloud.securitycenter_v2.types.resource import AwsMetadata -from google.cloud.securitycenter_v2.types.resource import AzureMetadata -from google.cloud.securitycenter_v2.types.resource import GcpMetadata -from google.cloud.securitycenter_v2.types.resource import Resource -from google.cloud.securitycenter_v2.types.resource import ResourcePath -from google.cloud.securitycenter_v2.types.resource import CloudProvider -from google.cloud.securitycenter_v2.types.resource_value_config import ResourceValueConfig -from google.cloud.securitycenter_v2.types.resource_value_config import ResourceValue -from google.cloud.securitycenter_v2.types.security_marks import SecurityMarks -from google.cloud.securitycenter_v2.types.security_posture import SecurityPosture -from google.cloud.securitycenter_v2.types.securitycenter_service import BatchCreateResourceValueConfigsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import BatchCreateResourceValueConfigsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import BulkMuteFindingsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import BulkMuteFindingsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import CreateBigQueryExportRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import CreateFindingRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import CreateMuteConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import CreateNotificationConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import CreateResourceValueConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import CreateSourceRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteBigQueryExportRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteMuteConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteNotificationConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import DeleteResourceValueConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetBigQueryExportRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetMuteConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetNotificationConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetResourceValueConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetSimulationRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetSourceRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GetValuedResourceRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GroupFindingsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import GroupFindingsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import GroupResult -from google.cloud.securitycenter_v2.types.securitycenter_service import ListAttackPathsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListAttackPathsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListBigQueryExportsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListBigQueryExportsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListFindingsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListFindingsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListMuteConfigsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListMuteConfigsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListNotificationConfigsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListNotificationConfigsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListResourceValueConfigsRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListResourceValueConfigsResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListSourcesRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListSourcesResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import ListValuedResourcesRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import ListValuedResourcesResponse -from google.cloud.securitycenter_v2.types.securitycenter_service import SetFindingStateRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import SetMuteRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateBigQueryExportRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateExternalSystemRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateFindingRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateMuteConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateNotificationConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateResourceValueConfigRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateSecurityMarksRequest -from google.cloud.securitycenter_v2.types.securitycenter_service import UpdateSourceRequest -from google.cloud.securitycenter_v2.types.simulation import Simulation -from google.cloud.securitycenter_v2.types.source import Source -from google.cloud.securitycenter_v2.types.toxic_combination import ToxicCombination -from google.cloud.securitycenter_v2.types.valued_resource import ResourceValueConfigMetadata -from google.cloud.securitycenter_v2.types.valued_resource import ValuedResource -from google.cloud.securitycenter_v2.types.vulnerability import Cve -from google.cloud.securitycenter_v2.types.vulnerability import Cvssv3 -from google.cloud.securitycenter_v2.types.vulnerability import Package -from google.cloud.securitycenter_v2.types.vulnerability import Reference -from google.cloud.securitycenter_v2.types.vulnerability import SecurityBulletin -from google.cloud.securitycenter_v2.types.vulnerability import Vulnerability - -__all__ = ('SecurityCenterClient', - 'SecurityCenterAsyncClient', - 'Access', - 'Geolocation', - 'ServiceAccountDelegationInfo', - 'Application', - 'AttackExposure', - 'AttackPath', - 'BackupDisasterRecovery', - 'BigQueryExport', - 'AdaptiveProtection', - 'Attack', - 'CloudArmor', - 'Requests', - 'SecurityPolicy', - 'CloudDlpDataProfile', - 'CloudDlpInspection', - 'Compliance', - 'Connection', - 'Contact', - 'ContactDetails', - 'Container', - 'Database', - 'ExfilResource', - 'Exfiltration', - 'ExternalSystem', - 'File', - 'Finding', - 'Folder', - 'GroupMembership', - 'IamBinding', - 'Indicator', - 'KernelRootkit', - 'Kubernetes', - 'Label', - 'LoadBalancer', - 'CloudLoggingEntry', - 'LogEntry', - 'MitreAttack', - 'MuteConfig', - 'Notebook', - 'NotificationConfig', - 'NotificationMessage', - 'OrgPolicy', - 'EnvironmentVariable', - 'Process', - 'AwsMetadata', - 'AzureMetadata', - 'GcpMetadata', - 'Resource', - 'ResourcePath', - 'CloudProvider', - 'ResourceValueConfig', - 'ResourceValue', - 'SecurityMarks', - 'SecurityPosture', - 'BatchCreateResourceValueConfigsRequest', - 'BatchCreateResourceValueConfigsResponse', - 'BulkMuteFindingsRequest', - 'BulkMuteFindingsResponse', - 'CreateBigQueryExportRequest', - 'CreateFindingRequest', - 'CreateMuteConfigRequest', - 'CreateNotificationConfigRequest', - 'CreateResourceValueConfigRequest', - 'CreateSourceRequest', - 'DeleteBigQueryExportRequest', - 'DeleteMuteConfigRequest', - 'DeleteNotificationConfigRequest', - 'DeleteResourceValueConfigRequest', - 'GetBigQueryExportRequest', - 'GetMuteConfigRequest', - 'GetNotificationConfigRequest', - 'GetResourceValueConfigRequest', - 'GetSimulationRequest', - 'GetSourceRequest', - 'GetValuedResourceRequest', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAttackPathsRequest', - 'ListAttackPathsResponse', - 'ListBigQueryExportsRequest', - 'ListBigQueryExportsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListMuteConfigsRequest', - 'ListMuteConfigsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListResourceValueConfigsRequest', - 'ListResourceValueConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListValuedResourcesRequest', - 'ListValuedResourcesResponse', - 'SetFindingStateRequest', - 'SetMuteRequest', - 'UpdateBigQueryExportRequest', - 'UpdateExternalSystemRequest', - 'UpdateFindingRequest', - 'UpdateMuteConfigRequest', - 'UpdateNotificationConfigRequest', - 'UpdateResourceValueConfigRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Simulation', - 'Source', - 'ToxicCombination', - 'ResourceValueConfigMetadata', - 'ValuedResource', - 'Cve', - 'Cvssv3', - 'Package', - 'Reference', - 'SecurityBulletin', - 'Vulnerability', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/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-securitycenter/v2/google/cloud/securitycenter/py.typed b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py deleted file mode 100644 index f27bfdd5500f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/__init__.py +++ /dev/null @@ -1,258 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.securitycenter_v2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.security_center import SecurityCenterClient -from .services.security_center import SecurityCenterAsyncClient - -from .types.access import Access -from .types.access import Geolocation -from .types.access import ServiceAccountDelegationInfo -from .types.application import Application -from .types.attack_exposure import AttackExposure -from .types.attack_path import AttackPath -from .types.backup_disaster_recovery import BackupDisasterRecovery -from .types.bigquery_export import BigQueryExport -from .types.cloud_armor import AdaptiveProtection -from .types.cloud_armor import Attack -from .types.cloud_armor import CloudArmor -from .types.cloud_armor import Requests -from .types.cloud_armor import SecurityPolicy -from .types.cloud_dlp_data_profile import CloudDlpDataProfile -from .types.cloud_dlp_inspection import CloudDlpInspection -from .types.compliance import Compliance -from .types.connection import Connection -from .types.contact_details import Contact -from .types.contact_details import ContactDetails -from .types.container import Container -from .types.database import Database -from .types.exfiltration import ExfilResource -from .types.exfiltration import Exfiltration -from .types.external_system import ExternalSystem -from .types.file import File -from .types.finding import Finding -from .types.folder import Folder -from .types.group_membership import GroupMembership -from .types.iam_binding import IamBinding -from .types.indicator import Indicator -from .types.kernel_rootkit import KernelRootkit -from .types.kubernetes import Kubernetes -from .types.label import Label -from .types.load_balancer import LoadBalancer -from .types.log_entry import CloudLoggingEntry -from .types.log_entry import LogEntry -from .types.mitre_attack import MitreAttack -from .types.mute_config import MuteConfig -from .types.notebook import Notebook -from .types.notification_config import NotificationConfig -from .types.notification_message import NotificationMessage -from .types.org_policy import OrgPolicy -from .types.process import EnvironmentVariable -from .types.process import Process -from .types.resource import AwsMetadata -from .types.resource import AzureMetadata -from .types.resource import GcpMetadata -from .types.resource import Resource -from .types.resource import ResourcePath -from .types.resource import CloudProvider -from .types.resource_value_config import ResourceValueConfig -from .types.resource_value_config import ResourceValue -from .types.security_marks import SecurityMarks -from .types.security_posture import SecurityPosture -from .types.securitycenter_service import BatchCreateResourceValueConfigsRequest -from .types.securitycenter_service import BatchCreateResourceValueConfigsResponse -from .types.securitycenter_service import BulkMuteFindingsRequest -from .types.securitycenter_service import BulkMuteFindingsResponse -from .types.securitycenter_service import CreateBigQueryExportRequest -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateMuteConfigRequest -from .types.securitycenter_service import CreateNotificationConfigRequest -from .types.securitycenter_service import CreateResourceValueConfigRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import DeleteBigQueryExportRequest -from .types.securitycenter_service import DeleteMuteConfigRequest -from .types.securitycenter_service import DeleteNotificationConfigRequest -from .types.securitycenter_service import DeleteResourceValueConfigRequest -from .types.securitycenter_service import GetBigQueryExportRequest -from .types.securitycenter_service import GetMuteConfigRequest -from .types.securitycenter_service import GetNotificationConfigRequest -from .types.securitycenter_service import GetResourceValueConfigRequest -from .types.securitycenter_service import GetSimulationRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GetValuedResourceRequest -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAttackPathsRequest -from .types.securitycenter_service import ListAttackPathsResponse -from .types.securitycenter_service import ListBigQueryExportsRequest -from .types.securitycenter_service import ListBigQueryExportsResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListMuteConfigsRequest -from .types.securitycenter_service import ListMuteConfigsResponse -from .types.securitycenter_service import ListNotificationConfigsRequest -from .types.securitycenter_service import ListNotificationConfigsResponse -from .types.securitycenter_service import ListResourceValueConfigsRequest -from .types.securitycenter_service import ListResourceValueConfigsResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import ListValuedResourcesRequest -from .types.securitycenter_service import ListValuedResourcesResponse -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import SetMuteRequest -from .types.securitycenter_service import UpdateBigQueryExportRequest -from .types.securitycenter_service import UpdateExternalSystemRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateMuteConfigRequest -from .types.securitycenter_service import UpdateNotificationConfigRequest -from .types.securitycenter_service import UpdateResourceValueConfigRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.simulation import Simulation -from .types.source import Source -from .types.toxic_combination import ToxicCombination -from .types.valued_resource import ResourceValueConfigMetadata -from .types.valued_resource import ValuedResource -from .types.vulnerability import Cve -from .types.vulnerability import Cvssv3 -from .types.vulnerability import Package -from .types.vulnerability import Reference -from .types.vulnerability import SecurityBulletin -from .types.vulnerability import Vulnerability - -__all__ = ( - 'SecurityCenterAsyncClient', -'Access', -'AdaptiveProtection', -'Application', -'Attack', -'AttackExposure', -'AttackPath', -'AwsMetadata', -'AzureMetadata', -'BackupDisasterRecovery', -'BatchCreateResourceValueConfigsRequest', -'BatchCreateResourceValueConfigsResponse', -'BigQueryExport', -'BulkMuteFindingsRequest', -'BulkMuteFindingsResponse', -'CloudArmor', -'CloudDlpDataProfile', -'CloudDlpInspection', -'CloudLoggingEntry', -'CloudProvider', -'Compliance', -'Connection', -'Contact', -'ContactDetails', -'Container', -'CreateBigQueryExportRequest', -'CreateFindingRequest', -'CreateMuteConfigRequest', -'CreateNotificationConfigRequest', -'CreateResourceValueConfigRequest', -'CreateSourceRequest', -'Cve', -'Cvssv3', -'Database', -'DeleteBigQueryExportRequest', -'DeleteMuteConfigRequest', -'DeleteNotificationConfigRequest', -'DeleteResourceValueConfigRequest', -'EnvironmentVariable', -'ExfilResource', -'Exfiltration', -'ExternalSystem', -'File', -'Finding', -'Folder', -'GcpMetadata', -'Geolocation', -'GetBigQueryExportRequest', -'GetMuteConfigRequest', -'GetNotificationConfigRequest', -'GetResourceValueConfigRequest', -'GetSimulationRequest', -'GetSourceRequest', -'GetValuedResourceRequest', -'GroupFindingsRequest', -'GroupFindingsResponse', -'GroupMembership', -'GroupResult', -'IamBinding', -'Indicator', -'KernelRootkit', -'Kubernetes', -'Label', -'ListAttackPathsRequest', -'ListAttackPathsResponse', -'ListBigQueryExportsRequest', -'ListBigQueryExportsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListMuteConfigsRequest', -'ListMuteConfigsResponse', -'ListNotificationConfigsRequest', -'ListNotificationConfigsResponse', -'ListResourceValueConfigsRequest', -'ListResourceValueConfigsResponse', -'ListSourcesRequest', -'ListSourcesResponse', -'ListValuedResourcesRequest', -'ListValuedResourcesResponse', -'LoadBalancer', -'LogEntry', -'MitreAttack', -'MuteConfig', -'Notebook', -'NotificationConfig', -'NotificationMessage', -'OrgPolicy', -'Package', -'Process', -'Reference', -'Requests', -'Resource', -'ResourcePath', -'ResourceValue', -'ResourceValueConfig', -'ResourceValueConfigMetadata', -'SecurityBulletin', -'SecurityCenterClient', -'SecurityMarks', -'SecurityPolicy', -'SecurityPosture', -'ServiceAccountDelegationInfo', -'SetFindingStateRequest', -'SetMuteRequest', -'Simulation', -'Source', -'ToxicCombination', -'UpdateBigQueryExportRequest', -'UpdateExternalSystemRequest', -'UpdateFindingRequest', -'UpdateMuteConfigRequest', -'UpdateNotificationConfigRequest', -'UpdateResourceValueConfigRequest', -'UpdateSecurityMarksRequest', -'UpdateSourceRequest', -'ValuedResource', -'Vulnerability', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json deleted file mode 100644 index 517d51c03f32..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_metadata.json +++ /dev/null @@ -1,628 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.securitycenter_v2", - "protoPackage": "google.cloud.securitycenter.v2", - "schema": "1.0", - "services": { - "SecurityCenter": { - "clients": { - "grpc": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "BatchCreateResourceValueConfigs": { - "methods": [ - "batch_create_resource_value_configs" - ] - }, - "BulkMuteFindings": { - "methods": [ - "bulk_mute_findings" - ] - }, - "CreateBigQueryExport": { - "methods": [ - "create_big_query_export" - ] - }, - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateMuteConfig": { - "methods": [ - "create_mute_config" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteBigQueryExport": { - "methods": [ - "delete_big_query_export" - ] - }, - "DeleteMuteConfig": { - "methods": [ - "delete_mute_config" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "DeleteResourceValueConfig": { - "methods": [ - "delete_resource_value_config" - ] - }, - "GetBigQueryExport": { - "methods": [ - "get_big_query_export" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetMuteConfig": { - "methods": [ - "get_mute_config" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetResourceValueConfig": { - "methods": [ - "get_resource_value_config" - ] - }, - "GetSimulation": { - "methods": [ - "get_simulation" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GetValuedResource": { - "methods": [ - "get_valued_resource" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAttackPaths": { - "methods": [ - "list_attack_paths" - ] - }, - "ListBigQueryExports": { - "methods": [ - "list_big_query_exports" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListMuteConfigs": { - "methods": [ - "list_mute_configs" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListResourceValueConfigs": { - "methods": [ - "list_resource_value_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "ListValuedResources": { - "methods": [ - "list_valued_resources" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "SetMute": { - "methods": [ - "set_mute" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateBigQueryExport": { - "methods": [ - "update_big_query_export" - ] - }, - "UpdateExternalSystem": { - "methods": [ - "update_external_system" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateMuteConfig": { - "methods": [ - "update_mute_config" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateResourceValueConfig": { - "methods": [ - "update_resource_value_config" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SecurityCenterAsyncClient", - "rpcs": { - "BatchCreateResourceValueConfigs": { - "methods": [ - "batch_create_resource_value_configs" - ] - }, - "BulkMuteFindings": { - "methods": [ - "bulk_mute_findings" - ] - }, - "CreateBigQueryExport": { - "methods": [ - "create_big_query_export" - ] - }, - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateMuteConfig": { - "methods": [ - "create_mute_config" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteBigQueryExport": { - "methods": [ - "delete_big_query_export" - ] - }, - "DeleteMuteConfig": { - "methods": [ - "delete_mute_config" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "DeleteResourceValueConfig": { - "methods": [ - "delete_resource_value_config" - ] - }, - "GetBigQueryExport": { - "methods": [ - "get_big_query_export" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetMuteConfig": { - "methods": [ - "get_mute_config" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetResourceValueConfig": { - "methods": [ - "get_resource_value_config" - ] - }, - "GetSimulation": { - "methods": [ - "get_simulation" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GetValuedResource": { - "methods": [ - "get_valued_resource" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAttackPaths": { - "methods": [ - "list_attack_paths" - ] - }, - "ListBigQueryExports": { - "methods": [ - "list_big_query_exports" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListMuteConfigs": { - "methods": [ - "list_mute_configs" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListResourceValueConfigs": { - "methods": [ - "list_resource_value_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "ListValuedResources": { - "methods": [ - "list_valued_resources" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "SetMute": { - "methods": [ - "set_mute" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateBigQueryExport": { - "methods": [ - "update_big_query_export" - ] - }, - "UpdateExternalSystem": { - "methods": [ - "update_external_system" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateMuteConfig": { - "methods": [ - "update_mute_config" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateResourceValueConfig": { - "methods": [ - "update_resource_value_config" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "rest": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "BatchCreateResourceValueConfigs": { - "methods": [ - "batch_create_resource_value_configs" - ] - }, - "BulkMuteFindings": { - "methods": [ - "bulk_mute_findings" - ] - }, - "CreateBigQueryExport": { - "methods": [ - "create_big_query_export" - ] - }, - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateMuteConfig": { - "methods": [ - "create_mute_config" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteBigQueryExport": { - "methods": [ - "delete_big_query_export" - ] - }, - "DeleteMuteConfig": { - "methods": [ - "delete_mute_config" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "DeleteResourceValueConfig": { - "methods": [ - "delete_resource_value_config" - ] - }, - "GetBigQueryExport": { - "methods": [ - "get_big_query_export" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetMuteConfig": { - "methods": [ - "get_mute_config" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetResourceValueConfig": { - "methods": [ - "get_resource_value_config" - ] - }, - "GetSimulation": { - "methods": [ - "get_simulation" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GetValuedResource": { - "methods": [ - "get_valued_resource" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAttackPaths": { - "methods": [ - "list_attack_paths" - ] - }, - "ListBigQueryExports": { - "methods": [ - "list_big_query_exports" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListMuteConfigs": { - "methods": [ - "list_mute_configs" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListResourceValueConfigs": { - "methods": [ - "list_resource_value_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "ListValuedResources": { - "methods": [ - "list_valued_resources" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "SetMute": { - "methods": [ - "set_mute" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateBigQueryExport": { - "methods": [ - "update_big_query_export" - ] - }, - "UpdateExternalSystem": { - "methods": [ - "update_external_system" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateMuteConfig": { - "methods": [ - "update_mute_config" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateResourceValueConfig": { - "methods": [ - "update_resource_value_config" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_version.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_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-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed deleted file mode 100644 index 23a44fc7e4ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_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-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__init__.py deleted file mode 100644 index bffcff5da306..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/__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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - 'SecurityCenterClient', - 'SecurityCenterAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py deleted file mode 100644 index 2d6ff6d7cf55..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/async_client.py +++ /dev/null @@ -1,5422 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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 functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.securitycenter_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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.securitycenter_v2.services.security_center import pagers -from google.cloud.securitycenter_v2.types import access -from google.cloud.securitycenter_v2.types import application -from google.cloud.securitycenter_v2.types import attack_exposure -from google.cloud.securitycenter_v2.types import attack_path -from google.cloud.securitycenter_v2.types import backup_disaster_recovery -from google.cloud.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import cloud_armor -from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile -from google.cloud.securitycenter_v2.types import cloud_dlp_inspection -from google.cloud.securitycenter_v2.types import compliance -from google.cloud.securitycenter_v2.types import connection -from google.cloud.securitycenter_v2.types import container -from google.cloud.securitycenter_v2.types import database -from google.cloud.securitycenter_v2.types import exfiltration -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import file -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import group_membership -from google.cloud.securitycenter_v2.types import iam_binding -from google.cloud.securitycenter_v2.types import indicator -from google.cloud.securitycenter_v2.types import kernel_rootkit -from google.cloud.securitycenter_v2.types import kubernetes -from google.cloud.securitycenter_v2.types import load_balancer -from google.cloud.securitycenter_v2.types import log_entry -from google.cloud.securitycenter_v2.types import mitre_attack -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notebook -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import org_policy -from google.cloud.securitycenter_v2.types import process -from google.cloud.securitycenter_v2.types import resource -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import security_posture -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import toxic_combination -from google.cloud.securitycenter_v2.types import valued_resource -from google.cloud.securitycenter_v2.types import vulnerability -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 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 SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V2 APIs for Security Center service.""" - - _client: SecurityCenterClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE - - attack_path_path = staticmethod(SecurityCenterClient.attack_path_path) - parse_attack_path_path = staticmethod(SecurityCenterClient.parse_attack_path_path) - big_query_export_path = staticmethod(SecurityCenterClient.big_query_export_path) - parse_big_query_export_path = staticmethod(SecurityCenterClient.parse_big_query_export_path) - dlp_job_path = staticmethod(SecurityCenterClient.dlp_job_path) - parse_dlp_job_path = staticmethod(SecurityCenterClient.parse_dlp_job_path) - external_system_path = staticmethod(SecurityCenterClient.external_system_path) - parse_external_system_path = staticmethod(SecurityCenterClient.parse_external_system_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) - parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) - mute_config_path = staticmethod(SecurityCenterClient.mute_config_path) - parse_mute_config_path = staticmethod(SecurityCenterClient.parse_mute_config_path) - notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) - parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) - policy_path = staticmethod(SecurityCenterClient.policy_path) - parse_policy_path = staticmethod(SecurityCenterClient.parse_policy_path) - resource_value_config_path = staticmethod(SecurityCenterClient.resource_value_config_path) - parse_resource_value_config_path = staticmethod(SecurityCenterClient.parse_resource_value_config_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) - simulation_path = staticmethod(SecurityCenterClient.simulation_path) - parse_simulation_path = staticmethod(SecurityCenterClient.parse_simulation_path) - source_path = staticmethod(SecurityCenterClient.source_path) - parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) - table_data_profile_path = staticmethod(SecurityCenterClient.table_data_profile_path) - parse_table_data_profile_path = staticmethod(SecurityCenterClient.parse_table_data_profile_path) - topic_path = staticmethod(SecurityCenterClient.topic_path) - parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) - valued_resource_path = staticmethod(SecurityCenterClient.valued_resource_path) - parse_valued_resource_path = staticmethod(SecurityCenterClient.parse_valued_resource_path) - common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) - parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) - common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) - parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) - parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) - parse_common_location_path = staticmethod(SecurityCenterClient.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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, 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 SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: 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 = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def batch_create_resource_value_configs(self, - request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - r"""Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - requests = securitycenter_v2.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - - request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest, dict]]): - The request object. Request message to create multiple - resource value configs - parent (:class:`str`): - Required. Resource name of the new - ResourceValueConfig's parent. The parent - field in the - CreateResourceValueConfigRequest - messages must either be empty or match - this field. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - requests (:class:`MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]`): - Required. The resource value configs - to be created. - - This corresponds to the ``requests`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse: - Response message for - BatchCreateResourceValueConfigs - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, requests]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): - request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if requests: - request.requests.extend(requests) - - # 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_resource_value_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, - ) - - # Done; return the response. - return response - - async def bulk_mute_findings(self, - request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), - ) -> operation_async.AsyncOperation: - r"""Kicks off an LRO to bulk mute findings for a parent - based on a filter. If no location is specified, findings - are muted in global. The parent can be either an - organization, folder, or project. The findings matched - by the filter will be muted after the LRO is done. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest, dict]]): - The request object. Request message for bulk findings - update. - Note: - - 1. If multiple bulk update requests - match the same resource, the order - in which they get executed is not - defined. - 2. Once a bulk operation is started, - there is no way to stop it. - parent (:class:`str`): - Required. The parent, at which bulk action needs to be - applied. If no location is specified, findings are - updated in global. The following list shows some - examples: - - - ``organizations/[organization_id]`` - - ``organizations/[organization_id]/locations/[location_id]`` - - ``folders/[folder_id]`` - - ``folders/[folder_id]/locations/[location_id]`` - - ``projects/[project_id]`` - - ``projects/[project_id]/locations/[location_id]`` - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v2.types.BulkMuteFindingsResponse` - The response to a BulkMute request. Contains the LRO - 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]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): - request = securitycenter_service.BulkMuteFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.bulk_mute_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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - securitycenter_service.BulkMuteFindingsResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - async def create_big_query_export(self, - request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, - *, - parent: Optional[str] = None, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - big_query_export_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Creates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_create_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = await client.create_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest, dict]]): - The request object. Request message for creating a - BigQuery export. - parent (:class:`str`): - Required. The name of the parent resource of the new - BigQuery export. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export (:class:`google.cloud.securitycenter_v2.types.BigQueryExport`): - Required. The BigQuery export being - created. - - This corresponds to the ``big_query_export`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``big_query_export_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.cloud.securitycenter_v2.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): - request = securitycenter_service.CreateBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if big_query_export is not None: - request.big_query_export = big_query_export - if big_query_export_id is not None: - request.big_query_export_id = big_query_export_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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - finding_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding in a location. The corresponding - source must exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_create_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.CreateFindingRequest, dict]]): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. The - following list shows some examples of the format: + - ``organizations/[organization_id]/sources/[source_id]`` - + - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`google.cloud.securitycenter_v2.types.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_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.cloud.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding, finding_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, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding is not None: - request.finding = finding - if finding_id is not None: - request.finding_id = finding_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_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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 create_mute_config(self, - request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - mute_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Creates a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_create_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = await client.create_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.CreateMuteConfigRequest, dict]]): - The request object. Request message for creating a mute - config. - parent (:class:`str`): - Required. Resource name of the new mute configs's - parent. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config (:class:`google.cloud.securitycenter_v2.types.MuteConfig`): - Required. The mute config being - created. - - This corresponds to the ``mute_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``mute_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.cloud.securitycenter_v2.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): - request = securitycenter_service.CreateMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if mute_config is not None: - request.mute_config = mute_config - if mute_config_id is not None: - request.mute_config_id = mute_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_mute_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 create_notification_config(self, - request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_create_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.create_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest, dict]]): - The request object. Request message for creating a - notification config. - parent (:class:`str`): - Required. Resource name of the new notification config's - parent. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (:class:`google.cloud.securitycenter_v2.types.NotificationConfig`): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (:class:`str`): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters and contain - alphanumeric characters, underscores, or - hyphens only. - - This corresponds to the ``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.cloud.securitycenter_v2.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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_config, 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, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if notification_config is not None: - request.notification_config = notification_config - if config_id is not None: - request.config_id = 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_notification_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 create_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v2 - - async def sample_create_source(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.CreateSourceRequest, dict]]): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be ``organizations/[organization_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`google.cloud.securitycenter_v2.types.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v2.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = 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_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 delete_big_query_export(self, - request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - await client.delete_big_query_export(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest, dict]]): - The request object. Request message for deleting a - BigQuery export. - name (:class:`str`): - Required. The name of the BigQuery export to delete. The - following list shows some examples of the format: - - - - - ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` - - - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` - - ``projects/{project}/locations/{location}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): - request = securitycenter_service.DeleteBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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 delete_mute_config(self, - request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. If no location is - specified, default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_delete_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_mute_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest, dict]]): - The request object. Request message for deleting a mute - config. If no location is specified, - default is global. - name (:class:`str`): - Required. Name of the mute config to delete. The - following list shows some examples of the format: - - - ``organizations/{organization}/muteConfigs/{config_id}`` - - - - ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` - - - ``folders/{folder}/muteConfigs/{config_id}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` - - ``projects/{project}/muteConfigs/{config_id}`` - - ``projects/{project}/locations/{location}/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): - request = securitycenter_service.DeleteMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_mute_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 delete_notification_config(self, - request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_delete_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest, dict]]): - The request object. Request message for deleting a - notification config. - name (:class:`str`): - Required. Name of the notification config to delete. The - following list shows some examples of the format: - - - - - ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` - + - ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 delete_resource_value_config(self, - request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_resource_value_config(request=request) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest, dict]]): - The request object. Request message to delete resource - value config - name (:class:`str`): - Required. Name of the - ResourceValueConfig 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. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): - request = securitycenter_service.DeleteResourceValueConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_resource_value_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_big_query_export(self, - request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Gets a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_get_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = await client.get_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetBigQueryExportRequest, dict]]): - The request object. Request message for retrieving a - BigQuery export. - name (:class:`str`): - Required. Name of the BigQuery export to retrieve. The - following list shows some examples of the format: - - - - - ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` - - - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` - - ``projects/{project}locations/{location}//bigQueryExports/{export_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.cloud.securitycenter_v2.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): - request = securitycenter_service.GetBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_simulation(self, - request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> simulation.Simulation: - r"""Get the simulation by name or the latest simulation - for the given organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_get_simulation(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_simulation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetSimulationRequest, dict]]): - The request object. Request message for getting - simulation. Simulation name can include - "latest" to retrieve the latest - simulation For example, - "organizations/123/simulations/latest". - name (:class:`str`): - Required. The organization name or simulation name of - this simulation - - Valid format: - ``organizations/{organization}/simulations/latest`` - ``organizations/{organization}/simulations/{simulation}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.Simulation: - Attack path simulation - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSimulationRequest): - request = securitycenter_service.GetSimulationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_simulation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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_valued_resource(self, - request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> valued_resource.ValuedResource: - r"""Get the valued resource by 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 import securitycenter_v2 - - async def sample_get_valued_resource(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_valued_resource(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetValuedResourceRequest, dict]]): - The request object. Request message for getting a valued - resource. - name (:class:`str`): - Required. The name of this valued resource - - Valid format: - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v2.types.ValuedResource: - A resource that is determined to have - value to a user's system - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetValuedResourceRequest): - request = securitycenter_service.GetValuedResourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_valued_resource] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v2 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 get_mute_config(self, - request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> mute_config.MuteConfig: - r"""Gets a mute config. If no location is specified, - default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_get_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetMuteConfigRequest, dict]]): - The request object. Request message for retrieving a mute - config. If no location is specified, - default is global. - name (:class:`str`): - Required. Name of the mute config to retrieve. The - following list shows some examples of the format: - - - ``organizations/{organization}/muteConfigs/{config_id}`` - - - - ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` - - - ``folders/{folder}/muteConfigs/{config_id}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` - - ``projects/{project}/muteConfigs/{config_id}`` - - ``projects/{project}/locations/{location}/muteConfigs/{config_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.cloud.securitycenter_v2.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetMuteConfigRequest): - request = securitycenter_service.GetMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_mute_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 get_notification_config(self, - request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_get_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetNotificationConfigRequest, dict]]): - The request object. Request message for getting a - notification config. - name (:class:`str`): - Required. Name of the notification config to get. The - following list shows some examples of the format: - - - - - ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_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.cloud.securitycenter_v2.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 get_resource_value_config(self, - request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resource_value_config.ResourceValueConfig: - r"""Gets a ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest, dict]]): - The request object. Request message to get resource value - config - name (:class:`str`): - Required. Name of the resource value config to retrieve. - Its format is - organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v2.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): - request = securitycenter_service.GetResourceValueConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_resource_value_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 get_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v2 - - async def sample_get_source(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GetSourceRequest, dict]]): - The request object. Request message for getting a source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v2.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = 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_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 group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties in a location. If no location is - specified, findings are assumed to be in global - - To group across all sources provide a ``-`` as the source id. - The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - - ``/v2/folders/{folder_id}/sources/-/findings`` - - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` - - ``/v2/projects/{project_id}/sources/-/findings`` - - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_group_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.GroupFindingsRequest, dict]]): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. If no location - is specified, finding is assumed to be in global. The - following list shows some examples: - - - ``organizations/[organization_id]/sources/[source_id]`` - - - - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - - ``folders/[folder_id]/sources/[source_id]`` - - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` - - ``projects/[project_id]/sources/[source_id]`` - - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` - - To groupBy across all sources provide a source_id of - ``-``. The following list shows some examples: - - - ``organizations/{organization_id}/sources/-`` - - ``organizations/{organization_id}/sources/-/locations/[location_id]`` - - ``folders/{folder_id}/sources/-`` - - ``folders/{folder_id}/sources/-/locations/[location_id]`` - - ``projects/{project_id}/sources/-`` - - ``projects/{project_id}/sources/-/locations/[location_id]`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping. The string value should follow SQL - syntax: comma separated list of fields. For example: - "parent,resource_name". - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.group_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.GroupFindingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_attack_paths(self, - request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsAsyncPager: - r"""Lists the attack paths for a set of simulation - results or valued resources and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_attack_paths(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListAttackPathsRequest, dict]]): - The request object. Request message for listing the - attack paths for a given simulation or - valued resource. - parent (:class:`str`): - Required. Name of parent to list attack paths. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - - 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.securitycenter_v2.services.security_center.pagers.ListAttackPathsAsyncPager: - Response message for listing the - attack paths for a given simulation or - valued resource. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): - request = securitycenter_service.ListAttackPathsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_attack_paths] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListAttackPathsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_big_query_exports(self, - request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsAsyncPager: - r"""Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are 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 securitycenter_v2 - - async def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest, dict]]): - The request object. Request message for listing BigQuery - exports at a given scope e.g. - organization, folder or project. - parent (:class:`str`): - Required. The parent, which owns the collection of - BigQuery exports. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - 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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsAsyncPager: - Response message for listing BigQuery - exports. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): - request = securitycenter_service.ListBigQueryExportsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_big_query_exports] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListBigQueryExportsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings(self, - request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsAsyncPager: - r"""Lists an organization or source's findings. - - To list across all sources for a given location provide a ``-`` - as the source id. If no location is specified, finding are - assumed to be in global. The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListFindingsRequest( - parent="parent_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.securitycenter_v2.types.ListFindingsRequest, dict]]): - The request object. Request message for listing findings. - parent (:class:`str`): - Required. Name of the source the findings belong to. If - no location is specified, the default is global. The - following list shows some examples: - - - ``organizations/[organization_id]/sources/[source_id]`` - - - - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - - ``folders/[folder_id]/sources/[source_id]`` - - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` - - ``projects/[project_id]/sources/[source_id]`` - - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` - - To list across all sources provide a source_id of ``-``. - The following list shows some examples: - - - ``organizations/{organization_id}/sources/-`` - - ``organizations/{organization_id}/sources/-/locations/{location_id}`` - - ``folders/{folder_id}/sources/-`` - - ``folders/{folder_id}/sources/-locations/{location_id}`` - - ``projects/{projects_id}/sources/-`` - - ``projects/{projects_id}/sources/-/locations/{location_id}`` - - 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.securitycenter_v2.services.security_center.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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_mute_configs(self, - request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsAsyncPager: - r"""Lists mute configs. If no location is specified, - default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_mute_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListMuteConfigsRequest, dict]]): - The request object. Request message for listing mute - configs at a given scope e.g. - organization, folder or project. If no - location is specified, default is - global. - parent (:class:`str`): - Required. The parent, which owns the collection of mute - configs. Its format is - ``organizations/[organization_id]", "folders/[folder_id]``, - ``projects/[project_id]``, - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, - ``projects/[project_id]/locations/[location_id]``. - - 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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsAsyncPager: - Response message for listing mute - configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): - request = securitycenter_service.ListMuteConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_mute_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.ListMuteConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_notification_configs(self, - request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsAsyncPager: - r"""Lists notification configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_notification_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest, dict]]): - The request object. Request message for listing - notification configs. - parent (:class:`str`): - Required. The name of the parent in which to list the - notification configurations. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". - - 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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsAsyncPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListNotificationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_resource_value_configs(self, - request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsAsyncPager: - r"""Lists all ResourceValueConfigs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest, dict]]): - The request object. Request message to list resource - value configs of a parent - parent (:class:`str`): - Required. The parent, which owns the collection of - resource value configs. Its format is - ``organizations/[organization_id]`` - - 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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsAsyncPager: - Response message to list resource - value configs - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): - request = securitycenter_service.ListResourceValueConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_resource_value_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.ListResourceValueConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_sources(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListSourcesRequest, dict]]): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - 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.securitycenter_v2.services.security_center.pagers.ListSourcesAsyncPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_valued_resources(self, - request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesAsyncPager: - r"""Lists the valued resources for a set of simulation - results and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_list_valued_resources(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.ListValuedResourcesRequest, dict]]): - The request object. Request message for listing the - valued resources for a given simulation. - parent (:class:`str`): - Required. Name of parent to list exposed resources. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - - 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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesAsyncPager: - Response message for listing the - valued resources for a given simulation. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): - request = securitycenter_service.ListValuedResourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_valued_resources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", 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.ListValuedResourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. If no location is - specified, finding is assumed to be in global - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_set_finding_state(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.SetFindingStateRequest, dict]]): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The `relative resource - name `__ - of the finding. If no location is specified, finding is - assumed to be in global. The following list shows some - examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`google.cloud.securitycenter_v2.types.Finding.State`): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.set_finding_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 set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v2 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 set_mute(self, - request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, - *, - name: Optional[str] = None, - mute: Optional[finding.Finding.Mute] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the mute state of a finding. If no location - is specified, finding is assumed to be in global - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_set_mute(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = await client.set_mute(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.SetMuteRequest, dict]]): - The request object. Request message for updating a - finding's mute status. - name (:class:`str`): - Required. The `relative resource - name `__ - of the finding. If no location is specified, finding is - assumed to be in global. The following list shows some - examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute (:class:`google.cloud.securitycenter_v2.types.Finding.Mute`): - Required. The desired state of the - Mute. - - This corresponds to the ``mute`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, mute]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetMuteRequest): - request = securitycenter_service.SetMuteRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if mute is not None: - request.mute = mute - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.set_mute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v2 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._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 update_big_query_export(self, - request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, - *, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - update_mask: 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]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Updates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateBigQueryExportRequest( - ) - - # Make the request - response = await client.update_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest, dict]]): - The request object. Request message for updating a - BigQuery export. - big_query_export (:class:`google.cloud.securitycenter_v2.types.BigQueryExport`): - Required. The BigQuery export being - updated. - - This corresponds to the ``big_query_export`` 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. - If empty all mutable fields 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.cloud.securitycenter_v2.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): - request = securitycenter_service.UpdateBigQueryExportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if big_query_export is not None: - request.big_query_export = big_query_export - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("big_query_export.name", request.big_query_export.name), - )), - ) - - # Validate the universe domain. - self._client._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_external_system(self, - request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, - *, - external_system: Optional[gcs_external_system.ExternalSystem] = None, - update_mask: 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]] = (), - ) -> gcs_external_system.ExternalSystem: - r"""Updates external system. This is for a given finding. - If no location is specified, finding is assumed to be in - global - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_external_system(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateExternalSystemRequest( - ) - - # Make the request - response = await client.update_external_system(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest, dict]]): - The request object. Request message for updating a - ExternalSystem resource. - external_system (:class:`google.cloud.securitycenter_v2.types.ExternalSystem`): - Required. The external system - resource to update. - - This corresponds to the ``external_system`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the external system resource. - If empty all mutable fields 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.cloud.securitycenter_v2.types.ExternalSystem: - Representation of third party - SIEM/SOAR fields within SCC. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): - request = securitycenter_service.UpdateExternalSystemRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if external_system is not None: - request.external_system = external_system - 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_external_system] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("external_system.name", request.external_system.name), - )), - ) - - # Validate the universe domain. - self._client._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_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - update_mask: 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]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. If no location is - specified, finding is assumed to be in global. The - corresponding source must exist for a finding creation - to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateFindingRequest, dict]]): - The request object. Request message for updating or - creating a finding. - finding (:class:`google.cloud.securitycenter_v2.types.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a - finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing - source_properties. Individual source_properties can be - added/updated by using "source_properties." in the field - mask. - - 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.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - 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_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe domain. - self._client._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_mute_config(self, - request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, - *, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - update_mask: 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]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Updates a mute config. If no location is specified, - default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = await client.update_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest, dict]]): - The request object. Request message for updating a mute - config. - mute_config (:class:`google.cloud.securitycenter_v2.types.MuteConfig`): - Required. The mute config being - updated. - - This corresponds to the ``mute_config`` 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. - If empty all mutable fields 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.cloud.securitycenter_v2.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): - request = securitycenter_service.UpdateMuteConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if mute_config is not None: - request.mute_config = mute_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_mute_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("mute_config.name", request.mute_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 update_notification_config(self, - request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, - *, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - update_mask: 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]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateNotificationConfigRequest( - ) - - # Make the request - response = await client.update_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest, dict]]): - The request object. Request message for updating a - notification config. - notification_config (:class:`google.cloud.securitycenter_v2.types.NotificationConfig`): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the notification config. - If empty all mutable fields 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.cloud.securitycenter_v2.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_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 update_resource_value_config(self, - request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, - *, - resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, - update_mask: 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]] = (), - ) -> gcs_resource_value_config.ResourceValueConfig: - r"""Updates an existing ResourceValueConfigs with new - rules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateResourceValueConfigRequest( - ) - - # Make the request - response = await client.update_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest, dict]]): - The request object. Request message to update resource - value config - resource_value_config (:class:`google.cloud.securitycenter_v2.types.ResourceValueConfig`): - Required. The resource value config - being updated. - - This corresponds to the ``resource_value_config`` 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. If empty all mutable - fields will be updated. - - To update nested fields, include the top level field in - the mask For example, to update - gcp_metadata.resource_type, include the "gcp_metadata" - field mask - - 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.securitycenter_v2.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): - request = securitycenter_service.UpdateResourceValueConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if resource_value_config is not None: - request.resource_value_config = resource_value_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_resource_value_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource_value_config.name", request.resource_value_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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - update_mask: 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]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. For Finding Security marks, - if no location is specified, finding is assumed to be in - global. Assets Security Marks can only be accessed - through global endpoint. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - async def sample_update_security_marks(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest, dict]]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`google.cloud.securitycenter_v2.types.SecurityMarks`): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If - empty or set to "marks", all marks will be replaced. - Individual marks can be updated using - "marks.". - - 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.securitycenter_v2.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - 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_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe domain. - self._client._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_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - update_mask: 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]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v2 - - async def sample_update_source(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateSourceRequest, dict]]): - The request object. Request message for updating a - source. - source (:class:`google.cloud.securitycenter_v2.types.Source`): - Required. The source resource to - update. - - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the source resource. - If empty all mutable fields 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.cloud.securitycenter_v2.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = 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_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self) -> "SecurityCenterAsyncClient": - 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__ = ( - "SecurityCenterAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py deleted file mode 100644 index 550305f1c892..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/client.py +++ /dev/null @@ -1,5948 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.securitycenter_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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.securitycenter_v2.services.security_center import pagers -from google.cloud.securitycenter_v2.types import access -from google.cloud.securitycenter_v2.types import application -from google.cloud.securitycenter_v2.types import attack_exposure -from google.cloud.securitycenter_v2.types import attack_path -from google.cloud.securitycenter_v2.types import backup_disaster_recovery -from google.cloud.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import cloud_armor -from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile -from google.cloud.securitycenter_v2.types import cloud_dlp_inspection -from google.cloud.securitycenter_v2.types import compliance -from google.cloud.securitycenter_v2.types import connection -from google.cloud.securitycenter_v2.types import container -from google.cloud.securitycenter_v2.types import database -from google.cloud.securitycenter_v2.types import exfiltration -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import file -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import group_membership -from google.cloud.securitycenter_v2.types import iam_binding -from google.cloud.securitycenter_v2.types import indicator -from google.cloud.securitycenter_v2.types import kernel_rootkit -from google.cloud.securitycenter_v2.types import kubernetes -from google.cloud.securitycenter_v2.types import load_balancer -from google.cloud.securitycenter_v2.types import log_entry -from google.cloud.securitycenter_v2.types import mitre_attack -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notebook -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import org_policy -from google.cloud.securitycenter_v2.types import process -from google.cloud.securitycenter_v2.types import resource -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import security_posture -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import toxic_combination -from google.cloud.securitycenter_v2.types import valued_resource -from google.cloud.securitycenter_v2.types import vulnerability -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 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 SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .transports.rest import SecurityCenterRestTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - _transport_registry["rest"] = SecurityCenterRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SecurityCenterTransport]: - """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V2 APIs for Security Center 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 = "securitycenter.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{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: - SecurityCenterClient: 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: - SecurityCenterClient: 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) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def attack_path_path(organization: str,simulation: str,valued_resource: str,attack_path: str,) -> str: - """Returns a fully-qualified attack_path string.""" - return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) - - @staticmethod - def parse_attack_path_path(path: str) -> Dict[str,str]: - """Parses a attack_path path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?P.+?)/attackPaths/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def big_query_export_path(organization: str,location: str,export: str,) -> str: - """Returns a fully-qualified big_query_export string.""" - return "organizations/{organization}/locations/{location}/bigQueryExports/{export}".format(organization=organization, location=location, export=export, ) - - @staticmethod - def parse_big_query_export_path(path: str) -> Dict[str,str]: - """Parses a big_query_export path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/locations/(?P.+?)/bigQueryExports/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def dlp_job_path(project: str,dlp_job: str,) -> str: - """Returns a fully-qualified dlp_job string.""" - return "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) - - @staticmethod - def parse_dlp_job_path(path: str) -> Dict[str,str]: - """Parses a dlp_job path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/dlpJobs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def external_system_path(organization: str,source: str,finding: str,externalsystem: str,) -> str: - """Returns a fully-qualified external_system string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) - - @staticmethod - def parse_external_system_path(path: str) -> Dict[str,str]: - """Parses a external_system path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)/externalSystems/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def finding_path(organization: str,source: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def mute_config_path(organization: str,mute_config: str,) -> str: - """Returns a fully-qualified mute_config string.""" - return "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) - - @staticmethod - def parse_mute_config_path(path: str) -> Dict[str,str]: - """Parses a mute_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/muteConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def notification_config_path(organization: str,location: str,notification_config: str,) -> str: - """Returns a fully-qualified notification_config string.""" - return "organizations/{organization}/locations/{location}/notificationConfigs/{notification_config}".format(organization=organization, location=location, notification_config=notification_config, ) - - @staticmethod - def parse_notification_config_path(path: str) -> Dict[str,str]: - """Parses a notification_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/locations/(?P.+?)/notificationConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def policy_path(organization: str,constraint_name: str,) -> str: - """Returns a fully-qualified policy string.""" - return "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) - - @staticmethod - def parse_policy_path(path: str) -> Dict[str,str]: - """Parses a policy path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/policies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def resource_value_config_path(organization: str,resource_value_config: str,) -> str: - """Returns a fully-qualified resource_value_config string.""" - return "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) - - @staticmethod - def parse_resource_value_config_path(path: str) -> Dict[str,str]: - """Parses a resource_value_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/resourceValueConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str,str]: - """Parses a security_marks path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) - return m.groupdict() if m else {} - - @staticmethod - def simulation_path(organization: str,simulation: str,) -> str: - """Returns a fully-qualified simulation string.""" - return "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) - - @staticmethod - def parse_simulation_path(path: str) -> Dict[str,str]: - """Parses a simulation path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str,source: str,) -> str: - """Returns a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str,str]: - """Parses a source path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def table_data_profile_path(project: str,table_profile: str,) -> str: - """Returns a fully-qualified table_data_profile string.""" - return "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) - - @staticmethod - def parse_table_data_profile_path(path: str) -> Dict[str,str]: - """Parses a table_data_profile path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/tableProfiles/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def topic_path(project: str,topic: str,) -> str: - """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - - @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: - """Parses a topic path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def valued_resource_path(organization: str,simulation: str,valued_resource: str,) -> str: - """Returns a fully-qualified valued_resource string.""" - return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) - - @staticmethod - def parse_valued_resource_path(path: str) -> Dict[str,str]: - """Parses a valued_resource path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?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 = SecurityCenterClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SecurityCenterClient._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 = SecurityCenterClient._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 - SecurityCenterClient._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, SecurityCenterTransport, Callable[..., SecurityCenterTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,SecurityCenterTransport,Callable[..., SecurityCenterTransport]]]): - 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 SecurityCenterTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - 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 = SecurityCenterClient._read_environment_variables() - self._client_cert_source = SecurityCenterClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = SecurityCenterClient._get_universe_domain(universe_domain_opt, 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, SecurityCenterTransport) - if transport_provided: - # transport is a SecurityCenterTransport 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(SecurityCenterTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - SecurityCenterClient._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[SecurityCenterTransport], Callable[..., SecurityCenterTransport]] = ( - type(self).get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., SecurityCenterTransport], 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 batch_create_resource_value_configs(self, - request: Optional[Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict]] = None, - *, - parent: Optional[str] = None, - requests: Optional[MutableSequence[securitycenter_service.CreateResourceValueConfigRequest]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - r"""Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - requests = securitycenter_v2.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - - request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest, dict]): - The request object. Request message to create multiple - resource value configs - parent (str): - Required. Resource name of the new - ResourceValueConfig's parent. The parent - field in the - CreateResourceValueConfigRequest - messages must either be empty or match - this field. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - requests (MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]): - Required. The resource value configs - to be created. - - This corresponds to the ``requests`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse: - Response message for - BatchCreateResourceValueConfigs - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, requests]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BatchCreateResourceValueConfigsRequest): - request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if requests is not None: - request.requests = requests - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_resource_value_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, - ) - - # Done; return the response. - return response - - def bulk_mute_findings(self, - request: Optional[Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), - ) -> operation.Operation: - r"""Kicks off an LRO to bulk mute findings for a parent - based on a filter. If no location is specified, findings - are muted in global. The parent can be either an - organization, folder, or project. The findings matched - by the filter will be muted after the LRO is done. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest, dict]): - The request object. Request message for bulk findings - update. - Note: - - 1. If multiple bulk update requests - match the same resource, the order - in which they get executed is not - defined. - 2. Once a bulk operation is started, - there is no way to stop it. - parent (str): - Required. The parent, at which bulk action needs to be - applied. If no location is specified, findings are - updated in global. The following list shows some - examples: - - - ``organizations/[organization_id]`` - - ``organizations/[organization_id]/locations/[location_id]`` - - ``folders/[folder_id]`` - - ``folders/[folder_id]/locations/[location_id]`` - - ``projects/[project_id]`` - - ``projects/[project_id]/locations/[location_id]`` - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v2.types.BulkMuteFindingsResponse` - The response to a BulkMute request. Contains the LRO - 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): - request = securitycenter_service.BulkMuteFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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.bulk_mute_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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - securitycenter_service.BulkMuteFindingsResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - def create_big_query_export(self, - request: Optional[Union[securitycenter_service.CreateBigQueryExportRequest, dict]] = None, - *, - parent: Optional[str] = None, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - big_query_export_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Creates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_create_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = client.create_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest, dict]): - The request object. Request message for creating a - BigQuery export. - parent (str): - Required. The name of the parent resource of the new - BigQuery export. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): - Required. The BigQuery export being - created. - - This corresponds to the ``big_query_export`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - big_query_export_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``big_query_export_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.cloud.securitycenter_v2.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, big_query_export, big_query_export_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, securitycenter_service.CreateBigQueryExportRequest): - request = securitycenter_service.CreateBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if big_query_export is not None: - request.big_query_export = big_query_export - if big_query_export_id is not None: - request.big_query_export_id = big_query_export_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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 create_finding(self, - request: Optional[Union[securitycenter_service.CreateFindingRequest, dict]] = None, - *, - parent: Optional[str] = None, - finding: Optional[gcs_finding.Finding] = None, - finding_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding in a location. The corresponding - source must exist for finding creation to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_create_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.CreateFindingRequest, dict]): - The request object. Request message for creating a - finding. - parent (str): - Required. Resource name of the new finding's parent. The - following list shows some examples of the format: + - ``organizations/[organization_id]/sources/[source_id]`` - + - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (google.cloud.securitycenter_v2.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_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.cloud.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding, finding_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, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding is not None: - request.finding = finding - if finding_id is not None: - request.finding_id = finding_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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 create_mute_config(self, - request: Optional[Union[securitycenter_service.CreateMuteConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - mute_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Creates a mute config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_create_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = client.create_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.CreateMuteConfigRequest, dict]): - The request object. Request message for creating a mute - config. - parent (str): - Required. Resource name of the new mute configs's - parent. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config (google.cloud.securitycenter_v2.types.MuteConfig): - Required. The mute config being - created. - - This corresponds to the ``mute_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute_config_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must consist of only lowercase - letters, numbers, and hyphens, must - start with a letter, must end with - either a letter or a number, and must be - 63 characters or less. - - This corresponds to the ``mute_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.cloud.securitycenter_v2.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, mute_config, mute_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, securitycenter_service.CreateMuteConfigRequest): - request = securitycenter_service.CreateMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if mute_config is not None: - request.mute_config = mute_config - if mute_config_id is not None: - request.mute_config_id = mute_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_mute_config] - - header_params = {} - - routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - 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_notification_config(self, - request: Optional[Union[securitycenter_service.CreateNotificationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_create_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = client.create_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest, dict]): - The request object. Request message for creating a - notification config. - parent (str): - Required. Resource name of the new notification config's - parent. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (str): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters and contain - alphanumeric characters, underscores, or - hyphens only. - - This corresponds to the ``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.cloud.securitycenter_v2.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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_config, 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, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if notification_config is not None: - request.notification_config = notification_config - if config_id is not None: - request.config_id = config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_notification_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 create_source(self, - request: Optional[Union[securitycenter_service.CreateSourceRequest, dict]] = None, - *, - parent: Optional[str] = None, - source: Optional[gcs_source.Source] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a 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.cloud import securitycenter_v2 - - def sample_create_source(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.CreateSourceRequest, dict]): - The request object. Request message for creating a - source. - parent (str): - Required. Resource name of the new source's parent. Its - format should be ``organizations/[organization_id]``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (google.cloud.securitycenter_v2.types.Source): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``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.cloud.securitycenter_v2.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_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 delete_big_query_export(self, - request: Optional[Union[securitycenter_service.DeleteBigQueryExportRequest, dict]] = 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 BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - client.delete_big_query_export(request=request) - - Args: - request (Union[google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest, dict]): - The request object. Request message for deleting a - BigQuery export. - name (str): - Required. The name of the BigQuery export to delete. The - following list shows some examples of the format: - - - - - ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` - - - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` - - ``projects/{project}/locations/{location}/bigQueryExports/{export_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, securitycenter_service.DeleteBigQueryExportRequest): - request = securitycenter_service.DeleteBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - 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 delete_mute_config(self, - request: Optional[Union[securitycenter_service.DeleteMuteConfigRequest, dict]] = 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 mute config. If no location is - specified, default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_delete_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_mute_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest, dict]): - The request object. Request message for deleting a mute - config. If no location is specified, - default is global. - name (str): - Required. Name of the mute config to delete. The - following list shows some examples of the format: - - - ``organizations/{organization}/muteConfigs/{config_id}`` - - - - ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` - - - ``folders/{folder}/muteConfigs/{config_id}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` - - ``projects/{project}/muteConfigs/{config_id}`` - - ``projects/{project}/locations/{location}/muteConfigs/{config_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, securitycenter_service.DeleteMuteConfigRequest): - request = securitycenter_service.DeleteMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_mute_config] - - header_params = {} - - routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - 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 delete_notification_config(self, - request: Optional[Union[securitycenter_service.DeleteNotificationConfigRequest, dict]] = 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 config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_delete_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest, dict]): - The request object. Request message for deleting a - notification config. - name (str): - Required. Name of the notification config to delete. The - following list shows some examples of the format: - - - - - ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` - + - ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_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, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 delete_resource_value_config(self, - request: Optional[Union[securitycenter_service.DeleteResourceValueConfigRequest, dict]] = 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 ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_resource_value_config(request=request) - - Args: - request (Union[google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest, dict]): - The request object. Request message to delete resource - value config - name (str): - Required. Name of the - ResourceValueConfig 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. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.DeleteResourceValueConfigRequest): - request = securitycenter_service.DeleteResourceValueConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_resource_value_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_big_query_export(self, - request: Optional[Union[securitycenter_service.GetBigQueryExportRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Gets a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_get_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = client.get_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetBigQueryExportRequest, dict]): - The request object. Request message for retrieving a - BigQuery export. - name (str): - Required. Name of the BigQuery export to retrieve. The - following list shows some examples of the format: - - - - - ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` - - - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` - - ``projects/{project}locations/{location}//bigQueryExports/{export_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.cloud.securitycenter_v2.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): - request = securitycenter_service.GetBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_simulation(self, - request: Optional[Union[securitycenter_service.GetSimulationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> simulation.Simulation: - r"""Get the simulation by name or the latest simulation - for the given organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_get_simulation(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = client.get_simulation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetSimulationRequest, dict]): - The request object. Request message for getting - simulation. Simulation name can include - "latest" to retrieve the latest - simulation For example, - "organizations/123/simulations/latest". - name (str): - Required. The organization name or simulation name of - this simulation - - Valid format: - ``organizations/{organization}/simulations/latest`` - ``organizations/{organization}/simulations/{simulation}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.Simulation: - Attack path simulation - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSimulationRequest): - request = securitycenter_service.GetSimulationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_simulation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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_valued_resource(self, - request: Optional[Union[securitycenter_service.GetValuedResourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> valued_resource.ValuedResource: - r"""Get the valued resource by 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 import securitycenter_v2 - - def sample_get_valued_resource(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_valued_resource(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetValuedResourceRequest, dict]): - The request object. Request message for getting a valued - resource. - name (str): - Required. The name of this valued resource - - Valid format: - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_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.securitycenter_v2.types.ValuedResource: - A resource that is determined to have - value to a user's system - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetValuedResourceRequest): - request = securitycenter_service.GetValuedResourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_valued_resource] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v2 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 get_mute_config(self, - request: Optional[Union[securitycenter_service.GetMuteConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> mute_config.MuteConfig: - r"""Gets a mute config. If no location is specified, - default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_get_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetMuteConfigRequest, dict]): - The request object. Request message for retrieving a mute - config. If no location is specified, - default is global. - name (str): - Required. Name of the mute config to retrieve. The - following list shows some examples of the format: - - - ``organizations/{organization}/muteConfigs/{config_id}`` - - - - ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` - - - ``folders/{folder}/muteConfigs/{config_id}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` - - ``projects/{project}/muteConfigs/{config_id}`` - - ``projects/{project}/locations/{location}/muteConfigs/{config_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.cloud.securitycenter_v2.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetMuteConfigRequest): - request = securitycenter_service.GetMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_mute_config] - - header_params = {} - - routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - 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_notification_config(self, - request: Optional[Union[securitycenter_service.GetNotificationConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_get_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetNotificationConfigRequest, dict]): - The request object. Request message for getting a - notification config. - name (str): - Required. Name of the notification config to get. The - following list shows some examples of the format: - - - - - ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_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.cloud.securitycenter_v2.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 get_resource_value_config(self, - request: Optional[Union[securitycenter_service.GetResourceValueConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resource_value_config.ResourceValueConfig: - r"""Gets a ResourceValueConfig. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest, dict]): - The request object. Request message to get resource value - config - name (str): - Required. Name of the resource value config to retrieve. - Its format is - organizations/{organization}/resourceValueConfigs/{config_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.cloud.securitycenter_v2.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetResourceValueConfigRequest): - request = securitycenter_service.GetResourceValueConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_resource_value_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 get_source(self, - request: Optional[Union[securitycenter_service.GetSourceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a 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.cloud import securitycenter_v2 - - def sample_get_source(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GetSourceRequest, dict]): - The request object. Request message for getting a source. - name (str): - Required. Relative resource name of the source. Its - format is - ``organizations/[organization_id]/source/[source_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.cloud.securitycenter_v2.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - 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_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 group_findings(self, - request: Optional[Union[securitycenter_service.GroupFindingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - group_by: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties in a location. If no location is - specified, findings are assumed to be in global - - To group across all sources provide a ``-`` as the source id. - The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - - ``/v2/folders/{folder_id}/sources/-/findings`` - - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` - - ``/v2/projects/{project_id}/sources/-/findings`` - - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_group_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.GroupFindingsRequest, dict]): - The request object. Request message for grouping by - findings. - parent (str): - Required. Name of the source to groupBy. If no location - is specified, finding is assumed to be in global. The - following list shows some examples: - - - ``organizations/[organization_id]/sources/[source_id]`` - - - - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - - ``folders/[folder_id]/sources/[source_id]`` - - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` - - ``projects/[project_id]/sources/[source_id]`` - - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` - - To groupBy across all sources provide a source_id of - ``-``. The following list shows some examples: - - - ``organizations/{organization_id}/sources/-`` - - ``organizations/{organization_id}/sources/-/locations/[location_id]`` - - ``folders/{folder_id}/sources/-`` - - ``folders/{folder_id}/sources/-/locations/[location_id]`` - - ``projects/{project_id}/sources/-`` - - ``projects/{project_id}/sources/-/locations/[location_id]`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (str): - Required. Expression that defines what assets fields to - use for grouping. The string value should follow SQL - syntax: comma separated list of fields. For example: - "parent,resource_name". - - This corresponds to the ``group_by`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_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.GroupFindingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_attack_paths(self, - request: Optional[Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsPager: - r"""Lists the attack paths for a set of simulation - results or valued resources and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_attack_paths(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListAttackPathsRequest, dict]): - The request object. Request message for listing the - attack paths for a given simulation or - valued resource. - parent (str): - Required. Name of parent to list attack paths. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - - 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.securitycenter_v2.services.security_center.pagers.ListAttackPathsPager: - Response message for listing the - attack paths for a given simulation or - valued resource. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListAttackPathsRequest): - request = securitycenter_service.ListAttackPathsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_attack_paths] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListAttackPathsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_big_query_exports(self, - request: Optional[Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsPager: - r"""Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are 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 securitycenter_v2 - - def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest, dict]): - The request object. Request message for listing BigQuery - exports at a given scope e.g. - organization, folder or project. - parent (str): - Required. The parent, which owns the collection of - BigQuery exports. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - - 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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsPager: - Response message for listing BigQuery - exports. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListBigQueryExportsRequest): - request = securitycenter_service.ListBigQueryExportsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_big_query_exports] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListBigQueryExportsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings(self, - request: Optional[Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsPager: - r"""Lists an organization or source's findings. - - To list across all sources for a given location provide a ``-`` - as the source id. If no location is specified, finding are - assumed to be in global. The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListFindingsRequest( - parent="parent_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.securitycenter_v2.types.ListFindingsRequest, dict]): - The request object. Request message for listing findings. - parent (str): - Required. Name of the source the findings belong to. If - no location is specified, the default is global. The - following list shows some examples: - - - ``organizations/[organization_id]/sources/[source_id]`` - - - - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - - ``folders/[folder_id]/sources/[source_id]`` - - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` - - ``projects/[project_id]/sources/[source_id]`` - - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` - - To list across all sources provide a source_id of ``-``. - The following list shows some examples: - - - ``organizations/{organization_id}/sources/-`` - - ``organizations/{organization_id}/sources/-/locations/{location_id}`` - - ``folders/{folder_id}/sources/-`` - - ``folders/{folder_id}/sources/-locations/{location_id}`` - - ``projects/{projects_id}/sources/-`` - - ``projects/{projects_id}/sources/-/locations/{location_id}`` - - 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.securitycenter_v2.services.security_center.pagers.ListFindingsPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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_mute_configs(self, - request: Optional[Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsPager: - r"""Lists mute configs. If no location is specified, - default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_mute_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListMuteConfigsRequest, dict]): - The request object. Request message for listing mute - configs at a given scope e.g. - organization, folder or project. If no - location is specified, default is - global. - parent (str): - Required. The parent, which owns the collection of mute - configs. Its format is - ``organizations/[organization_id]", "folders/[folder_id]``, - ``projects/[project_id]``, - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, - ``projects/[project_id]/locations/[location_id]``. - - 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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsPager: - Response message for listing mute - configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListMuteConfigsRequest): - request = securitycenter_service.ListMuteConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_mute_configs] - - header_params = {} - - routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - 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.ListMuteConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_notification_configs(self, - request: Optional[Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsPager: - r"""Lists notification configs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_notification_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest, dict]): - The request object. Request message for listing - notification configs. - parent (str): - Required. The name of the parent in which to list the - notification configurations. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". - - 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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListNotificationConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_resource_value_configs(self, - request: Optional[Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsPager: - r"""Lists all ResourceValueConfigs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest, dict]): - The request object. Request message to list resource - value configs of a parent - parent (str): - Required. The parent, which owns the collection of - resource value configs. Its format is - ``organizations/[organization_id]`` - - 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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsPager: - Response message to list resource - value configs - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListResourceValueConfigsRequest): - request = securitycenter_service.ListResourceValueConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_resource_value_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.ListResourceValueConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_sources(self, - request: Optional[Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_sources(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListSourcesRequest, dict]): - The request object. Request message for listing sources. - parent (str): - Required. Resource name of the parent of sources to - list. Its format should be - ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - - 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.securitycenter_v2.services.security_center.pagers.ListSourcesPager: - Response message for listing sources. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_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.ListSourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_valued_resources(self, - request: Optional[Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesPager: - r"""Lists the valued resources for a set of simulation - results and filter. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_list_valued_resources(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.ListValuedResourcesRequest, dict]): - The request object. Request message for listing the - valued resources for a given simulation. - parent (str): - Required. Name of parent to list exposed resources. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - - 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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesPager: - Response message for listing the - valued resources for a given simulation. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: 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, securitycenter_service.ListValuedResourcesRequest): - request = securitycenter_service.ListValuedResourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - 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_valued_resources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_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.ListValuedResourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_finding_state(self, - request: Optional[Union[securitycenter_service.SetFindingStateRequest, dict]] = None, - *, - name: Optional[str] = None, - state: Optional[finding.Finding.State] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. If no location is - specified, finding is assumed to be in global - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_set_finding_state(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.SetFindingStateRequest, dict]): - The request object. Request message for updating a - finding's state. - name (str): - Required. The `relative resource - name `__ - of the finding. If no location is specified, finding is - assumed to be in global. The following list shows some - examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (google.cloud.securitycenter_v2.types.Finding.State): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_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 set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on the specified - 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.cloud import securitycenter_v2 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - :literal:`\` { "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')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` - - **YAML example:** - - :literal:`\` 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') etag: BwWWja0YfJA= version: 3`\ \` - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # 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 set_mute(self, - request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, - *, - name: Optional[str] = None, - mute: Optional[finding.Finding.Mute] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the mute state of a finding. If no location - is specified, finding is assumed to be in global - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_set_mute(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = client.set_mute(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.SetMuteRequest, dict]): - The request object. Request message for updating a - finding's mute status. - name (str): - Required. The `relative resource - name `__ - of the finding. If no location is specified, finding is - assumed to be in global. The following list shows some - examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mute (google.cloud.securitycenter_v2.types.Finding.Mute): - Required. The desired state of the - Mute. - - This corresponds to the ``mute`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, mute]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, securitycenter_service.SetMuteRequest): - request = securitycenter_service.SetMuteRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if mute is not None: - request.mute = mute - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_mute] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the - specified 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.cloud import securitycenter_v2 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions 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([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # - The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # 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 - - def update_big_query_export(self, - request: Optional[Union[securitycenter_service.UpdateBigQueryExportRequest, dict]] = None, - *, - big_query_export: Optional[bigquery_export.BigQueryExport] = None, - update_mask: 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]] = (), - ) -> bigquery_export.BigQueryExport: - r"""Updates a BigQuery export. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateBigQueryExportRequest( - ) - - # Make the request - response = client.update_big_query_export(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest, dict]): - The request object. Request message for updating a - BigQuery export. - big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): - Required. The BigQuery export being - updated. - - This corresponds to the ``big_query_export`` 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. - If empty all mutable fields 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.cloud.securitycenter_v2.types.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([big_query_export, 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, securitycenter_service.UpdateBigQueryExportRequest): - request = securitycenter_service.UpdateBigQueryExportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if big_query_export is not None: - request.big_query_export = big_query_export - 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_big_query_export] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("big_query_export.name", request.big_query_export.name), - )), - ) - - # Validate the universe 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_external_system(self, - request: Optional[Union[securitycenter_service.UpdateExternalSystemRequest, dict]] = None, - *, - external_system: Optional[gcs_external_system.ExternalSystem] = None, - update_mask: 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]] = (), - ) -> gcs_external_system.ExternalSystem: - r"""Updates external system. This is for a given finding. - If no location is specified, finding is assumed to be in - global - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_external_system(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateExternalSystemRequest( - ) - - # Make the request - response = client.update_external_system(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest, dict]): - The request object. Request message for updating a - ExternalSystem resource. - external_system (google.cloud.securitycenter_v2.types.ExternalSystem): - Required. The external system - resource to update. - - This corresponds to the ``external_system`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the external system resource. - If empty all mutable fields 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.cloud.securitycenter_v2.types.ExternalSystem: - Representation of third party - SIEM/SOAR fields within SCC. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([external_system, 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, securitycenter_service.UpdateExternalSystemRequest): - request = securitycenter_service.UpdateExternalSystemRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if external_system is not None: - request.external_system = external_system - 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_external_system] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("external_system.name", request.external_system.name), - )), - ) - - # Validate the universe 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_finding(self, - request: Optional[Union[securitycenter_service.UpdateFindingRequest, dict]] = None, - *, - finding: Optional[gcs_finding.Finding] = None, - update_mask: 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]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. If no location is - specified, finding is assumed to be in global. The - corresponding source must exist for a finding creation - to succeed. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateFindingRequest, dict]): - The request object. Request message for updating or - creating a finding. - finding (google.cloud.securitycenter_v2.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a - finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing - source_properties. Individual source_properties can be - added/updated by using "source_properties." in the field - mask. - - 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.securitycenter_v2.types.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding, 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, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - 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_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Validate the universe 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_mute_config(self, - request: Optional[Union[securitycenter_service.UpdateMuteConfigRequest, dict]] = None, - *, - mute_config: Optional[gcs_mute_config.MuteConfig] = None, - update_mask: 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]] = (), - ) -> gcs_mute_config.MuteConfig: - r"""Updates a mute config. If no location is specified, - default is global. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = client.update_mute_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest, dict]): - The request object. Request message for updating a mute - config. - mute_config (google.cloud.securitycenter_v2.types.MuteConfig): - Required. The mute config being - updated. - - This corresponds to the ``mute_config`` 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. - If empty all mutable fields 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.cloud.securitycenter_v2.types.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([mute_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, securitycenter_service.UpdateMuteConfigRequest): - request = securitycenter_service.UpdateMuteConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if mute_config is not None: - request.mute_config = mute_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_mute_config] - - header_params = {} - - routing_param_regex = re.compile('^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.mute_config.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.mute_config.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - routing_param_regex = re.compile('^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$') - regex_match = routing_param_regex.match(request.mute_config.name) - if regex_match and regex_match.group("location"): - header_params["location"] = regex_match.group("location") - - 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_notification_config(self, - request: Optional[Union[securitycenter_service.UpdateNotificationConfigRequest, dict]] = None, - *, - notification_config: Optional[gcs_notification_config.NotificationConfig] = None, - update_mask: 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]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateNotificationConfigRequest( - ) - - # Make the request - response = client.update_notification_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest, dict]): - The request object. Request message for updating a - notification config. - notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the notification config. - If empty all mutable fields 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.cloud.securitycenter_v2.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # - Quick 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_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, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_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 update_resource_value_config(self, - request: Optional[Union[securitycenter_service.UpdateResourceValueConfigRequest, dict]] = None, - *, - resource_value_config: Optional[gcs_resource_value_config.ResourceValueConfig] = None, - update_mask: 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]] = (), - ) -> gcs_resource_value_config.ResourceValueConfig: - r"""Updates an existing ResourceValueConfigs with new - rules. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateResourceValueConfigRequest( - ) - - # Make the request - response = client.update_resource_value_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest, dict]): - The request object. Request message to update resource - value config - resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): - Required. The resource value config - being updated. - - This corresponds to the ``resource_value_config`` 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. If empty all mutable - fields will be updated. - - To update nested fields, include the top level field in - the mask For example, to update - gcp_metadata.resource_type, include the "gcp_metadata" - field mask - - 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.securitycenter_v2.types.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource_value_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, securitycenter_service.UpdateResourceValueConfigRequest): - request = securitycenter_service.UpdateResourceValueConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if resource_value_config is not None: - request.resource_value_config = resource_value_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_resource_value_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource_value_config.name", request.resource_value_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 update_security_marks(self, - request: Optional[Union[securitycenter_service.UpdateSecurityMarksRequest, dict]] = None, - *, - security_marks: Optional[gcs_security_marks.SecurityMarks] = None, - update_mask: 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]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. For Finding Security marks, - if no location is specified, finding is assumed to be in - global. Assets Security Marks can only be accessed - through global endpoint. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import securitycenter_v2 - - def sample_update_security_marks(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest, dict]): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If - empty or set to "marks", all marks will be replaced. - Individual marks can be updated using - "marks.". - - 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.securitycenter_v2.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks, 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, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - 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_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Validate the universe 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_source(self, - request: Optional[Union[securitycenter_service.UpdateSourceRequest, dict]] = None, - *, - source: Optional[gcs_source.Source] = None, - update_mask: 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]] = (), - ) -> gcs_source.Source: - r"""Updates a 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.cloud import securitycenter_v2 - - def sample_update_source(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.securitycenter_v2.types.UpdateSourceRequest, dict]): - The request object. Request message for updating a - source. - source (google.cloud.securitycenter_v2.types.Source): - Required. The source resource to - update. - - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the source resource. - If empty all mutable fields 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.cloud.securitycenter_v2.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([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, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = 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_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.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 __enter__(self) -> "SecurityCenterClient": - 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 = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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 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 = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - 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 = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SecurityCenterClient", -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py deleted file mode 100644 index 59d34c60c0a9..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/pagers.py +++ /dev/null @@ -1,1249 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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.securitycenter_v2.types import attack_path -from google.cloud.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import valued_resource - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v2.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` - attributes are available on the 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[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v2.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - 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[securitycenter_service.GroupFindingsResponse]: - 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[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAttackPathsPager: - """A pager for iterating through ``list_attack_paths`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``attack_paths`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAttackPaths`` requests and continue to iterate - through the ``attack_paths`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListAttackPathsResponse], - request: securitycenter_service.ListAttackPathsRequest, - response: securitycenter_service.ListAttackPathsResponse, - *, - 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.securitycenter_v2.types.ListAttackPathsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListAttackPathsResponse): - 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 = securitycenter_service.ListAttackPathsRequest(request) - 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[securitycenter_service.ListAttackPathsResponse]: - 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[attack_path.AttackPath]: - for page in self.pages: - yield from page.attack_paths - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAttackPathsAsyncPager: - """A pager for iterating through ``list_attack_paths`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``attack_paths`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAttackPaths`` requests and continue to iterate - through the ``attack_paths`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` - attributes are available on the 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[securitycenter_service.ListAttackPathsResponse]], - request: securitycenter_service.ListAttackPathsRequest, - response: securitycenter_service.ListAttackPathsResponse, - *, - 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.securitycenter_v2.types.ListAttackPathsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListAttackPathsResponse): - 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 = securitycenter_service.ListAttackPathsRequest(request) - 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[securitycenter_service.ListAttackPathsResponse]: - 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[attack_path.AttackPath]: - async def async_generator(): - async for page in self.pages: - for response in page.attack_paths: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBigQueryExportsPager: - """A pager for iterating through ``list_big_query_exports`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``big_query_exports`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListBigQueryExports`` requests and continue to iterate - through the ``big_query_exports`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListBigQueryExportsResponse], - request: securitycenter_service.ListBigQueryExportsRequest, - response: securitycenter_service.ListBigQueryExportsResponse, - *, - 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.securitycenter_v2.types.ListBigQueryExportsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse): - 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 = securitycenter_service.ListBigQueryExportsRequest(request) - 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[securitycenter_service.ListBigQueryExportsResponse]: - 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[bigquery_export.BigQueryExport]: - for page in self.pages: - yield from page.big_query_exports - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBigQueryExportsAsyncPager: - """A pager for iterating through ``list_big_query_exports`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``big_query_exports`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListBigQueryExports`` requests and continue to iterate - through the ``big_query_exports`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` - attributes are available on the 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[securitycenter_service.ListBigQueryExportsResponse]], - request: securitycenter_service.ListBigQueryExportsRequest, - response: securitycenter_service.ListBigQueryExportsResponse, - *, - 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.securitycenter_v2.types.ListBigQueryExportsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse): - 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 = securitycenter_service.ListBigQueryExportsRequest(request) - 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[securitycenter_service.ListBigQueryExportsResponse]: - 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[bigquery_export.BigQueryExport]: - async def async_generator(): - async for page in self.pages: - for response in page.big_query_exports: - 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.securitycenter_v2.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.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[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v2.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - for page in self.pages: - yield from page.list_findings_results - - 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.securitycenter_v2.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.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[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.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.securitycenter_v2.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.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 = securitycenter_service.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[securitycenter_service.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[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_findings_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMuteConfigsPager: - """A pager for iterating through ``list_mute_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``mute_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListMuteConfigs`` requests and continue to iterate - through the ``mute_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListMuteConfigsResponse], - request: securitycenter_service.ListMuteConfigsRequest, - response: securitycenter_service.ListMuteConfigsResponse, - *, - 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.securitycenter_v2.types.ListMuteConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListMuteConfigsResponse): - 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 = securitycenter_service.ListMuteConfigsRequest(request) - 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[securitycenter_service.ListMuteConfigsResponse]: - 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[mute_config.MuteConfig]: - for page in self.pages: - yield from page.mute_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMuteConfigsAsyncPager: - """A pager for iterating through ``list_mute_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``mute_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListMuteConfigs`` requests and continue to iterate - through the ``mute_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` - attributes are available on the 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[securitycenter_service.ListMuteConfigsResponse]], - request: securitycenter_service.ListMuteConfigsRequest, - response: securitycenter_service.ListMuteConfigsResponse, - *, - 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.securitycenter_v2.types.ListMuteConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListMuteConfigsResponse): - 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 = securitycenter_service.ListMuteConfigsRequest(request) - 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[securitycenter_service.ListMuteConfigsResponse]: - 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[mute_config.MuteConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.mute_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v2.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - 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[securitycenter_service.ListNotificationConfigsResponse]: - 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[notification_config.NotificationConfig]: - for page in self.pages: - yield from page.notification_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsAsyncPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` - attributes are available on the 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[securitycenter_service.ListNotificationConfigsResponse]], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v2.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - 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[securitycenter_service.ListNotificationConfigsResponse]: - 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[notification_config.NotificationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.notification_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourceValueConfigsPager: - """A pager for iterating through ``list_resource_value_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``resource_value_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListResourceValueConfigs`` requests and continue to iterate - through the ``resource_value_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListResourceValueConfigsResponse], - request: securitycenter_service.ListResourceValueConfigsRequest, - response: securitycenter_service.ListResourceValueConfigsResponse, - *, - 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.securitycenter_v2.types.ListResourceValueConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse): - 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 = securitycenter_service.ListResourceValueConfigsRequest(request) - 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[securitycenter_service.ListResourceValueConfigsResponse]: - 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[resource_value_config.ResourceValueConfig]: - for page in self.pages: - yield from page.resource_value_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourceValueConfigsAsyncPager: - """A pager for iterating through ``list_resource_value_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``resource_value_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListResourceValueConfigs`` requests and continue to iterate - through the ``resource_value_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` - attributes are available on the 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[securitycenter_service.ListResourceValueConfigsResponse]], - request: securitycenter_service.ListResourceValueConfigsRequest, - response: securitycenter_service.ListResourceValueConfigsResponse, - *, - 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.securitycenter_v2.types.ListResourceValueConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse): - 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 = securitycenter_service.ListResourceValueConfigsRequest(request) - 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[securitycenter_service.ListResourceValueConfigsResponse]: - 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[resource_value_config.ResourceValueConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.resource_value_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v2.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` - attributes are available on the 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[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v2.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - 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[securitycenter_service.ListSourcesResponse]: - 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[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.sources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListValuedResourcesPager: - """A pager for iterating through ``list_valued_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``valued_resources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListValuedResources`` requests and continue to iterate - through the ``valued_resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., securitycenter_service.ListValuedResourcesResponse], - request: securitycenter_service.ListValuedResourcesRequest, - response: securitycenter_service.ListValuedResourcesResponse, - *, - 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.securitycenter_v2.types.ListValuedResourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListValuedResourcesResponse): - 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 = securitycenter_service.ListValuedResourcesRequest(request) - 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[securitycenter_service.ListValuedResourcesResponse]: - 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[valued_resource.ValuedResource]: - for page in self.pages: - yield from page.valued_resources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListValuedResourcesAsyncPager: - """A pager for iterating through ``list_valued_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``valued_resources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListValuedResources`` requests and continue to iterate - through the ``valued_resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` - attributes are available on the 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[securitycenter_service.ListValuedResourcesResponse]], - request: securitycenter_service.ListValuedResourcesRequest, - response: securitycenter_service.ListValuedResourcesResponse, - *, - 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.securitycenter_v2.types.ListValuedResourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v2.types.ListValuedResourcesResponse): - 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 = securitycenter_service.ListValuedResourcesRequest(request) - 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[securitycenter_service.ListValuedResourcesResponse]: - 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[valued_resource.ValuedResource]: - async def async_generator(): - async for page in self.pages: - for response in page.valued_resources: - 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-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py deleted file mode 100644 index 9d36139c1a9b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/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 SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .rest import SecurityCenterRestTransport -from .rest import SecurityCenterRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry['grpc'] = SecurityCenterGrpcTransport -_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport -_transport_registry['rest'] = SecurityCenterRestTransport - -__all__ = ( - 'SecurityCenterTransport', - 'SecurityCenterGrpcTransport', - 'SecurityCenterGrpcAsyncIOTransport', - 'SecurityCenterRestTransport', - 'SecurityCenterRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py deleted file mode 100644 index 817f5b747cd0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/base.py +++ /dev/null @@ -1,761 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.securitycenter_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.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.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import valued_resource -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 empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'securitycenter.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.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: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials 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.batch_create_resource_value_configs: gapic_v1.method.wrap_method( - self.batch_create_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.bulk_mute_findings: gapic_v1.method.wrap_method( - self.bulk_mute_findings, - default_timeout=None, - client_info=client_info, - ), - self.create_big_query_export: gapic_v1.method.wrap_method( - self.create_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, - default_timeout=None, - client_info=client_info, - ), - self.create_mute_config: gapic_v1.method.wrap_method( - self.create_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method.wrap_method( - self.create_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.create_source: gapic_v1.method.wrap_method( - self.create_source, - default_timeout=None, - client_info=client_info, - ), - self.delete_big_query_export: gapic_v1.method.wrap_method( - self.delete_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.delete_mute_config: gapic_v1.method.wrap_method( - self.delete_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method.wrap_method( - self.delete_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_resource_value_config: gapic_v1.method.wrap_method( - self.delete_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.get_big_query_export: gapic_v1.method.wrap_method( - self.get_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.get_simulation: gapic_v1.method.wrap_method( - self.get_simulation, - default_timeout=None, - client_info=client_info, - ), - self.get_valued_resource: gapic_v1.method.wrap_method( - self.get_valued_resource, - default_timeout=None, - 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.get_mute_config: gapic_v1.method.wrap_method( - self.get_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.get_notification_config: gapic_v1.method.wrap_method( - self.get_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.get_resource_value_config: gapic_v1.method.wrap_method( - self.get_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.get_source: gapic_v1.method.wrap_method( - self.get_source, - default_timeout=None, - client_info=client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_findings, - default_timeout=None, - client_info=client_info, - ), - self.list_attack_paths: gapic_v1.method.wrap_method( - self.list_attack_paths, - default_timeout=None, - client_info=client_info, - ), - self.list_big_query_exports: gapic_v1.method.wrap_method( - self.list_big_query_exports, - default_timeout=None, - client_info=client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - default_timeout=None, - client_info=client_info, - ), - self.list_mute_configs: gapic_v1.method.wrap_method( - self.list_mute_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method.wrap_method( - self.list_notification_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_resource_value_configs: gapic_v1.method.wrap_method( - self.list_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_sources: gapic_v1.method.wrap_method( - self.list_sources, - default_timeout=None, - client_info=client_info, - ), - self.list_valued_resources: gapic_v1.method.wrap_method( - self.list_valued_resources, - default_timeout=None, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, - 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.set_mute: gapic_v1.method.wrap_method( - self.set_mute, - 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.update_big_query_export: gapic_v1.method.wrap_method( - self.update_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.update_external_system: gapic_v1.method.wrap_method( - self.update_external_system, - default_timeout=None, - client_info=client_info, - ), - self.update_finding: gapic_v1.method.wrap_method( - self.update_finding, - default_timeout=None, - client_info=client_info, - ), - self.update_mute_config: gapic_v1.method.wrap_method( - self.update_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method.wrap_method( - self.update_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.update_resource_value_config: gapic_v1.method.wrap_method( - self.update_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=None, - client_info=client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_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 operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - Union[ - securitycenter_service.BatchCreateResourceValueConfigsResponse, - Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - Union[ - bigquery_export.BigQueryExport, - Awaitable[bigquery_export.BigQueryExport] - ]]: - raise NotImplementedError() - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - Union[ - gcs_mute_config.MuteConfig, - Awaitable[gcs_mute_config.MuteConfig] - ]]: - raise NotImplementedError() - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - Union[ - bigquery_export.BigQueryExport, - Awaitable[bigquery_export.BigQueryExport] - ]]: - raise NotImplementedError() - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - Union[ - simulation.Simulation, - Awaitable[simulation.Simulation] - ]]: - raise NotImplementedError() - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - Union[ - valued_resource.ValuedResource, - Awaitable[valued_resource.ValuedResource] - ]]: - 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 get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - Union[ - mute_config.MuteConfig, - Awaitable[mute_config.MuteConfig] - ]]: - raise NotImplementedError() - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Union[ - notification_config.NotificationConfig, - Awaitable[notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - Union[ - resource_value_config.ResourceValueConfig, - Awaitable[resource_value_config.ResourceValueConfig] - ]]: - raise NotImplementedError() - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Union[ - source.Source, - Awaitable[source.Source] - ]]: - raise NotImplementedError() - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Union[ - securitycenter_service.GroupFindingsResponse, - Awaitable[securitycenter_service.GroupFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - Union[ - securitycenter_service.ListAttackPathsResponse, - Awaitable[securitycenter_service.ListAttackPathsResponse] - ]]: - raise NotImplementedError() - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - Union[ - securitycenter_service.ListBigQueryExportsResponse, - Awaitable[securitycenter_service.ListBigQueryExportsResponse] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Union[ - securitycenter_service.ListFindingsResponse, - Awaitable[securitycenter_service.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - Union[ - securitycenter_service.ListMuteConfigsResponse, - Awaitable[securitycenter_service.ListMuteConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Union[ - securitycenter_service.ListNotificationConfigsResponse, - Awaitable[securitycenter_service.ListNotificationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - Union[ - securitycenter_service.ListResourceValueConfigsResponse, - Awaitable[securitycenter_service.ListResourceValueConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Union[ - securitycenter_service.ListSourcesResponse, - Awaitable[securitycenter_service.ListSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - Union[ - securitycenter_service.ListValuedResourcesResponse, - Awaitable[securitycenter_service.ListValuedResourcesResponse] - ]]: - raise NotImplementedError() - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - 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 set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - 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 update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - Union[ - bigquery_export.BigQueryExport, - Awaitable[bigquery_export.BigQueryExport] - ]]: - raise NotImplementedError() - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - Union[ - gcs_external_system.ExternalSystem, - Awaitable[gcs_external_system.ExternalSystem] - ]]: - raise NotImplementedError() - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - Union[ - gcs_mute_config.MuteConfig, - Awaitable[gcs_mute_config.MuteConfig] - ]]: - raise NotImplementedError() - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - Union[ - gcs_resource_value_config.ResourceValueConfig, - Awaitable[gcs_resource_value_config.ResourceValueConfig] - ]]: - raise NotImplementedError() - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Union[ - gcs_security_marks.SecurityMarks, - Awaitable[gcs_security_marks.SecurityMarks] - ]]: - raise NotImplementedError() - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SecurityCenterTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py deleted file mode 100644 index 3ab2b66d9b6e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py +++ /dev/null @@ -1,1452 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import valued_resource -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 empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V2 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: 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 batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - securitycenter_service.BatchCreateResourceValueConfigsResponse]: - r"""Return a callable for the batch create resource value - configs method over gRPC. - - Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - Returns: - Callable[[~.BatchCreateResourceValueConfigsRequest], - ~.BatchCreateResourceValueConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: - self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/BatchCreateResourceValueConfigs', - request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, - ) - return self._stubs['batch_create_resource_value_configs'] - - @property - def bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - operations_pb2.Operation]: - r"""Return a callable for the bulk mute findings method over gRPC. - - Kicks off an LRO to bulk mute findings for a parent - based on a filter. If no location is specified, findings - are muted in global. The parent can be either an - organization, folder, or project. The findings matched - by the filter will be muted after the LRO is done. - - Returns: - Callable[[~.BulkMuteFindingsRequest], - ~.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 'bulk_mute_findings' not in self._stubs: - self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/BulkMuteFindings', - request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['bulk_mute_findings'] - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - r"""Return a callable for the create big query export method over gRPC. - - Creates a BigQuery export. - - Returns: - Callable[[~.CreateBigQueryExportRequest], - ~.BigQueryExport]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateBigQueryExport', - request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['create_big_query_export'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding in a location. The corresponding - source must exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - r"""Return a callable for the create mute config method over gRPC. - - Creates a mute config. - - Returns: - Callable[[~.CreateMuteConfigRequest], - ~.MuteConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateMuteConfig', - request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['create_mute_config'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete big query export method over gRPC. - - Deletes an existing BigQuery export. - - Returns: - Callable[[~.DeleteBigQueryExportRequest], - ~.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_big_query_export' not in self._stubs: - self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteBigQueryExport', - request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_big_query_export'] - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete mute config method over gRPC. - - Deletes an existing mute config. If no location is - specified, default is global. - - Returns: - Callable[[~.DeleteMuteConfigRequest], - ~.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_mute_config' not in self._stubs: - self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteMuteConfig', - request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_mute_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - ~.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_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete resource value config method over gRPC. - - Deletes a ResourceValueConfig. - - Returns: - Callable[[~.DeleteResourceValueConfigRequest], - ~.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_resource_value_config' not in self._stubs: - self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteResourceValueConfig', - request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_resource_value_config'] - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - bigquery_export.BigQueryExport]: - r"""Return a callable for the get big query export method over gRPC. - - Gets a BigQuery export. - - Returns: - Callable[[~.GetBigQueryExportRequest], - ~.BigQueryExport]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_big_query_export' not in self._stubs: - self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetBigQueryExport', - request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['get_big_query_export'] - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - simulation.Simulation]: - r"""Return a callable for the get simulation method over gRPC. - - Get the simulation by name or the latest simulation - for the given organization. - - Returns: - Callable[[~.GetSimulationRequest], - ~.Simulation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_simulation' not in self._stubs: - self._stubs['get_simulation'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetSimulation', - request_serializer=securitycenter_service.GetSimulationRequest.serialize, - response_deserializer=simulation.Simulation.deserialize, - ) - return self._stubs['get_simulation'] - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - valued_resource.ValuedResource]: - r"""Return a callable for the get valued resource method over gRPC. - - Get the valued resource by name - - Returns: - Callable[[~.GetValuedResourceRequest], - ~.ValuedResource]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_valued_resource' not in self._stubs: - self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetValuedResource', - request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, - response_deserializer=valued_resource.ValuedResource.deserialize, - ) - return self._stubs['get_valued_resource'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v2.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - mute_config.MuteConfig]: - r"""Return a callable for the get mute config method over gRPC. - - Gets a mute config. If no location is specified, - default is global. - - Returns: - Callable[[~.GetMuteConfigRequest], - ~.MuteConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_mute_config' not in self._stubs: - self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetMuteConfig', - request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, - response_deserializer=mute_config.MuteConfig.deserialize, - ) - return self._stubs['get_mute_config'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - resource_value_config.ResourceValueConfig]: - r"""Return a callable for the get resource value config method over gRPC. - - Gets a ResourceValueConfig. - - Returns: - Callable[[~.GetResourceValueConfigRequest], - ~.ResourceValueConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_resource_value_config' not in self._stubs: - self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetResourceValueConfig', - request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, - response_deserializer=resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['get_resource_value_config'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties in a location. If no location is - specified, findings are assumed to be in global - - To group across all sources provide a ``-`` as the source id. - The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - - ``/v2/folders/{folder_id}/sources/-/findings`` - - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` - - ``/v2/projects/{project_id}/sources/-/findings`` - - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - securitycenter_service.ListAttackPathsResponse]: - r"""Return a callable for the list attack paths method over gRPC. - - Lists the attack paths for a set of simulation - results or valued resources and filter. - - Returns: - Callable[[~.ListAttackPathsRequest], - ~.ListAttackPathsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_attack_paths' not in self._stubs: - self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListAttackPaths', - request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, - response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, - ) - return self._stubs['list_attack_paths'] - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - securitycenter_service.ListBigQueryExportsResponse]: - r"""Return a callable for the list big query exports method over gRPC. - - Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are returned. - - Returns: - Callable[[~.ListBigQueryExportsRequest], - ~.ListBigQueryExportsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_big_query_exports' not in self._stubs: - self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListBigQueryExports', - request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, - response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, - ) - return self._stubs['list_big_query_exports'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources for a given location provide a ``-`` - as the source id. If no location is specified, finding are - assumed to be in global. The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - 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.securitycenter.v2.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - securitycenter_service.ListMuteConfigsResponse]: - r"""Return a callable for the list mute configs method over gRPC. - - Lists mute configs. If no location is specified, - default is global. - - Returns: - Callable[[~.ListMuteConfigsRequest], - ~.ListMuteConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_mute_configs' not in self._stubs: - self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListMuteConfigs', - request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, - ) - return self._stubs['list_mute_configs'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - ~.ListNotificationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - securitycenter_service.ListResourceValueConfigsResponse]: - r"""Return a callable for the list resource value configs method over gRPC. - - Lists all ResourceValueConfigs. - - Returns: - Callable[[~.ListResourceValueConfigsRequest], - ~.ListResourceValueConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_resource_value_configs' not in self._stubs: - self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListResourceValueConfigs', - request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, - ) - return self._stubs['list_resource_value_configs'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - securitycenter_service.ListValuedResourcesResponse]: - r"""Return a callable for the list valued resources method over gRPC. - - Lists the valued resources for a set of simulation - results and filter. - - Returns: - Callable[[~.ListValuedResourcesRequest], - ~.ListValuedResourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_valued_resources' not in self._stubs: - self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListValuedResources', - request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, - response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, - ) - return self._stubs['list_valued_resources'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. If no location is - specified, finding is assumed to be in global - - Returns: - Callable[[~.SetFindingStateRequest], - ~.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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v2.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - finding.Finding]: - r"""Return a callable for the set mute method over gRPC. - - Updates the mute state of a finding. If no location - is specified, finding is assumed to be in global - - Returns: - Callable[[~.SetMuteRequest], - ~.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 'set_mute' not in self._stubs: - self._stubs['set_mute'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/SetMute', - request_serializer=securitycenter_service.SetMuteRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_mute'] - - @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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v2.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - r"""Return a callable for the update big query export method over gRPC. - - Updates a BigQuery export. - - Returns: - Callable[[~.UpdateBigQueryExportRequest], - ~.BigQueryExport]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateBigQueryExport', - request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['update_big_query_export'] - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - gcs_external_system.ExternalSystem]: - r"""Return a callable for the update external system method over gRPC. - - Updates external system. This is for a given finding. - If no location is specified, finding is assumed to be in - global - - Returns: - Callable[[~.UpdateExternalSystemRequest], - ~.ExternalSystem]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_external_system' not in self._stubs: - self._stubs['update_external_system'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateExternalSystem', - request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, - response_deserializer=gcs_external_system.ExternalSystem.deserialize, - ) - return self._stubs['update_external_system'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. If no location is - specified, finding is assumed to be in global. The - corresponding source must exist for a finding creation - to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - r"""Return a callable for the update mute config method over gRPC. - - Updates a mute config. If no location is specified, - default is global. - - Returns: - Callable[[~.UpdateMuteConfigRequest], - ~.MuteConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateMuteConfig', - request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['update_mute_config'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - gcs_resource_value_config.ResourceValueConfig]: - r"""Return a callable for the update resource value config method over gRPC. - - Updates an existing ResourceValueConfigs with new - rules. - - Returns: - Callable[[~.UpdateResourceValueConfigRequest], - ~.ResourceValueConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: - self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateResourceValueConfig', - request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, - response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['update_resource_value_config'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. For Finding Security marks, - if no location is specified, finding is assumed to be in - global. Assets Security Marks can only be accessed - through global endpoint. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - 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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SecurityCenterGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index b83a55a9f90c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,1657 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 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.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import valued_resource -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 empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V2 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be 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._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 batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse]]: - r"""Return a callable for the batch create resource value - configs method over gRPC. - - Creates a ResourceValueConfig for an organization. - Maps user's tags to difference resource values for use - by the attack path simulation. - - Returns: - Callable[[~.BatchCreateResourceValueConfigsRequest], - Awaitable[~.BatchCreateResourceValueConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_configs' not in self._stubs: - self._stubs['batch_create_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/BatchCreateResourceValueConfigs', - request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, - ) - return self._stubs['batch_create_resource_value_configs'] - - @property - def bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the bulk mute findings method over gRPC. - - Kicks off an LRO to bulk mute findings for a parent - based on a filter. If no location is specified, findings - are muted in global. The parent can be either an - organization, folder, or project. The findings matched - by the filter will be muted after the LRO is done. - - Returns: - Callable[[~.BulkMuteFindingsRequest], - 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 'bulk_mute_findings' not in self._stubs: - self._stubs['bulk_mute_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/BulkMuteFindings', - request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['bulk_mute_findings'] - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - Awaitable[bigquery_export.BigQueryExport]]: - r"""Return a callable for the create big query export method over gRPC. - - Creates a BigQuery export. - - Returns: - Callable[[~.CreateBigQueryExportRequest], - Awaitable[~.BigQueryExport]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['create_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateBigQueryExport', - request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['create_big_query_export'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding in a location. The corresponding - source must exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - 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 'create_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - Awaitable[gcs_mute_config.MuteConfig]]: - r"""Return a callable for the create mute config method over gRPC. - - Creates a mute config. - - Returns: - Callable[[~.CreateMuteConfigRequest], - Awaitable[~.MuteConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['create_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateMuteConfig', - request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['create_mute_config'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete big query export method over gRPC. - - Deletes an existing BigQuery export. - - Returns: - Callable[[~.DeleteBigQueryExportRequest], - 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_big_query_export' not in self._stubs: - self._stubs['delete_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteBigQueryExport', - request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_big_query_export'] - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete mute config method over gRPC. - - Deletes an existing mute config. If no location is - specified, default is global. - - Returns: - Callable[[~.DeleteMuteConfigRequest], - 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_mute_config' not in self._stubs: - self._stubs['delete_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteMuteConfig', - request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_mute_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - 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_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete resource value config method over gRPC. - - Deletes a ResourceValueConfig. - - Returns: - Callable[[~.DeleteResourceValueConfigRequest], - 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_resource_value_config' not in self._stubs: - self._stubs['delete_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/DeleteResourceValueConfig', - request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_resource_value_config'] - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - Awaitable[bigquery_export.BigQueryExport]]: - r"""Return a callable for the get big query export method over gRPC. - - Gets a BigQuery export. - - Returns: - Callable[[~.GetBigQueryExportRequest], - Awaitable[~.BigQueryExport]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_big_query_export' not in self._stubs: - self._stubs['get_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetBigQueryExport', - request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['get_big_query_export'] - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - Awaitable[simulation.Simulation]]: - r"""Return a callable for the get simulation method over gRPC. - - Get the simulation by name or the latest simulation - for the given organization. - - Returns: - Callable[[~.GetSimulationRequest], - Awaitable[~.Simulation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_simulation' not in self._stubs: - self._stubs['get_simulation'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetSimulation', - request_serializer=securitycenter_service.GetSimulationRequest.serialize, - response_deserializer=simulation.Simulation.deserialize, - ) - return self._stubs['get_simulation'] - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - Awaitable[valued_resource.ValuedResource]]: - r"""Return a callable for the get valued resource method over gRPC. - - Get the valued resource by name - - Returns: - Callable[[~.GetValuedResourceRequest], - Awaitable[~.ValuedResource]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_valued_resource' not in self._stubs: - self._stubs['get_valued_resource'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetValuedResource', - request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, - response_deserializer=valued_resource.ValuedResource.deserialize, - ) - return self._stubs['get_valued_resource'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v2.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - Awaitable[mute_config.MuteConfig]]: - r"""Return a callable for the get mute config method over gRPC. - - Gets a mute config. If no location is specified, - default is global. - - Returns: - Callable[[~.GetMuteConfigRequest], - Awaitable[~.MuteConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_mute_config' not in self._stubs: - self._stubs['get_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetMuteConfig', - request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, - response_deserializer=mute_config.MuteConfig.deserialize, - ) - return self._stubs['get_mute_config'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Awaitable[notification_config.NotificationConfig]]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - Awaitable[resource_value_config.ResourceValueConfig]]: - r"""Return a callable for the get resource value config method over gRPC. - - Gets a ResourceValueConfig. - - Returns: - Callable[[~.GetResourceValueConfigRequest], - Awaitable[~.ResourceValueConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_resource_value_config' not in self._stubs: - self._stubs['get_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetResourceValueConfig', - request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, - response_deserializer=resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['get_resource_value_config'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse]]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties in a location. If no location is - specified, findings are assumed to be in global - - To group across all sources provide a ``-`` as the source id. - The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - - ``/v2/folders/{folder_id}/sources/-/findings`` - - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` - - ``/v2/projects/{project_id}/sources/-/findings`` - - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - Awaitable[securitycenter_service.ListAttackPathsResponse]]: - r"""Return a callable for the list attack paths method over gRPC. - - Lists the attack paths for a set of simulation - results or valued resources and filter. - - Returns: - Callable[[~.ListAttackPathsRequest], - Awaitable[~.ListAttackPathsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_attack_paths' not in self._stubs: - self._stubs['list_attack_paths'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListAttackPaths', - request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, - response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, - ) - return self._stubs['list_attack_paths'] - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - Awaitable[securitycenter_service.ListBigQueryExportsResponse]]: - r"""Return a callable for the list big query exports method over gRPC. - - Lists BigQuery exports. Note that when requesting - BigQuery exports at a given level all exports under that - level are also returned e.g. if requesting BigQuery - exports under a folder, then all BigQuery exports - immediately under the folder plus the ones created under - the projects within the folder are returned. - - Returns: - Callable[[~.ListBigQueryExportsRequest], - Awaitable[~.ListBigQueryExportsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_big_query_exports' not in self._stubs: - self._stubs['list_big_query_exports'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListBigQueryExports', - request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, - response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, - ) - return self._stubs['list_big_query_exports'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources for a given location provide a ``-`` - as the source id. If no location is specified, finding are - assumed to be in global. The following list shows some examples: - - - ``/v2/organizations/{organization_id}/sources/-/findings`` - - - - ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` - - 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.securitycenter.v2.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - Awaitable[securitycenter_service.ListMuteConfigsResponse]]: - r"""Return a callable for the list mute configs method over gRPC. - - Lists mute configs. If no location is specified, - default is global. - - Returns: - Callable[[~.ListMuteConfigsRequest], - Awaitable[~.ListMuteConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_mute_configs' not in self._stubs: - self._stubs['list_mute_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListMuteConfigs', - request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, - ) - return self._stubs['list_mute_configs'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - Awaitable[~.ListNotificationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - Awaitable[securitycenter_service.ListResourceValueConfigsResponse]]: - r"""Return a callable for the list resource value configs method over gRPC. - - Lists all ResourceValueConfigs. - - Returns: - Callable[[~.ListResourceValueConfigsRequest], - Awaitable[~.ListResourceValueConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_resource_value_configs' not in self._stubs: - self._stubs['list_resource_value_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListResourceValueConfigs', - request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, - ) - return self._stubs['list_resource_value_configs'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse]]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - Awaitable[securitycenter_service.ListValuedResourcesResponse]]: - r"""Return a callable for the list valued resources method over gRPC. - - Lists the valued resources for a set of simulation - results and filter. - - Returns: - Callable[[~.ListValuedResourcesRequest], - Awaitable[~.ListValuedResourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_valued_resources' not in self._stubs: - self._stubs['list_valued_resources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/ListValuedResources', - request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, - response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, - ) - return self._stubs['list_valued_resources'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. If no location is - specified, finding is assumed to be in global - - Returns: - Callable[[~.SetFindingStateRequest], - 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 'set_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.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.cloud.securitycenter.v2.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set mute method over gRPC. - - Updates the mute state of a finding. If no location - is specified, finding is assumed to be in global - - Returns: - Callable[[~.SetMuteRequest], - 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 'set_mute' not in self._stubs: - self._stubs['set_mute'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/SetMute', - request_serializer=securitycenter_service.SetMuteRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_mute'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.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.cloud.securitycenter.v2.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - Awaitable[bigquery_export.BigQueryExport]]: - r"""Return a callable for the update big query export method over gRPC. - - Updates a BigQuery export. - - Returns: - Callable[[~.UpdateBigQueryExportRequest], - Awaitable[~.BigQueryExport]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_big_query_export' not in self._stubs: - self._stubs['update_big_query_export'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateBigQueryExport', - request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, - response_deserializer=bigquery_export.BigQueryExport.deserialize, - ) - return self._stubs['update_big_query_export'] - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - Awaitable[gcs_external_system.ExternalSystem]]: - r"""Return a callable for the update external system method over gRPC. - - Updates external system. This is for a given finding. - If no location is specified, finding is assumed to be in - global - - Returns: - Callable[[~.UpdateExternalSystemRequest], - Awaitable[~.ExternalSystem]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_external_system' not in self._stubs: - self._stubs['update_external_system'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateExternalSystem', - request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, - response_deserializer=gcs_external_system.ExternalSystem.deserialize, - ) - return self._stubs['update_external_system'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. If no location is - specified, finding is assumed to be in global. The - corresponding source must exist for a finding creation - to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - 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 'update_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - Awaitable[gcs_mute_config.MuteConfig]]: - r"""Return a callable for the update mute config method over gRPC. - - Updates a mute config. If no location is specified, - default is global. - - Returns: - Callable[[~.UpdateMuteConfigRequest], - Awaitable[~.MuteConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_mute_config' not in self._stubs: - self._stubs['update_mute_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateMuteConfig', - request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, - response_deserializer=gcs_mute_config.MuteConfig.deserialize, - ) - return self._stubs['update_mute_config'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - Awaitable[gcs_resource_value_config.ResourceValueConfig]]: - r"""Return a callable for the update resource value config method over gRPC. - - Updates an existing ResourceValueConfigs with new - rules. - - Returns: - Callable[[~.UpdateResourceValueConfigRequest], - Awaitable[~.ResourceValueConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_resource_value_config' not in self._stubs: - self._stubs['update_resource_value_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateResourceValueConfig', - request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, - response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, - ) - return self._stubs['update_resource_value_config'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks]]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. For Finding Security marks, - if no location is specified, finding is assumed to be in - global. Assets Security Marks can only be accessed - through global endpoint. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v2.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_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.batch_create_resource_value_configs: gapic_v1.method_async.wrap_method( - self.batch_create_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.bulk_mute_findings: gapic_v1.method_async.wrap_method( - self.bulk_mute_findings, - default_timeout=None, - client_info=client_info, - ), - self.create_big_query_export: gapic_v1.method_async.wrap_method( - self.create_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.create_finding: gapic_v1.method_async.wrap_method( - self.create_finding, - default_timeout=None, - client_info=client_info, - ), - self.create_mute_config: gapic_v1.method_async.wrap_method( - self.create_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method_async.wrap_method( - self.create_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.create_source: gapic_v1.method_async.wrap_method( - self.create_source, - default_timeout=None, - client_info=client_info, - ), - self.delete_big_query_export: gapic_v1.method_async.wrap_method( - self.delete_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.delete_mute_config: gapic_v1.method_async.wrap_method( - self.delete_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method_async.wrap_method( - self.delete_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.delete_resource_value_config: gapic_v1.method_async.wrap_method( - self.delete_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.get_big_query_export: gapic_v1.method_async.wrap_method( - self.get_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.get_simulation: gapic_v1.method_async.wrap_method( - self.get_simulation, - default_timeout=None, - client_info=client_info, - ), - self.get_valued_resource: gapic_v1.method_async.wrap_method( - self.get_valued_resource, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.get_mute_config: gapic_v1.method_async.wrap_method( - self.get_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.get_notification_config: gapic_v1.method_async.wrap_method( - self.get_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.get_resource_value_config: gapic_v1.method_async.wrap_method( - self.get_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.get_source: gapic_v1.method_async.wrap_method( - self.get_source, - default_timeout=None, - client_info=client_info, - ), - self.group_findings: gapic_v1.method_async.wrap_method( - self.group_findings, - default_timeout=None, - client_info=client_info, - ), - self.list_attack_paths: gapic_v1.method_async.wrap_method( - self.list_attack_paths, - default_timeout=None, - client_info=client_info, - ), - self.list_big_query_exports: gapic_v1.method_async.wrap_method( - self.list_big_query_exports, - default_timeout=None, - client_info=client_info, - ), - self.list_findings: gapic_v1.method_async.wrap_method( - self.list_findings, - default_timeout=None, - client_info=client_info, - ), - self.list_mute_configs: gapic_v1.method_async.wrap_method( - self.list_mute_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method_async.wrap_method( - self.list_notification_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_resource_value_configs: gapic_v1.method_async.wrap_method( - self.list_resource_value_configs, - default_timeout=None, - client_info=client_info, - ), - self.list_sources: gapic_v1.method_async.wrap_method( - self.list_sources, - default_timeout=None, - client_info=client_info, - ), - self.list_valued_resources: gapic_v1.method_async.wrap_method( - self.list_valued_resources, - default_timeout=None, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method_async.wrap_method( - self.set_finding_state, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_mute: gapic_v1.method_async.wrap_method( - self.set_mute, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.update_big_query_export: gapic_v1.method_async.wrap_method( - self.update_big_query_export, - default_timeout=None, - client_info=client_info, - ), - self.update_external_system: gapic_v1.method_async.wrap_method( - self.update_external_system, - default_timeout=None, - client_info=client_info, - ), - self.update_finding: gapic_v1.method_async.wrap_method( - self.update_finding, - default_timeout=None, - client_info=client_info, - ), - self.update_mute_config: gapic_v1.method_async.wrap_method( - self.update_mute_config, - default_timeout=None, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method_async.wrap_method( - self.update_notification_config, - default_timeout=None, - client_info=client_info, - ), - self.update_resource_value_config: gapic_v1.method_async.wrap_method( - self.update_resource_value_config, - default_timeout=None, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method_async.wrap_method( - self.update_security_marks, - default_timeout=None, - client_info=client_info, - ), - self.update_source: gapic_v1.method_async.wrap_method( - self.update_source, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - return 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"] - - -__all__ = ( - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py deleted file mode 100644 index 251cc55815bd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/services/security_center/transports/rest.py +++ /dev/null @@ -1,5820 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # 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 path_template -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 -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -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.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import valued_resource -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SecurityCenterRestInterceptor: - """Interceptor for SecurityCenter. - - 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 SecurityCenterRestTransport. - - .. code-block:: python - class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): - def pre_batch_create_resource_value_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_create_resource_value_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_bulk_mute_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_bulk_mute_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_big_query_export(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_mute_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_resource_value_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_big_query_export(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_mute_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_resource_value_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_resource_value_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_simulation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_simulation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_valued_resource(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_valued_resource(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_group_findings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_group_findings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_attack_paths(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_attack_paths(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_big_query_exports(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_big_query_exports(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_mute_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_mute_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_notification_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_notification_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_resource_value_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_resource_value_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_sources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_sources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_valued_resources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_valued_resources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_finding_state(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_finding_state(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_mute(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_mute(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_big_query_export(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_big_query_export(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_external_system(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_external_system(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_finding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_finding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_mute_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_mute_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_notification_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_notification_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_resource_value_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_resource_value_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_security_marks(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_security_marks(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_source(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) - client = SecurityCenterClient(transport=transport) - - - """ - def pre_batch_create_resource_value_configs(self, request: securitycenter_service.BatchCreateResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BatchCreateResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_create_resource_value_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_batch_create_resource_value_configs(self, response: securitycenter_service.BatchCreateResourceValueConfigsResponse) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - """Post-rpc interceptor for batch_create_resource_value_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_bulk_mute_findings(self, request: securitycenter_service.BulkMuteFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.BulkMuteFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for bulk_mute_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_bulk_mute_findings(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for bulk_mute_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_big_query_export(self, request: securitycenter_service.CreateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: - """Post-rpc interceptor for create_big_query_export - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_finding(self, request: securitycenter_service.CreateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for create_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_mute_config(self, request: securitycenter_service.CreateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: - """Post-rpc interceptor for create_mute_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_notification_config(self, request: securitycenter_service.CreateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: - """Post-rpc interceptor for create_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_create_source(self, request: securitycenter_service.CreateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for create_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_delete_big_query_export(self, request: securitycenter_service.DeleteBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_mute_config(self, request: securitycenter_service.DeleteMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_notification_config(self, request: securitycenter_service.DeleteNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_delete_resource_value_config(self, request: securitycenter_service.DeleteResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.DeleteResourceValueConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_resource_value_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def pre_get_big_query_export(self, request: securitycenter_service.GetBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: - """Post-rpc interceptor for get_big_query_export - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_mute_config(self, request: securitycenter_service.GetMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_mute_config(self, response: mute_config.MuteConfig) -> mute_config.MuteConfig: - """Post-rpc interceptor for get_mute_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_notification_config(self, request: securitycenter_service.GetNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_notification_config(self, response: notification_config.NotificationConfig) -> notification_config.NotificationConfig: - """Post-rpc interceptor for get_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_resource_value_config(self, request: securitycenter_service.GetResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetResourceValueConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_resource_value_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_resource_value_config(self, response: resource_value_config.ResourceValueConfig) -> resource_value_config.ResourceValueConfig: - """Post-rpc interceptor for get_resource_value_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_simulation(self, request: securitycenter_service.GetSimulationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSimulationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_simulation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_simulation(self, response: simulation.Simulation) -> simulation.Simulation: - """Post-rpc interceptor for get_simulation - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_source(self, request: securitycenter_service.GetSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_source(self, response: source.Source) -> source.Source: - """Post-rpc interceptor for get_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_get_valued_resource(self, request: securitycenter_service.GetValuedResourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GetValuedResourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_valued_resource - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_get_valued_resource(self, response: valued_resource.ValuedResource) -> valued_resource.ValuedResource: - """Post-rpc interceptor for get_valued_resource - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_group_findings(self, request: securitycenter_service.GroupFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for group_findings - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_group_findings(self, response: securitycenter_service.GroupFindingsResponse) -> securitycenter_service.GroupFindingsResponse: - """Post-rpc interceptor for group_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_attack_paths(self, request: securitycenter_service.ListAttackPathsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListAttackPathsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_attack_paths - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_attack_paths(self, response: securitycenter_service.ListAttackPathsResponse) -> securitycenter_service.ListAttackPathsResponse: - """Post-rpc interceptor for list_attack_paths - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_big_query_exports(self, request: securitycenter_service.ListBigQueryExportsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListBigQueryExportsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_big_query_exports - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_big_query_exports(self, response: securitycenter_service.ListBigQueryExportsResponse) -> securitycenter_service.ListBigQueryExportsResponse: - """Post-rpc interceptor for list_big_query_exports - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_findings(self, request: securitycenter_service.ListFindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.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 SecurityCenter server. - """ - return request, metadata - - def post_list_findings(self, response: securitycenter_service.ListFindingsResponse) -> securitycenter_service.ListFindingsResponse: - """Post-rpc interceptor for list_findings - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_mute_configs(self, request: securitycenter_service.ListMuteConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListMuteConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_mute_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_mute_configs(self, response: securitycenter_service.ListMuteConfigsResponse) -> securitycenter_service.ListMuteConfigsResponse: - """Post-rpc interceptor for list_mute_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_notification_configs(self, request: securitycenter_service.ListNotificationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListNotificationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_notification_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_notification_configs(self, response: securitycenter_service.ListNotificationConfigsResponse) -> securitycenter_service.ListNotificationConfigsResponse: - """Post-rpc interceptor for list_notification_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_resource_value_configs(self, request: securitycenter_service.ListResourceValueConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListResourceValueConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_resource_value_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_resource_value_configs(self, response: securitycenter_service.ListResourceValueConfigsResponse) -> securitycenter_service.ListResourceValueConfigsResponse: - """Post-rpc interceptor for list_resource_value_configs - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_sources(self, request: securitycenter_service.ListSourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_sources - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_sources(self, response: securitycenter_service.ListSourcesResponse) -> securitycenter_service.ListSourcesResponse: - """Post-rpc interceptor for list_sources - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_list_valued_resources(self, request: securitycenter_service.ListValuedResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.ListValuedResourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_valued_resources - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_list_valued_resources(self, response: securitycenter_service.ListValuedResourcesResponse) -> securitycenter_service.ListValuedResourcesResponse: - """Post-rpc interceptor for list_valued_resources - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_set_finding_state(self, request: securitycenter_service.SetFindingStateRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for set_finding_state - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_set_mute(self, request: securitycenter_service.SetMuteRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.SetMuteRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_mute - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_set_mute(self, response: finding.Finding) -> finding.Finding: - """Post-rpc interceptor for set_mute - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_big_query_export(self, request: securitycenter_service.UpdateBigQueryExportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateBigQueryExportRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_big_query_export - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_big_query_export(self, response: bigquery_export.BigQueryExport) -> bigquery_export.BigQueryExport: - """Post-rpc interceptor for update_big_query_export - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_external_system(self, request: securitycenter_service.UpdateExternalSystemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateExternalSystemRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_external_system - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_external_system(self, response: gcs_external_system.ExternalSystem) -> gcs_external_system.ExternalSystem: - """Post-rpc interceptor for update_external_system - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_finding(self, request: securitycenter_service.UpdateFindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_finding - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: - """Post-rpc interceptor for update_finding - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_mute_config(self, request: securitycenter_service.UpdateMuteConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateMuteConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_mute_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_mute_config(self, response: gcs_mute_config.MuteConfig) -> gcs_mute_config.MuteConfig: - """Post-rpc interceptor for update_mute_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_notification_config(self, request: securitycenter_service.UpdateNotificationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateNotificationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_notification_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_notification_config(self, response: gcs_notification_config.NotificationConfig) -> gcs_notification_config.NotificationConfig: - """Post-rpc interceptor for update_notification_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_resource_value_config(self, request: securitycenter_service.UpdateResourceValueConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateResourceValueConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_resource_value_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_resource_value_config(self, response: gcs_resource_value_config.ResourceValueConfig) -> gcs_resource_value_config.ResourceValueConfig: - """Post-rpc interceptor for update_resource_value_config - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_security_marks(self, request: securitycenter_service.UpdateSecurityMarksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_security_marks(self, response: gcs_security_marks.SecurityMarks) -> gcs_security_marks.SecurityMarks: - """Post-rpc interceptor for update_security_marks - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter server but before - it is returned to user code. - """ - return response - def pre_update_source(self, request: securitycenter_service.UpdateSourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the SecurityCenter server. - """ - return request, metadata - - def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: - """Post-rpc interceptor for update_source - - Override in a subclass to manipulate the response - after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SecurityCenterRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SecurityCenterRestInterceptor - - -class SecurityCenterRestTransport(SecurityCenterTransport): - """REST backend transport for SecurityCenter. - - V2 APIs for Security Center 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 = 'securitycenter.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[SecurityCenterRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'securitycenter.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the 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 - 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 - ) - 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 SecurityCenterRestInterceptor() - 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': '/v2/{name=organizations/*/operations/*}:cancel', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v2/{name=organizations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v2/{name=organizations/*/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="v2") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _BatchCreateResourceValueConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("BatchCreateResourceValueConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.BatchCreateResourceValueConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: - r"""Call the batch create resource - value configs method over HTTP. - - Args: - request (~.securitycenter_service.BatchCreateResourceValueConfigsRequest): - The request object. Request message to create multiple - resource value configs - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.BatchCreateResourceValueConfigsResponse: - Response message for - BatchCreateResourceValueConfigs - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*}/resourceValueConfigs:batchCreate', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/locations/*}/resourceValueConfigs:batchCreate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_create_resource_value_configs(request, metadata) - pb_request = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.BatchCreateResourceValueConfigsResponse() - pb_resp = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_create_resource_value_configs(resp) - return resp - - class _BulkMuteFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("BulkMuteFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.BulkMuteFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the bulk mute findings method over HTTP. - - Args: - request (~.securitycenter_service.BulkMuteFindingsRequest): - The request object. Request message for bulk findings - update. - Note: - - 1. If multiple bulk update requests - match the same resource, the order - in which they get executed is not - defined. - 2. Once a bulk operation is started, - there is no way to stop it. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/locations/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*/locations/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*}/findings:bulkMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/findings:bulkMute', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_bulk_mute_findings(request, metadata) - pb_request = securitycenter_service.BulkMuteFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_bulk_mute_findings(resp) - return resp - - class _CreateBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "bigQueryExportId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> bigquery_export.BigQueryExport: - r"""Call the create big query export method over HTTP. - - Args: - request (~.securitycenter_service.CreateBigQueryExportRequest): - The request object. Request message for creating a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.bigquery_export.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/locations/*}/bigQueryExports', - 'body': 'big_query_export', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*/locations/*}/bigQueryExports', - 'body': 'big_query_export', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/bigQueryExports', - 'body': 'big_query_export', - }, - ] - request, metadata = self._interceptor.pre_create_big_query_export(request, metadata) - pb_request = securitycenter_service.CreateBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = bigquery_export.BigQueryExport() - pb_resp = bigquery_export.BigQueryExport.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_big_query_export(resp) - return resp - - class _CreateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "findingId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the create finding method over HTTP. - - Args: - request (~.securitycenter_service.CreateFindingRequest): - The request object. Request message for creating a - finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/sources/*/locations/*}/findings', - 'body': 'finding', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/sources/*}/findings', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_create_finding(request, metadata) - pb_request = securitycenter_service.CreateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_finding(resp) - return resp - - class _CreateMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "muteConfigId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_mute_config.MuteConfig: - r"""Call the create mute config method over HTTP. - - Args: - request (~.securitycenter_service.CreateMuteConfigRequest): - The request object. Request message for creating a mute - config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_mute_config.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/locations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*/locations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*}/muteConfigs', - 'body': 'mute_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*}/muteConfigs', - 'body': 'mute_config', - }, - ] - request, metadata = self._interceptor.pre_create_mute_config(request, metadata) - pb_request = securitycenter_service.CreateMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_mute_config.MuteConfig() - pb_resp = gcs_mute_config.MuteConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_mute_config(resp) - return resp - - class _CreateNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "configId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_notification_config.NotificationConfig: - r"""Call the create notification - config method over HTTP. - - Args: - request (~.securitycenter_service.CreateNotificationConfigRequest): - The request object. Request message for creating a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/locations/*}/notificationConfigs', - 'body': 'notification_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*/locations/*}/notificationConfigs', - 'body': 'notification_config', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/locations/*}/notificationConfigs', - 'body': 'notification_config', - }, - ] - request, metadata = self._interceptor.pre_create_notification_config(request, metadata) - pb_request = securitycenter_service.CreateNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_notification_config.NotificationConfig() - pb_resp = gcs_notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_notification_config(resp) - return resp - - class _CreateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("CreateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.CreateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the create source method over HTTP. - - Args: - request (~.securitycenter_service.CreateSourceRequest): - The request object. Request message for creating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*}/sources', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_create_source(request, metadata) - pb_request = securitycenter_service.CreateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_source(resp) - return resp - - class _DeleteBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete big query export method over HTTP. - - Args: - request (~.securitycenter_service.DeleteBigQueryExportRequest): - The request object. Request message for deleting a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/locations/*/bigQueryExports/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=folders/*/locations/*/bigQueryExports/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/bigQueryExports/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_big_query_export(request, metadata) - pb_request = securitycenter_service.DeleteBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete mute config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteMuteConfigRequest): - The request object. Request message for deleting a mute - config. If no location is specified, - default is global. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=folders/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=folders/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/muteConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/muteConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_mute_config(request, metadata) - pb_request = securitycenter_service.DeleteMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete notification - config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteNotificationConfigRequest): - The request object. Request message for deleting a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/locations/*/notificationConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=folders/*/locations/*/notificationConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=projects/*/locations/*/notificationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_notification_config(request, metadata) - pb_request = securitycenter_service.DeleteNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _DeleteResourceValueConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("DeleteResourceValueConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.DeleteResourceValueConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete resource value - config method over HTTP. - - Args: - request (~.securitycenter_service.DeleteResourceValueConfigRequest): - The request object. Request message to delete resource - value config - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/resourceValueConfigs/*}', - }, -{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/locations/*/resourceValueConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_resource_value_config(request, metadata) - pb_request = securitycenter_service.DeleteResourceValueConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 _GetBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("GetBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> bigquery_export.BigQueryExport: - r"""Call the get big query export method over HTTP. - - Args: - request (~.securitycenter_service.GetBigQueryExportRequest): - The request object. Request message for retrieving a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.bigquery_export.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/locations/*/bigQueryExports/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=folders/*/locations/*/bigQueryExports/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/bigQueryExports/*}', - }, - ] - request, metadata = self._interceptor.pre_get_big_query_export(request, metadata) - pb_request = securitycenter_service.GetBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = bigquery_export.BigQueryExport() - pb_resp = bigquery_export.BigQueryExport.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_big_query_export(resp) - return resp - - class _GetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{resource=organizations/*/sources/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _GetMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> mute_config.MuteConfig: - r"""Call the get mute config method over HTTP. - - Args: - request (~.securitycenter_service.GetMuteConfigRequest): - The request object. Request message for retrieving a mute - config. If no location is specified, - default is global. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.mute_config.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=folders/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=folders/*/locations/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/muteConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/muteConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_mute_config(request, metadata) - pb_request = securitycenter_service.GetMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = mute_config.MuteConfig() - pb_resp = mute_config.MuteConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_mute_config(resp) - return resp - - class _GetNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> notification_config.NotificationConfig: - r"""Call the get notification config method over HTTP. - - Args: - request (~.securitycenter_service.GetNotificationConfigRequest): - The request object. Request message for getting a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/locations/*/notificationConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=folders/*/locations/*/notificationConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=projects/*/locations/*/notificationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_notification_config(request, metadata) - pb_request = securitycenter_service.GetNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = notification_config.NotificationConfig() - pb_resp = notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_notification_config(resp) - return resp - - class _GetResourceValueConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("GetResourceValueConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetResourceValueConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resource_value_config.ResourceValueConfig: - r"""Call the get resource value config method over HTTP. - - Args: - request (~.securitycenter_service.GetResourceValueConfigRequest): - The request object. Request message to get resource value - config - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resource_value_config.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/resourceValueConfigs/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/locations/*/resourceValueConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_resource_value_config(request, metadata) - pb_request = securitycenter_service.GetResourceValueConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resource_value_config.ResourceValueConfig() - pb_resp = resource_value_config.ResourceValueConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_resource_value_config(resp) - return resp - - class _GetSimulation(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSimulation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSimulationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> simulation.Simulation: - r"""Call the get simulation method over HTTP. - - Args: - request (~.securitycenter_service.GetSimulationRequest): - The request object. Request message for getting - simulation. Simulation name can include - "latest" to retrieve the latest - simulation For example, - "organizations/123/simulations/latest". - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.simulation.Simulation: - Attack path simulation - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/simulations/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/locations/*/simulations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_simulation(request, metadata) - pb_request = securitycenter_service.GetSimulationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = simulation.Simulation() - pb_resp = simulation.Simulation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_simulation(resp) - return resp - - class _GetSource(SecurityCenterRestStub): - def __hash__(self): - return hash("GetSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> source.Source: - r"""Call the get source method over HTTP. - - Args: - request (~.securitycenter_service.GetSourceRequest): - The request object. Request message for getting a source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/sources/*}', - }, - ] - request, metadata = self._interceptor.pre_get_source(request, metadata) - pb_request = securitycenter_service.GetSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = source.Source() - pb_resp = source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_source(resp) - return resp - - class _GetValuedResource(SecurityCenterRestStub): - def __hash__(self): - return hash("GetValuedResource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GetValuedResourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> valued_resource.ValuedResource: - r"""Call the get valued resource method over HTTP. - - Args: - request (~.securitycenter_service.GetValuedResourceRequest): - The request object. Request message for getting a valued - resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.valued_resource.ValuedResource: - A resource that is determined to have - value to a user's system - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/simulations/*/valuedResources/*}', - }, -{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/locations/*/simulations/*/valuedResources/*}', - }, - ] - request, metadata = self._interceptor.pre_get_valued_resource(request, metadata) - pb_request = securitycenter_service.GetValuedResourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = valued_resource.ValuedResource() - pb_resp = valued_resource.ValuedResource.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_valued_resource(resp) - return resp - - class _GroupFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("GroupFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.GroupFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.GroupFindingsResponse: - r"""Call the group findings method over HTTP. - - Args: - request (~.securitycenter_service.GroupFindingsRequest): - The request object. Request message for grouping by - findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.GroupFindingsResponse: - Response message for group by - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=organizations/*/sources/*/locations/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=folders/*/sources/*/locations/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/sources/*}/findings:group', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{parent=projects/*/sources/*/locations/*}/findings:group', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_group_findings(request, metadata) - pb_request = securitycenter_service.GroupFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.GroupFindingsResponse() - pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_group_findings(resp) - return resp - - class _ListAttackPaths(SecurityCenterRestStub): - def __hash__(self): - return hash("ListAttackPaths") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListAttackPathsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListAttackPathsResponse: - r"""Call the list attack paths method over HTTP. - - Args: - request (~.securitycenter_service.ListAttackPathsRequest): - The request object. Request message for listing the - attack paths for a given simulation or - valued resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListAttackPathsResponse: - Response message for listing the - attack paths for a given simulation or - valued resource. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/simulations/*}/attackPaths', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/simulations/*/valuedResources/*}/attackPaths', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/locations/*/simulations/*/valuedResources/*}/attackPaths', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/simulations/*/attackExposureResults/*}/attackPaths', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/locations/*/simulations/*/attackExposureResults/*}/attackPaths', - }, - ] - request, metadata = self._interceptor.pre_list_attack_paths(request, metadata) - pb_request = securitycenter_service.ListAttackPathsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListAttackPathsResponse() - pb_resp = securitycenter_service.ListAttackPathsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_attack_paths(resp) - return resp - - class _ListBigQueryExports(SecurityCenterRestStub): - def __hash__(self): - return hash("ListBigQueryExports") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListBigQueryExportsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListBigQueryExportsResponse: - r"""Call the list big query exports method over HTTP. - - Args: - request (~.securitycenter_service.ListBigQueryExportsRequest): - The request object. Request message for listing BigQuery - exports at a given scope e.g. - organization, folder or 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: - ~.securitycenter_service.ListBigQueryExportsResponse: - Response message for listing BigQuery - exports. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/locations/*}/bigQueryExports', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*/locations/*}/bigQueryExports', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/bigQueryExports', - }, - ] - request, metadata = self._interceptor.pre_list_big_query_exports(request, metadata) - pb_request = securitycenter_service.ListBigQueryExportsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListBigQueryExportsResponse() - pb_resp = securitycenter_service.ListBigQueryExportsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_big_query_exports(resp) - return resp - - class _ListFindings(SecurityCenterRestStub): - def __hash__(self): - return hash("ListFindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListFindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListFindingsResponse: - r"""Call the list findings method over HTTP. - - Args: - request (~.securitycenter_service.ListFindingsRequest): - The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListFindingsResponse: - Response message for listing - findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/sources/*/locations/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*/sources/*/locations/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/sources/*}/findings', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/sources/*/locations/*}/findings', - }, - ] - request, metadata = self._interceptor.pre_list_findings(request, metadata) - pb_request = securitycenter_service.ListFindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListFindingsResponse() - pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_findings(resp) - return resp - - class _ListMuteConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListMuteConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListMuteConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListMuteConfigsResponse: - r"""Call the list mute configs method over HTTP. - - Args: - request (~.securitycenter_service.ListMuteConfigsRequest): - The request object. Request message for listing mute - configs at a given scope e.g. - organization, folder or project. If no - location is specified, default is - global. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListMuteConfigsResponse: - Response message for listing mute - configs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/locations/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*/locations/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*}/muteConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/muteConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_mute_configs(request, metadata) - pb_request = securitycenter_service.ListMuteConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListMuteConfigsResponse() - pb_resp = securitycenter_service.ListMuteConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_mute_configs(resp) - return resp - - class _ListNotificationConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListNotificationConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListNotificationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListNotificationConfigsResponse: - r"""Call the list notification configs method over HTTP. - - Args: - request (~.securitycenter_service.ListNotificationConfigsRequest): - The request object. Request message for listing - notification configs. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListNotificationConfigsResponse: - Response message for listing - notification configs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/locations/*}/notificationConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*/locations/*}/notificationConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*/locations/*}/notificationConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_notification_configs(request, metadata) - pb_request = securitycenter_service.ListNotificationConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListNotificationConfigsResponse() - pb_resp = securitycenter_service.ListNotificationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_notification_configs(resp) - return resp - - class _ListResourceValueConfigs(SecurityCenterRestStub): - def __hash__(self): - return hash("ListResourceValueConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListResourceValueConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListResourceValueConfigsResponse: - r"""Call the list resource value - configs method over HTTP. - - Args: - request (~.securitycenter_service.ListResourceValueConfigsRequest): - The request object. Request message to list resource - value configs of a parent - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListResourceValueConfigsResponse: - Response message to list resource - value configs - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*}/resourceValueConfigs', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/locations/*}/resourceValueConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_resource_value_configs(request, metadata) - pb_request = securitycenter_service.ListResourceValueConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListResourceValueConfigsResponse() - pb_resp = securitycenter_service.ListResourceValueConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_resource_value_configs(resp) - return resp - - class _ListSources(SecurityCenterRestStub): - def __hash__(self): - return hash("ListSources") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListSourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListSourcesResponse: - r"""Call the list sources method over HTTP. - - Args: - request (~.securitycenter_service.ListSourcesRequest): - The request object. Request message for listing sources. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListSourcesResponse: - Response message for listing sources. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*}/sources', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=folders/*}/sources', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=projects/*}/sources', - }, - ] - request, metadata = self._interceptor.pre_list_sources(request, metadata) - pb_request = securitycenter_service.ListSourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListSourcesResponse() - pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_sources(resp) - return resp - - class _ListValuedResources(SecurityCenterRestStub): - def __hash__(self): - return hash("ListValuedResources") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.ListValuedResourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> securitycenter_service.ListValuedResourcesResponse: - r"""Call the list valued resources method over HTTP. - - Args: - request (~.securitycenter_service.ListValuedResourcesRequest): - The request object. Request message for listing the - valued resources for a given simulation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.securitycenter_service.ListValuedResourcesResponse: - Response message for listing the - valued resources for a given simulation. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/simulations/*}/valuedResources', - }, -{ - 'method': 'get', - 'uri': '/v2/{parent=organizations/*/simulations/*/attackExposureResults/*}/valuedResources', - }, - ] - request, metadata = self._interceptor.pre_list_valued_resources(request, metadata) - pb_request = securitycenter_service.ListValuedResourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = securitycenter_service.ListValuedResourcesResponse() - pb_resp = securitycenter_service.ListValuedResourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_valued_resources(resp) - return resp - - class _SetFindingState(SecurityCenterRestStub): - def __hash__(self): - return hash("SetFindingState") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SetFindingStateRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the set finding state method over HTTP. - - Args: - request (~.securitycenter_service.SetFindingStateRequest): - The request object. Request message for updating a - finding's state. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=organizations/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=organizations/*/sources/*/locations/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=folders/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=folders/*/sources/*/locations/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/sources/*/findings/*}:setState', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/sources/*/locations/*/findings/*}:setState', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_finding_state(request, metadata) - pb_request = securitycenter_service.SetFindingStateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_set_finding_state(resp) - return resp - - class _SetIamPolicy(SecurityCenterRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{resource=organizations/*/sources/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _SetMute(SecurityCenterRestStub): - def __hash__(self): - return hash("SetMute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.SetMuteRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> finding.Finding: - r"""Call the set mute method over HTTP. - - Args: - request (~.securitycenter_service.SetMuteRequest): - The request object. Request message for updating a - finding's mute status. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=organizations/*/sources/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=organizations/*/sources/*/locations/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=folders/*/sources/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=folders/*/sources/*/locations/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/sources/*/findings/*}:setMute', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v2/{name=projects/*/sources/*/locations/*/findings/*}:setMute', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_mute(request, metadata) - pb_request = securitycenter_service.SetMuteRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, 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_set_mute(resp) - return resp - - class _TestIamPermissions(SecurityCenterRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - 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. 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{resource=organizations/*/sources/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UpdateBigQueryExport(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateBigQueryExport") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateBigQueryExportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> bigquery_export.BigQueryExport: - r"""Call the update big query export method over HTTP. - - Args: - request (~.securitycenter_service.UpdateBigQueryExportRequest): - The request object. Request message for updating a - BigQuery export. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.bigquery_export.BigQueryExport: - Configures how to deliver Findings to - BigQuery Instance. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{big_query_export.name=organizations/*/locations/*/bigQueryExports/*}', - 'body': 'big_query_export', - }, -{ - 'method': 'patch', - 'uri': '/v2/{big_query_export.name=folders/*/locations/*/bigQueryExports/*}', - 'body': 'big_query_export', - }, -{ - 'method': 'patch', - 'uri': '/v2/{big_query_export.name=projects/*/locations/*/bigQueryExports/*}', - 'body': 'big_query_export', - }, - ] - request, metadata = self._interceptor.pre_update_big_query_export(request, metadata) - pb_request = securitycenter_service.UpdateBigQueryExportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = bigquery_export.BigQueryExport() - pb_resp = bigquery_export.BigQueryExport.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_big_query_export(resp) - return resp - - class _UpdateExternalSystem(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateExternalSystem") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateExternalSystemRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_external_system.ExternalSystem: - r"""Call the update external system method over HTTP. - - Args: - request (~.securitycenter_service.UpdateExternalSystemRequest): - The request object. Request message for updating a - ExternalSystem resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_external_system.ExternalSystem: - Representation of third party - SIEM/SOAR fields within SCC. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v2/{external_system.name=organizations/*/sources/*/locations/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v2/{external_system.name=folders/*/sources/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v2/{external_system.name=folders/*/sources/*/locations/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v2/{external_system.name=projects/*/sources/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, -{ - 'method': 'patch', - 'uri': '/v2/{external_system.name=projects/*/sources/*/locations/*/findings/*/externalSystems/*}', - 'body': 'external_system', - }, - ] - request, metadata = self._interceptor.pre_update_external_system(request, metadata) - pb_request = securitycenter_service.UpdateExternalSystemRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_external_system.ExternalSystem() - pb_resp = gcs_external_system.ExternalSystem.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_external_system(resp) - return resp - - class _UpdateFinding(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateFinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateFindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_finding.Finding: - r"""Call the update finding method over HTTP. - - Args: - request (~.securitycenter_service.UpdateFindingRequest): - The request object. Request message for updating or - creating a finding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{finding.name=organizations/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v2/{finding.name=organizations/*/sources/*/locations/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v2/{finding.name=folders/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v2/{finding.name=folders/*/sources/*/locations/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v2/{finding.name=projects/*/sources/*/findings/*}', - 'body': 'finding', - }, -{ - 'method': 'patch', - 'uri': '/v2/{finding.name=projects/*/sources/*/locations/*/findings/*}', - 'body': 'finding', - }, - ] - request, metadata = self._interceptor.pre_update_finding(request, metadata) - pb_request = securitycenter_service.UpdateFindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_finding.Finding() - pb_resp = gcs_finding.Finding.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_finding(resp) - return resp - - class _UpdateMuteConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateMuteConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateMuteConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_mute_config.MuteConfig: - r"""Call the update mute config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateMuteConfigRequest): - The request object. Request message for updating a mute - config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_mute_config.MuteConfig: - A mute config is a Cloud SCC resource - that contains the configuration to mute - create/update events of findings. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{mute_config.name=organizations/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{mute_config.name=organizations/*/locations/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{mute_config.name=folders/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{mute_config.name=folders/*/locations/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{mute_config.name=projects/*/muteConfigs/*}', - 'body': 'mute_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{mute_config.name=projects/*/locations/*/muteConfigs/*}', - 'body': 'mute_config', - }, - ] - request, metadata = self._interceptor.pre_update_mute_config(request, metadata) - pb_request = securitycenter_service.UpdateMuteConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_mute_config.MuteConfig() - pb_resp = gcs_mute_config.MuteConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_mute_config(resp) - return resp - - class _UpdateNotificationConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateNotificationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateNotificationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_notification_config.NotificationConfig: - r"""Call the update notification - config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateNotificationConfigRequest): - The request object. Request message for updating a - notification config. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{notification_config.name=organizations/*/locations/*/notificationConfigs/*}', - 'body': 'notification_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{notification_config.name=folders/*/locations/*/notificationConfigs/*}', - 'body': 'notification_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{notification_config.name=projects/*/locations/*/notificationConfigs/*}', - 'body': 'notification_config', - }, - ] - request, metadata = self._interceptor.pre_update_notification_config(request, metadata) - pb_request = securitycenter_service.UpdateNotificationConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_notification_config.NotificationConfig() - pb_resp = gcs_notification_config.NotificationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_notification_config(resp) - return resp - - class _UpdateResourceValueConfig(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateResourceValueConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateResourceValueConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_resource_value_config.ResourceValueConfig: - r"""Call the update resource value - config method over HTTP. - - Args: - request (~.securitycenter_service.UpdateResourceValueConfigRequest): - The request object. Request message to update resource - value config - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_resource_value_config.ResourceValueConfig: - A resource value configuration (RVC) - is a mapping configuration of user's - resources to resource values. Used in - Attack path simulations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{resource_value_config.name=organizations/*/resourceValueConfigs/*}', - 'body': 'resource_value_config', - }, -{ - 'method': 'patch', - 'uri': '/v2/{resource_value_config.name=organizations/*/locations/*/resourceValueConfigs/*}', - 'body': 'resource_value_config', - }, - ] - request, metadata = self._interceptor.pre_update_resource_value_config(request, metadata) - pb_request = securitycenter_service.UpdateResourceValueConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_resource_value_config.ResourceValueConfig() - pb_resp = gcs_resource_value_config.ResourceValueConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_resource_value_config(resp) - return resp - - class _UpdateSecurityMarks(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSecurityMarks") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSecurityMarksRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_security_marks.SecurityMarks: - r"""Call the update security marks method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSecurityMarksRequest): - The request object. Request message for updating a - SecurityMarks resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=organizations/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=organizations/*/sources/*/locations/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=folders/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=folders/*/sources/*/locations/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=projects/*/assets/*/securityMarks}', - 'body': 'security_marks', - }, -{ - 'method': 'patch', - 'uri': '/v2/{security_marks.name=projects/*/sources/*/locations/*/findings/*/securityMarks}', - 'body': 'security_marks', - }, - ] - request, metadata = self._interceptor.pre_update_security_marks(request, metadata) - pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_security_marks.SecurityMarks() - pb_resp = gcs_security_marks.SecurityMarks.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_security_marks(resp) - return resp - - class _UpdateSource(SecurityCenterRestStub): - def __hash__(self): - return hash("UpdateSource") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: securitycenter_service.UpdateSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcs_source.Source: - r"""Call the update source method over HTTP. - - Args: - request (~.securitycenter_service.UpdateSourceRequest): - The request object. Request message for updating a - source. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v2/{source.name=organizations/*/sources/*}', - 'body': 'source', - }, - ] - request, metadata = self._interceptor.pre_update_source(request, metadata) - pb_request = securitycenter_service.UpdateSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcs_source.Source() - pb_resp = gcs_source.Source.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_source(resp) - return resp - - @property - def batch_create_resource_value_configs(self) -> Callable[ - [securitycenter_service.BatchCreateResourceValueConfigsRequest], - securitycenter_service.BatchCreateResourceValueConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchCreateResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def bulk_mute_findings(self) -> Callable[ - [securitycenter_service.BulkMuteFindingsRequest], - 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._BulkMuteFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_big_query_export(self) -> Callable[ - [securitycenter_service.CreateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_mute_config(self) -> Callable[ - [securitycenter_service.CreateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_big_query_export(self) -> Callable[ - [securitycenter_service.DeleteBigQueryExportRequest], - 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._DeleteBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_mute_config(self) -> Callable[ - [securitycenter_service.DeleteMuteConfigRequest], - 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._DeleteMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - 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._DeleteNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_resource_value_config(self) -> Callable[ - [securitycenter_service.DeleteResourceValueConfigRequest], - 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._DeleteResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_big_query_export(self) -> Callable[ - [securitycenter_service.GetBigQueryExportRequest], - bigquery_export.BigQueryExport]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_mute_config(self) -> Callable[ - [securitycenter_service.GetMuteConfigRequest], - mute_config.MuteConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_resource_value_config(self) -> Callable[ - [securitycenter_service.GetResourceValueConfigRequest], - resource_value_config.ResourceValueConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_simulation(self) -> Callable[ - [securitycenter_service.GetSimulationRequest], - simulation.Simulation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSimulation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_valued_resource(self) -> Callable[ - [securitycenter_service.GetValuedResourceRequest], - valued_resource.ValuedResource]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetValuedResource(self._session, self._host, self._interceptor) # type: ignore - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GroupFindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_attack_paths(self) -> Callable[ - [securitycenter_service.ListAttackPathsRequest], - securitycenter_service.ListAttackPathsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListAttackPaths(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_big_query_exports(self) -> Callable[ - [securitycenter_service.ListBigQueryExportsRequest], - securitycenter_service.ListBigQueryExportsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListBigQueryExports(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.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_mute_configs(self) -> Callable[ - [securitycenter_service.ListMuteConfigsRequest], - securitycenter_service.ListMuteConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListMuteConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListNotificationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_resource_value_configs(self) -> Callable[ - [securitycenter_service.ListResourceValueConfigsRequest], - securitycenter_service.ListResourceValueConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSources(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_valued_resources(self) -> Callable[ - [securitycenter_service.ListValuedResourcesRequest], - securitycenter_service.ListValuedResourcesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListValuedResources(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_mute(self) -> Callable[ - [securitycenter_service.SetMuteRequest], - 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._SetMute(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_big_query_export(self) -> Callable[ - [securitycenter_service.UpdateBigQueryExportRequest], - bigquery_export.BigQueryExport]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_external_system(self) -> Callable[ - [securitycenter_service.UpdateExternalSystemRequest], - gcs_external_system.ExternalSystem]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateExternalSystem(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_mute_config(self) -> Callable[ - [securitycenter_service.UpdateMuteConfigRequest], - gcs_mute_config.MuteConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateMuteConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_resource_value_config(self) -> Callable[ - [securitycenter_service.UpdateResourceValueConfigRequest], - gcs_resource_value_config.ResourceValueConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v2/{name=organizations/*/operations/*}:cancel', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In 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(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v2/{name=organizations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In 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(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), 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(SecurityCenterRestStub): - 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: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v2/{name=organizations/*/operations}', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SecurityCenterRestTransport', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.py deleted file mode 100644 index bb1db5459f13..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/__init__.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. -# -from .access import ( - Access, - Geolocation, - ServiceAccountDelegationInfo, -) -from .application import ( - Application, -) -from .attack_exposure import ( - AttackExposure, -) -from .attack_path import ( - AttackPath, -) -from .backup_disaster_recovery import ( - BackupDisasterRecovery, -) -from .bigquery_export import ( - BigQueryExport, -) -from .cloud_armor import ( - AdaptiveProtection, - Attack, - CloudArmor, - Requests, - SecurityPolicy, -) -from .cloud_dlp_data_profile import ( - CloudDlpDataProfile, -) -from .cloud_dlp_inspection import ( - CloudDlpInspection, -) -from .compliance import ( - Compliance, -) -from .connection import ( - Connection, -) -from .contact_details import ( - Contact, - ContactDetails, -) -from .container import ( - Container, -) -from .database import ( - Database, -) -from .exfiltration import ( - ExfilResource, - Exfiltration, -) -from .external_system import ( - ExternalSystem, -) -from .file import ( - File, -) -from .finding import ( - Finding, -) -from .folder import ( - Folder, -) -from .group_membership import ( - GroupMembership, -) -from .iam_binding import ( - IamBinding, -) -from .indicator import ( - Indicator, -) -from .kernel_rootkit import ( - KernelRootkit, -) -from .kubernetes import ( - Kubernetes, -) -from .label import ( - Label, -) -from .load_balancer import ( - LoadBalancer, -) -from .log_entry import ( - CloudLoggingEntry, - LogEntry, -) -from .mitre_attack import ( - MitreAttack, -) -from .mute_config import ( - MuteConfig, -) -from .notebook import ( - Notebook, -) -from .notification_config import ( - NotificationConfig, -) -from .notification_message import ( - NotificationMessage, -) -from .org_policy import ( - OrgPolicy, -) -from .process import ( - EnvironmentVariable, - Process, -) -from .resource import ( - AwsMetadata, - AzureMetadata, - GcpMetadata, - Resource, - ResourcePath, - CloudProvider, -) -from .resource_value_config import ( - ResourceValueConfig, - ResourceValue, -) -from .security_marks import ( - SecurityMarks, -) -from .security_posture import ( - SecurityPosture, -) -from .securitycenter_service import ( - BatchCreateResourceValueConfigsRequest, - BatchCreateResourceValueConfigsResponse, - BulkMuteFindingsRequest, - BulkMuteFindingsResponse, - CreateBigQueryExportRequest, - CreateFindingRequest, - CreateMuteConfigRequest, - CreateNotificationConfigRequest, - CreateResourceValueConfigRequest, - CreateSourceRequest, - DeleteBigQueryExportRequest, - DeleteMuteConfigRequest, - DeleteNotificationConfigRequest, - DeleteResourceValueConfigRequest, - GetBigQueryExportRequest, - GetMuteConfigRequest, - GetNotificationConfigRequest, - GetResourceValueConfigRequest, - GetSimulationRequest, - GetSourceRequest, - GetValuedResourceRequest, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListAttackPathsRequest, - ListAttackPathsResponse, - ListBigQueryExportsRequest, - ListBigQueryExportsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListMuteConfigsRequest, - ListMuteConfigsResponse, - ListNotificationConfigsRequest, - ListNotificationConfigsResponse, - ListResourceValueConfigsRequest, - ListResourceValueConfigsResponse, - ListSourcesRequest, - ListSourcesResponse, - ListValuedResourcesRequest, - ListValuedResourcesResponse, - SetFindingStateRequest, - SetMuteRequest, - UpdateBigQueryExportRequest, - UpdateExternalSystemRequest, - UpdateFindingRequest, - UpdateMuteConfigRequest, - UpdateNotificationConfigRequest, - UpdateResourceValueConfigRequest, - UpdateSecurityMarksRequest, - UpdateSourceRequest, -) -from .simulation import ( - Simulation, -) -from .source import ( - Source, -) -from .toxic_combination import ( - ToxicCombination, -) -from .valued_resource import ( - ResourceValueConfigMetadata, - ValuedResource, -) -from .vulnerability import ( - Cve, - Cvssv3, - Package, - Reference, - SecurityBulletin, - Vulnerability, -) - -__all__ = ( - 'Access', - 'Geolocation', - 'ServiceAccountDelegationInfo', - 'Application', - 'AttackExposure', - 'AttackPath', - 'BackupDisasterRecovery', - 'BigQueryExport', - 'AdaptiveProtection', - 'Attack', - 'CloudArmor', - 'Requests', - 'SecurityPolicy', - 'CloudDlpDataProfile', - 'CloudDlpInspection', - 'Compliance', - 'Connection', - 'Contact', - 'ContactDetails', - 'Container', - 'Database', - 'ExfilResource', - 'Exfiltration', - 'ExternalSystem', - 'File', - 'Finding', - 'Folder', - 'GroupMembership', - 'IamBinding', - 'Indicator', - 'KernelRootkit', - 'Kubernetes', - 'Label', - 'LoadBalancer', - 'CloudLoggingEntry', - 'LogEntry', - 'MitreAttack', - 'MuteConfig', - 'Notebook', - 'NotificationConfig', - 'NotificationMessage', - 'OrgPolicy', - 'EnvironmentVariable', - 'Process', - 'AwsMetadata', - 'AzureMetadata', - 'GcpMetadata', - 'Resource', - 'ResourcePath', - 'CloudProvider', - 'ResourceValueConfig', - 'ResourceValue', - 'SecurityMarks', - 'SecurityPosture', - 'BatchCreateResourceValueConfigsRequest', - 'BatchCreateResourceValueConfigsResponse', - 'BulkMuteFindingsRequest', - 'BulkMuteFindingsResponse', - 'CreateBigQueryExportRequest', - 'CreateFindingRequest', - 'CreateMuteConfigRequest', - 'CreateNotificationConfigRequest', - 'CreateResourceValueConfigRequest', - 'CreateSourceRequest', - 'DeleteBigQueryExportRequest', - 'DeleteMuteConfigRequest', - 'DeleteNotificationConfigRequest', - 'DeleteResourceValueConfigRequest', - 'GetBigQueryExportRequest', - 'GetMuteConfigRequest', - 'GetNotificationConfigRequest', - 'GetResourceValueConfigRequest', - 'GetSimulationRequest', - 'GetSourceRequest', - 'GetValuedResourceRequest', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAttackPathsRequest', - 'ListAttackPathsResponse', - 'ListBigQueryExportsRequest', - 'ListBigQueryExportsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListMuteConfigsRequest', - 'ListMuteConfigsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListResourceValueConfigsRequest', - 'ListResourceValueConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListValuedResourcesRequest', - 'ListValuedResourcesResponse', - 'SetFindingStateRequest', - 'SetMuteRequest', - 'UpdateBigQueryExportRequest', - 'UpdateExternalSystemRequest', - 'UpdateFindingRequest', - 'UpdateMuteConfigRequest', - 'UpdateNotificationConfigRequest', - 'UpdateResourceValueConfigRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Simulation', - 'Source', - 'ToxicCombination', - 'ResourceValueConfigMetadata', - 'ValuedResource', - 'Cve', - 'Cvssv3', - 'Package', - 'Reference', - 'SecurityBulletin', - 'Vulnerability', -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py deleted file mode 100644 index e617c4170012..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/access.py +++ /dev/null @@ -1,193 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v2', - manifest={ - 'Access', - 'ServiceAccountDelegationInfo', - 'Geolocation', - }, -) - - -class Access(proto.Message): - r"""Represents an access event. - - Attributes: - principal_email (str): - Associated email, such as "foo@google.com". - - The email address of the authenticated user or a service - account acting on behalf of a third party principal making - the request. For third party identity callers, the - ``principal_subject`` field is populated instead of this - field. For privacy reasons, the principal email address is - sometimes redacted. For more information, see `Caller - identities in audit - logs `__. - caller_ip (str): - Caller's IP address, such as "1.1.1.1". - caller_ip_geo (google.cloud.securitycenter_v2.types.Geolocation): - The caller IP's geolocation, which identifies - where the call came from. - user_agent_family (str): - Type of user agent associated with the - finding. For example, an operating system shell - or an embedded or standalone application. - user_agent (str): - The caller's user agent string associated - with the finding. - service_name (str): - This is the API service that the service - account made a call to, e.g. - "iam.googleapis.com". - method_name (str): - The method that the service account called, - e.g. "SetIamPolicy". - principal_subject (str): - A string that represents the principal_subject that is - associated with the identity. Unlike ``principal_email``, - ``principal_subject`` supports principals that aren't - associated with email addresses, such as third party - principals. For most identities, the format is - ``principal://iam.googleapis.com/{identity pool name}/subject/{subject}``. - Some GKE identities, such as GKE_WORKLOAD, FREEFORM, and - GKE_HUB_WORKLOAD, still use the legacy format - ``serviceAccount:{identity pool name}[{subject}]``. - service_account_key_name (str): - The name of the service account key that was used to create - or exchange credentials when authenticating the service - account that made the request. This is a scheme-less URI - full resource name. For example: - - "//iam.googleapis.com/projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}". - service_account_delegation_info (MutableSequence[google.cloud.securitycenter_v2.types.ServiceAccountDelegationInfo]): - The identity delegation history of an authenticated service - account that made the request. The - ``serviceAccountDelegationInfo[]`` object contains - information about the real authorities that try to access - Google Cloud resources by delegating on a service account. - When multiple authorities are present, they are guaranteed - to be sorted based on the original ordering of the identity - delegation events. - user_name (str): - A string that represents a username. The - username provided depends on the type of the - finding and is likely not an IAM principal. For - example, this can be a system username if the - finding is related to a virtual machine, or it - can be an application login username. - """ - - principal_email: str = proto.Field( - proto.STRING, - number=1, - ) - caller_ip: str = proto.Field( - proto.STRING, - number=2, - ) - caller_ip_geo: 'Geolocation' = proto.Field( - proto.MESSAGE, - number=3, - message='Geolocation', - ) - user_agent_family: str = proto.Field( - proto.STRING, - number=4, - ) - user_agent: str = proto.Field( - proto.STRING, - number=5, - ) - service_name: str = proto.Field( - proto.STRING, - number=6, - ) - method_name: str = proto.Field( - proto.STRING, - number=7, - ) - principal_subject: str = proto.Field( - proto.STRING, - number=8, - ) - service_account_key_name: str = proto.Field( - proto.STRING, - number=9, - ) - service_account_delegation_info: MutableSequence['ServiceAccountDelegationInfo'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='ServiceAccountDelegationInfo', - ) - user_name: str = proto.Field( - proto.STRING, - number=11, - ) - - -class ServiceAccountDelegationInfo(proto.Message): - r"""Identity delegation history of an authenticated service - account. - - Attributes: - principal_email (str): - The email address of a Google account. - principal_subject (str): - A string representing the principal_subject associated with - the identity. As compared to ``principal_email``, supports - principals that aren't associated with email addresses, such - as third party principals. For most identities, the format - will be - ``principal://iam.googleapis.com/{identity pool name}/subjects/{subject}`` - except for some GKE identities (GKE_WORKLOAD, FREEFORM, - GKE_HUB_WORKLOAD) that are still in the legacy format - ``serviceAccount:{identity pool name}[{subject}]`` - """ - - principal_email: str = proto.Field( - proto.STRING, - number=1, - ) - principal_subject: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Geolocation(proto.Message): - r"""Represents a geographical location for a given access. - - Attributes: - region_code (str): - A CLDR. - """ - - region_code: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.py deleted file mode 100644 index b77f5993987b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/application.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Application', - }, -) - - -class Application(proto.Message): - r"""Represents an application associated with a finding. - - Attributes: - base_uri (str): - The base URI that identifies the network location of the - application in which the vulnerability was detected. For - example, ``http://example.com``. - full_uri (str): - The full URI with payload that could be used to reproduce - the vulnerability. For example, - ``http://example.com?p=aMmYgI6H``. - """ - - base_uri: str = proto.Field( - proto.STRING, - number=1, - ) - full_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.py deleted file mode 100644 index 600d1a66d91e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_exposure.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 timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'AttackExposure', - }, -) - - -class AttackExposure(proto.Message): - r"""An attack exposure contains the results of an attack path - simulation run. - - Attributes: - score (float): - A number between 0 (inclusive) and infinity - that represents how important this finding is to - remediate. The higher the score, the more - important it is to remediate. - latest_calculation_time (google.protobuf.timestamp_pb2.Timestamp): - The most recent time the attack exposure was - updated on this finding. - attack_exposure_result (str): - The resource name of the attack path simulation result that - contains the details regarding this attack exposure score. - Example: - ``organizations/123/simulations/456/attackExposureResults/789`` - state (google.cloud.securitycenter_v2.types.AttackExposure.State): - Output only. What state this AttackExposure - is in. This captures whether or not an attack - exposure has been calculated or not. - exposed_high_value_resources_count (int): - The number of high value resources that are - exposed as a result of this finding. - exposed_medium_value_resources_count (int): - The number of medium value resources that are - exposed as a result of this finding. - exposed_low_value_resources_count (int): - The number of high value resources that are - exposed as a result of this finding. - """ - class State(proto.Enum): - r"""This enum defines the various states an AttackExposure can be - in. - - Values: - STATE_UNSPECIFIED (0): - The state is not specified. - CALCULATED (1): - The attack exposure has been calculated. - NOT_CALCULATED (2): - The attack exposure has not been calculated. - """ - STATE_UNSPECIFIED = 0 - CALCULATED = 1 - NOT_CALCULATED = 2 - - score: float = proto.Field( - proto.DOUBLE, - number=1, - ) - latest_calculation_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - attack_exposure_result: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - exposed_high_value_resources_count: int = proto.Field( - proto.INT32, - number=5, - ) - exposed_medium_value_resources_count: int = proto.Field( - proto.INT32, - number=6, - ) - exposed_low_value_resources_count: int = proto.Field( - proto.INT32, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py deleted file mode 100644 index 433afe1a5eee..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/attack_path.py +++ /dev/null @@ -1,223 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v2', - manifest={ - 'AttackPath', - }, -) - - -class AttackPath(proto.Message): - r"""A path that an attacker could take to reach an exposed - resource. - - Attributes: - name (str): - The attack path name, for example, - ``organizations/12/simulations/34/valuedResources/56/attackPaths/78`` - path_nodes (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode]): - A list of nodes that exist in this attack - path. - edges (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathEdge]): - A list of the edges between nodes in this - attack path. - """ - - class AttackPathNode(proto.Message): - r"""Represents one point that an attacker passes through in this - attack path. - - Attributes: - resource (str): - The name of the resource at this point in the attack path. - The format of the name follows the Cloud Asset Inventory - `resource name - format `__ - resource_type (str): - The `supported resource - type `__ - display_name (str): - Human-readable name of this resource. - associated_findings (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.PathNodeAssociatedFinding]): - The findings associated with this node in the - attack path. - uuid (str): - Unique id of the attack path node. - attack_steps (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.AttackStepNode]): - A list of attack step nodes that exist in - this attack path node. - """ - class NodeType(proto.Enum): - r"""The type of the incoming attack step node. - - Values: - NODE_TYPE_UNSPECIFIED (0): - Type not specified - NODE_TYPE_AND (1): - Incoming edge joined with AND - NODE_TYPE_OR (2): - Incoming edge joined with OR - NODE_TYPE_DEFENSE (3): - Incoming edge is defense - NODE_TYPE_ATTACKER (4): - Incoming edge is attacker - """ - NODE_TYPE_UNSPECIFIED = 0 - NODE_TYPE_AND = 1 - NODE_TYPE_OR = 2 - NODE_TYPE_DEFENSE = 3 - NODE_TYPE_ATTACKER = 4 - - class PathNodeAssociatedFinding(proto.Message): - r"""A finding that is associated with this node in the attack - path. - - Attributes: - canonical_finding (str): - Canonical name of the associated findings. Example: - ``organizations/123/sources/456/findings/789`` - finding_category (str): - The additional taxonomy group within findings - from a given source. - name (str): - Full resource name of the finding. - """ - - canonical_finding: str = proto.Field( - proto.STRING, - number=1, - ) - finding_category: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - class AttackStepNode(proto.Message): - r"""Detailed steps the attack can take between path nodes. - - Attributes: - uuid (str): - Unique ID for one Node - type_ (google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.NodeType): - Attack step type. Can be either AND, OR or - DEFENSE - display_name (str): - User friendly name of the attack step - labels (MutableMapping[str, str]): - Attack step labels for metadata - description (str): - Attack step description - """ - - uuid: str = proto.Field( - proto.STRING, - number=1, - ) - type_: 'AttackPath.AttackPathNode.NodeType' = proto.Field( - proto.ENUM, - number=2, - enum='AttackPath.AttackPathNode.NodeType', - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - description: str = proto.Field( - proto.STRING, - number=5, - ) - - resource: str = proto.Field( - proto.STRING, - number=1, - ) - resource_type: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - associated_findings: MutableSequence['AttackPath.AttackPathNode.PathNodeAssociatedFinding'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='AttackPath.AttackPathNode.PathNodeAssociatedFinding', - ) - uuid: str = proto.Field( - proto.STRING, - number=5, - ) - attack_steps: MutableSequence['AttackPath.AttackPathNode.AttackStepNode'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='AttackPath.AttackPathNode.AttackStepNode', - ) - - class AttackPathEdge(proto.Message): - r"""Represents a connection between a source node and a - destination node in this attack path. - - Attributes: - source (str): - The attack node uuid of the source node. - destination (str): - The attack node uuid of the destination node. - """ - - source: str = proto.Field( - proto.STRING, - number=1, - ) - destination: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - path_nodes: MutableSequence[AttackPathNode] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=AttackPathNode, - ) - edges: MutableSequence[AttackPathEdge] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=AttackPathEdge, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py deleted file mode 100644 index 0c1d44505179..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py +++ /dev/null @@ -1,137 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v2', - manifest={ - 'BackupDisasterRecovery', - }, -) - - -class BackupDisasterRecovery(proto.Message): - r"""Information related to Google Cloud Backup and DR Service - findings. - - Attributes: - backup_template (str): - The name of a Backup and DR template which comprises one or - more backup policies. See the `Backup and DR - documentation `__ - for more information. For example, ``snap-ov``. - policies (MutableSequence[str]): - The names of Backup and DR policies that are associated with - a template and that define when to run a backup, how - frequently to run a backup, and how long to retain the - backup image. For example, ``onvaults``. - host (str): - The name of a Backup and DR host, which is managed by the - backup and recovery appliance and known to the management - console. The host can be of type Generic (for example, - Compute Engine, SQL Server, Oracle DB, SMB file system, - etc.), vCenter, or an ESX server. See the `Backup and DR - documentation on - hosts `__ - for more information. For example, ``centos7-01``. - applications (MutableSequence[str]): - The names of Backup and DR applications. An application is a - VM, database, or file system on a managed host monitored by - a backup and recovery appliance. For example, - ``centos7-01-vol00``, ``centos7-01-vol01``, - ``centos7-01-vol02``. - storage_pool (str): - The name of the Backup and DR storage pool that the backup - and recovery appliance is storing data in. The storage pool - could be of type Cloud, Primary, Snapshot, or OnVault. See - the `Backup and DR documentation on storage - pools `__. - For example, ``DiskPoolOne``. - policy_options (MutableSequence[str]): - The names of Backup and DR advanced policy options of a - policy applying to an application. See the `Backup and DR - documentation on policy - options `__. - For example, ``skipofflineappsincongrp, nounmap``. - profile (str): - The name of the Backup and DR resource profile that - specifies the storage media for backups of application and - VM data. See the `Backup and DR documentation on - profiles `__. - For example, ``GCP``. - appliance (str): - The name of the Backup and DR appliance that captures, - moves, and manages the lifecycle of backup data. For - example, ``backup-server-57137``. - backup_type (str): - The backup type of the Backup and DR image. For example, - ``Snapshot``, ``Remote Snapshot``, ``OnVault``. - backup_create_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp at which the Backup and DR - backup was created. - """ - - backup_template: str = proto.Field( - proto.STRING, - number=1, - ) - policies: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - host: str = proto.Field( - proto.STRING, - number=3, - ) - applications: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - storage_pool: str = proto.Field( - proto.STRING, - number=5, - ) - policy_options: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - profile: str = proto.Field( - proto.STRING, - number=7, - ) - appliance: str = proto.Field( - proto.STRING, - number=8, - ) - backup_type: str = proto.Field( - proto.STRING, - number=9, - ) - backup_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py deleted file mode 100644 index 01d3971a5bd5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/bigquery_export.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v2', - manifest={ - 'BigQueryExport', - }, -) - - -class BigQueryExport(proto.Message): - r"""Configures how to deliver Findings to BigQuery Instance. - - Attributes: - name (str): - Identifier. The relative resource name of this export. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name. - The following list shows some examples: - - - - - ``organizations/{organization_id}/locations/{location_id}/bigQueryExports/{export_id}`` - - - ``folders/{folder_id}/locations/{location_id}/bigQueryExports/{export_id}`` - - - - ``projects/{project_id}/locations/{location_id}/bigQueryExports/{export_id}`` - - This field is provided in responses, and is ignored when - provided in create requests. - description (str): - The description of the export (max of 1024 - characters). - filter (str): - Expression that defines the filter to apply across - create/update events of findings. The expression is a list - of zero or more restrictions combined via logical operators - ``AND`` and ``OR``. Parentheses are supported, and ``OR`` - has higher precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - dataset (str): - The dataset to write findings' updates to. Its format is - "projects/[project_id]/datasets/[bigquery_dataset_id]". - BigQuery dataset unique ID must contain only letters (a-z, - A-Z), numbers (0-9), or underscores (_). - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the BigQuery - export was created. This field is set by the - server and will be ignored if provided on export - on creation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The most recent time at which - the BigQuery export was updated. This field is - set by the server and will be ignored if - provided on export creation or update. - most_recent_editor (str): - Output only. Email address of the user who - last edited the BigQuery export. This field is - set by the server and will be ignored if - provided on export creation or update. - principal (str): - Output only. The service account that needs - permission to create table and upload data to - the BigQuery dataset. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - filter: str = proto.Field( - proto.STRING, - number=3, - ) - dataset: 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, - ) - most_recent_editor: str = proto.Field( - proto.STRING, - number=7, - ) - principal: str = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.py deleted file mode 100644 index 2bf900e3af1c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_armor.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.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'CloudArmor', - 'SecurityPolicy', - 'Requests', - 'AdaptiveProtection', - 'Attack', - }, -) - - -class CloudArmor(proto.Message): - r"""Fields related to Google Cloud Armor findings. - - Attributes: - security_policy (google.cloud.securitycenter_v2.types.SecurityPolicy): - Information about the `Google Cloud Armor security - policy `__ - relevant to the finding. - requests (google.cloud.securitycenter_v2.types.Requests): - Information about incoming requests evaluated by `Google - Cloud Armor security - policies `__. - adaptive_protection (google.cloud.securitycenter_v2.types.AdaptiveProtection): - Information about potential Layer 7 DDoS attacks identified - by `Google Cloud Armor Adaptive - Protection `__. - attack (google.cloud.securitycenter_v2.types.Attack): - Information about DDoS attack volume and - classification. - threat_vector (str): - Distinguish between volumetric & protocol DDoS attack and - application layer attacks. For example, "L3_4" for Layer 3 - and Layer 4 DDoS attacks, or "L_7" for Layer 7 DDoS attacks. - duration (google.protobuf.duration_pb2.Duration): - Duration of attack from the start until the - current moment (updated every 5 minutes). - """ - - security_policy: 'SecurityPolicy' = proto.Field( - proto.MESSAGE, - number=1, - message='SecurityPolicy', - ) - requests: 'Requests' = proto.Field( - proto.MESSAGE, - number=2, - message='Requests', - ) - adaptive_protection: 'AdaptiveProtection' = proto.Field( - proto.MESSAGE, - number=3, - message='AdaptiveProtection', - ) - attack: 'Attack' = proto.Field( - proto.MESSAGE, - number=4, - message='Attack', - ) - threat_vector: str = proto.Field( - proto.STRING, - number=5, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - - -class SecurityPolicy(proto.Message): - r"""Information about the `Google Cloud Armor security - policy `__ - relevant to the finding. - - Attributes: - name (str): - The name of the Google Cloud Armor security - policy, for example, "my-security-policy". - type_ (str): - The type of Google Cloud Armor security - policy for example, 'backend security policy', - 'edge security policy', 'network edge security - policy', or 'always-on DDoS protection'. - preview (bool): - Whether or not the associated rule or policy - is in preview mode. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - preview: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class Requests(proto.Message): - r"""Information about the requests relevant to the finding. - - Attributes: - ratio (float): - For 'Increasing deny ratio', the ratio is the - denied traffic divided by the allowed traffic. - For 'Allowed traffic spike', the ratio is the - allowed traffic in the short term divided by - allowed traffic in the long term. - short_term_allowed (int): - Allowed RPS (requests per second) in the - short term. - long_term_allowed (int): - Allowed RPS (requests per second) over the - long term. - long_term_denied (int): - Denied RPS (requests per second) over the - long term. - """ - - ratio: float = proto.Field( - proto.DOUBLE, - number=1, - ) - short_term_allowed: int = proto.Field( - proto.INT32, - number=2, - ) - long_term_allowed: int = proto.Field( - proto.INT32, - number=3, - ) - long_term_denied: int = proto.Field( - proto.INT32, - number=4, - ) - - -class AdaptiveProtection(proto.Message): - r"""Information about `Google Cloud Armor Adaptive - Protection `__. - - Attributes: - confidence (float): - A score of 0 means that there is low confidence that the - detected event is an actual attack. A score of 1 means that - there is high confidence that the detected event is an - attack. See the `Adaptive Protection - documentation `__ - for further explanation. - """ - - confidence: float = proto.Field( - proto.DOUBLE, - number=1, - ) - - -class Attack(proto.Message): - r"""Information about DDoS attack volume and classification. - - Attributes: - volume_pps (int): - Total PPS (packets per second) volume of - attack. - volume_bps (int): - Total BPS (bytes per second) volume of - attack. - classification (str): - Type of attack, for example, 'SYN-flood', - 'NTP-udp', or 'CHARGEN-udp'. - """ - - volume_pps: int = proto.Field( - proto.INT32, - number=1, - ) - volume_bps: int = proto.Field( - proto.INT32, - number=2, - ) - classification: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py deleted file mode 100644 index 1b41c5f6d040..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.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.cloud.securitycenter.v2', - manifest={ - 'CloudDlpDataProfile', - }, -) - - -class CloudDlpDataProfile(proto.Message): - r"""The `data - profile `__ - associated with the finding. - - Attributes: - data_profile (str): - Name of the data profile, for example, - ``projects/123/locations/europe/tableProfiles/8383929``. - parent_type (google.cloud.securitycenter_v2.types.CloudDlpDataProfile.ParentType): - The resource hierarchy level at which the - data profile was generated. - """ - class ParentType(proto.Enum): - r"""Parents for configurations that produce data profile - findings. - - Values: - PARENT_TYPE_UNSPECIFIED (0): - Unspecified parent type. - ORGANIZATION (1): - Organization-level configurations. - PROJECT (2): - Project-level configurations. - """ - PARENT_TYPE_UNSPECIFIED = 0 - ORGANIZATION = 1 - PROJECT = 2 - - data_profile: str = proto.Field( - proto.STRING, - number=1, - ) - parent_type: ParentType = proto.Field( - proto.ENUM, - number=2, - enum=ParentType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py deleted file mode 100644 index c98af340d22a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'CloudDlpInspection', - }, -) - - -class CloudDlpInspection(proto.Message): - r"""Details about the Cloud Data Loss Prevention (Cloud DLP) `inspection - job `__ - that produced the finding. - - Attributes: - inspect_job (str): - Name of the inspection job, for example, - ``projects/123/locations/europe/dlpJobs/i-8383929``. - info_type (str): - The type of information (or - `infoType `__) - found, for example, ``EMAIL_ADDRESS`` or ``STREET_ADDRESS``. - info_type_count (int): - The number of times Cloud DLP found this - infoType within this job and resource. - full_scan (bool): - Whether Cloud DLP scanned the complete - resource or a sampled subset. - """ - - inspect_job: str = proto.Field( - proto.STRING, - number=1, - ) - info_type: str = proto.Field( - proto.STRING, - number=2, - ) - info_type_count: int = proto.Field( - proto.INT64, - number=3, - ) - full_scan: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.py deleted file mode 100644 index 64f5c99ef06b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/compliance.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Compliance', - }, -) - - -class Compliance(proto.Message): - r"""Contains compliance information about a security standard - indicating unmet recommendations. - - Attributes: - standard (str): - Industry-wide compliance standards or - benchmarks, such as CIS, PCI, and OWASP. - version (str): - Version of the standard or benchmark, for - example, 1.1 - ids (MutableSequence[str]): - Policies within the standard or benchmark, - for example, A.12.4.1 - """ - - standard: str = proto.Field( - proto.STRING, - number=1, - ) - version: str = proto.Field( - proto.STRING, - number=2, - ) - ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.py deleted file mode 100644 index 1e0ff52947d5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/connection.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.cloud.securitycenter.v2', - manifest={ - 'Connection', - }, -) - - -class Connection(proto.Message): - r"""Contains information about the IP connection associated with - the finding. - - Attributes: - destination_ip (str): - Destination IP address. Not present for - sockets that are listening and not connected. - destination_port (int): - Destination port. Not present for sockets - that are listening and not connected. - source_ip (str): - Source IP address. - source_port (int): - Source port. - protocol (google.cloud.securitycenter_v2.types.Connection.Protocol): - IANA Internet Protocol Number such as TCP(6) - and UDP(17). - """ - class Protocol(proto.Enum): - r"""IANA Internet Protocol Number such as TCP(6) and UDP(17). - - Values: - PROTOCOL_UNSPECIFIED (0): - Unspecified protocol (not HOPOPT). - ICMP (1): - Internet Control Message Protocol. - TCP (6): - Transmission Control Protocol. - UDP (17): - User Datagram Protocol. - GRE (47): - Generic Routing Encapsulation. - ESP (50): - Encap Security Payload. - """ - PROTOCOL_UNSPECIFIED = 0 - ICMP = 1 - TCP = 6 - UDP = 17 - GRE = 47 - ESP = 50 - - destination_ip: str = proto.Field( - proto.STRING, - number=1, - ) - destination_port: int = proto.Field( - proto.INT32, - number=2, - ) - source_ip: str = proto.Field( - proto.STRING, - number=3, - ) - source_port: int = proto.Field( - proto.INT32, - number=4, - ) - protocol: Protocol = proto.Field( - proto.ENUM, - number=5, - enum=Protocol, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.py deleted file mode 100644 index f7e49e2e4392..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/contact_details.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'ContactDetails', - 'Contact', - }, -) - - -class ContactDetails(proto.Message): - r"""Details about specific contacts - - Attributes: - contacts (MutableSequence[google.cloud.securitycenter_v2.types.Contact]): - A list of contacts - """ - - contacts: MutableSequence['Contact'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Contact', - ) - - -class Contact(proto.Message): - r"""The email address of a contact. - - Attributes: - email (str): - An email address. For example, "``person123@company.com``". - """ - - email: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.py deleted file mode 100644 index de1e6fd55be0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/container.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v2.types import label -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Container', - }, -) - - -class Container(proto.Message): - r"""Container associated with the finding. - - Attributes: - name (str): - Name of the container. - uri (str): - Container image URI provided when configuring - a pod or container. This string can identify a - container image version using mutable tags. - image_id (str): - Optional container image ID, if provided by - the container runtime. Uniquely identifies the - container image launched using a container image - digest. - labels (MutableSequence[google.cloud.securitycenter_v2.types.Label]): - Container labels, as provided by the - container runtime. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the container was created. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - image_id: str = proto.Field( - proto.STRING, - number=3, - ) - labels: MutableSequence[label.Label] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=label.Label, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.py deleted file mode 100644 index 59f3eefcf9e3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/database.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Database', - }, -) - - -class Database(proto.Message): - r"""Represents database access information, such as queries. A database - may be a sub-resource of an instance (as in the case of Cloud SQL - instances or Cloud Spanner instances), or the database instance - itself. Some database resources might not have the `full resource - name `__ populated - because these resource types, such as Cloud SQL databases, are not - yet supported by Cloud Asset Inventory. In these cases only the - display name is provided. - - Attributes: - name (str): - Some database resources may not have the `full resource - name `__ - populated because these resource types are not yet supported - by Cloud Asset Inventory (e.g. Cloud SQL databases). In - these cases only the display name will be provided. The - `full resource - name `__ of - the database that the user connected to, if it is supported - by Cloud Asset Inventory. - display_name (str): - The human-readable name of the database that - the user connected to. - user_name (str): - The username used to connect to the database. - The username might not be an IAM principal and - does not have a set format. - query (str): - The SQL statement that is associated with the - database access. - grantees (MutableSequence[str]): - The target usernames, roles, or groups of an - SQL privilege grant, which is not an IAM policy - change. - version (str): - The version of the database, for example, POSTGRES_14. See - `the complete - list `__. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - user_name: str = proto.Field( - proto.STRING, - number=3, - ) - query: str = proto.Field( - proto.STRING, - number=4, - ) - grantees: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - version: str = proto.Field( - proto.STRING, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.py deleted file mode 100644 index 8a3c83a21200..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/exfiltration.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Exfiltration', - 'ExfilResource', - }, -) - - -class Exfiltration(proto.Message): - r"""Exfiltration represents a data exfiltration attempt from one or more - sources to one or more targets. The ``sources`` attribute lists the - sources of the exfiltrated data. The ``targets`` attribute lists the - destinations the data was copied to. - - Attributes: - sources (MutableSequence[google.cloud.securitycenter_v2.types.ExfilResource]): - If there are multiple sources, then the data - is considered "joined" between them. For - instance, BigQuery can join multiple tables, and - each table would be considered a source. - targets (MutableSequence[google.cloud.securitycenter_v2.types.ExfilResource]): - If there are multiple targets, each target - would get a complete copy of the "joined" source - data. - total_exfiltrated_bytes (int): - Total exfiltrated bytes processed for the - entire job. - """ - - sources: MutableSequence['ExfilResource'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ExfilResource', - ) - targets: MutableSequence['ExfilResource'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ExfilResource', - ) - total_exfiltrated_bytes: int = proto.Field( - proto.INT64, - number=3, - ) - - -class ExfilResource(proto.Message): - r"""Resource where data was exfiltrated from or exfiltrated to. - - Attributes: - name (str): - The resource's `full resource - name `__. - components (MutableSequence[str]): - Subcomponents of the asset that was - exfiltrated, like URIs used during exfiltration, - table names, databases, and filenames. For - example, multiple tables might have been - exfiltrated from the same Cloud SQL instance, or - multiple files might have been exfiltrated from - the same Cloud Storage bucket. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - components: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py deleted file mode 100644 index 780eb3c24edf..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/external_system.py +++ /dev/null @@ -1,192 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v2', - manifest={ - 'ExternalSystem', - }, -) - - -class ExternalSystem(proto.Message): - r"""Representation of third party SIEM/SOAR fields within SCC. - - Attributes: - name (str): - Full resource name of the external system. The following - list shows some examples: - - - ``organizations/1234/sources/5678/findings/123456/externalSystems/jira`` - - - - ``organizations/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` - - - ``folders/1234/sources/5678/findings/123456/externalSystems/jira`` - - - - ``folders/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` - - - ``projects/1234/sources/5678/findings/123456/externalSystems/jira`` - - - - ``projects/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` - assignees (MutableSequence[str]): - References primary/secondary etc assignees in - the external system. - external_uid (str): - The identifier that's used to track the - finding's corresponding case in the external - system. - status (str): - The most recent status of the finding's - corresponding case, as reported by the external - system. - external_system_update_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the case was last updated, as - reported by the external system. - case_uri (str): - The link to the finding's corresponding case - in the external system. - case_priority (str): - The priority of the finding's corresponding - case in the external system. - case_sla (google.protobuf.timestamp_pb2.Timestamp): - The SLA of the finding's corresponding case - in the external system. - case_create_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the case was created, as - reported by the external system. - case_close_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the case was closed, as - reported by the external system. - ticket_info (google.cloud.securitycenter_v2.types.ExternalSystem.TicketInfo): - Information about the ticket, if any, that is - being used to track the resolution of the issue - that is identified by this finding. - """ - - class TicketInfo(proto.Message): - r"""Information about the ticket, if any, that is being used to - track the resolution of the issue that is identified by this - finding. - - Attributes: - id (str): - The identifier of the ticket in the ticket - system. - assignee (str): - The assignee of the ticket in the ticket - system. - description (str): - The description of the ticket in the ticket - system. - uri (str): - The link to the ticket in the ticket system. - status (str): - The latest status of the ticket, as reported - by the ticket system. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time when the ticket was last updated, as - reported by the ticket system. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - assignee: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - uri: str = proto.Field( - proto.STRING, - number=4, - ) - status: str = proto.Field( - proto.STRING, - number=5, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - assignees: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - external_uid: str = proto.Field( - proto.STRING, - number=3, - ) - status: str = proto.Field( - proto.STRING, - number=4, - ) - external_system_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - case_uri: str = proto.Field( - proto.STRING, - number=6, - ) - case_priority: str = proto.Field( - proto.STRING, - number=7, - ) - case_sla: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - case_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - case_close_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - ticket_info: TicketInfo = proto.Field( - proto.MESSAGE, - number=8, - message=TicketInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.py deleted file mode 100644 index 5bb6f2f70ef0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/file.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'File', - }, -) - - -class File(proto.Message): - r"""File information about the related binary/library used by an - executable, or the script used by a script interpreter - - Attributes: - path (str): - Absolute path of the file as a JSON encoded - string. - size (int): - Size of the file in bytes. - sha256 (str): - SHA256 hash of the first hashed_size bytes of the file - encoded as a hex string. If hashed_size == size, sha256 - represents the SHA256 hash of the entire file. - hashed_size (int): - The length in bytes of the file prefix that was hashed. If - hashed_size == size, any hashes reported represent the - entire file. - partially_hashed (bool): - True when the hash covers only a prefix of - the file. - contents (str): - Prefix of the file contents as a JSON-encoded - string. - disk_path (google.cloud.securitycenter_v2.types.File.DiskPath): - Path of the file in terms of underlying - disk/partition identifiers. - """ - - class DiskPath(proto.Message): - r"""Path of the file in terms of underlying disk/partition - identifiers. - - Attributes: - partition_uuid (str): - UUID of the partition (format - https://wiki.archlinux.org/title/persistent_block_device_naming#by-uuid) - relative_path (str): - Relative path of the file in the partition as a JSON encoded - string. Example: /home/user1/executable_file.sh - """ - - partition_uuid: str = proto.Field( - proto.STRING, - number=1, - ) - relative_path: str = proto.Field( - proto.STRING, - number=2, - ) - - path: str = proto.Field( - proto.STRING, - number=1, - ) - size: int = proto.Field( - proto.INT64, - number=2, - ) - sha256: str = proto.Field( - proto.STRING, - number=3, - ) - hashed_size: int = proto.Field( - proto.INT64, - number=4, - ) - partially_hashed: bool = proto.Field( - proto.BOOL, - number=5, - ) - contents: str = proto.Field( - proto.STRING, - number=6, - ) - disk_path: DiskPath = proto.Field( - proto.MESSAGE, - number=7, - message=DiskPath, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.py deleted file mode 100644 index 4e18ac0eb8ae..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/finding.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v2.types import access as gcs_access -from google.cloud.securitycenter_v2.types import application as gcs_application -from google.cloud.securitycenter_v2.types import attack_exposure as gcs_attack_exposure -from google.cloud.securitycenter_v2.types import backup_disaster_recovery as gcs_backup_disaster_recovery -from google.cloud.securitycenter_v2.types import cloud_armor as gcs_cloud_armor -from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile as gcs_cloud_dlp_data_profile -from google.cloud.securitycenter_v2.types import cloud_dlp_inspection as gcs_cloud_dlp_inspection -from google.cloud.securitycenter_v2.types import compliance -from google.cloud.securitycenter_v2.types import connection -from google.cloud.securitycenter_v2.types import contact_details -from google.cloud.securitycenter_v2.types import container -from google.cloud.securitycenter_v2.types import database as gcs_database -from google.cloud.securitycenter_v2.types import exfiltration as gcs_exfiltration -from google.cloud.securitycenter_v2.types import external_system -from google.cloud.securitycenter_v2.types import file -from google.cloud.securitycenter_v2.types import group_membership -from google.cloud.securitycenter_v2.types import iam_binding -from google.cloud.securitycenter_v2.types import indicator as gcs_indicator -from google.cloud.securitycenter_v2.types import kernel_rootkit as gcs_kernel_rootkit -from google.cloud.securitycenter_v2.types import kubernetes as gcs_kubernetes -from google.cloud.securitycenter_v2.types import load_balancer -from google.cloud.securitycenter_v2.types import log_entry -from google.cloud.securitycenter_v2.types import mitre_attack as gcs_mitre_attack -from google.cloud.securitycenter_v2.types import notebook as gcs_notebook -from google.cloud.securitycenter_v2.types import org_policy -from google.cloud.securitycenter_v2.types import process -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import security_posture as gcs_security_posture -from google.cloud.securitycenter_v2.types import toxic_combination as gcs_toxic_combination -from google.cloud.securitycenter_v2.types import vulnerability as gcs_vulnerability -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - - A finding is a record of assessment data like security, risk, - health, or privacy, that is ingested into Security Command - Center for presentation, notification, analysis, policy testing, - and enforcement. For example, a cross-site scripting (XSS) - vulnerability in an App Engine application is a finding. - - Attributes: - name (str): - The `relative resource - name `__ - of the finding. The following list shows some examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - canonical_name (str): - Output only. The canonical name of the finding. The - following list shows some examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - The prefix is the closest CRM ancestor of the resource - associated with the finding. - parent (str): - The relative resource name of the source and location the - finding belongs to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. The following - list shows some examples: - - - ``organizations/{organization_id}/sources/{source_id}`` - - ``folders/{folders_id}/sources/{source_id}`` - - ``projects/{projects_id}/sources/{source_id}`` - - - - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}`` - - - ``folders/{folders_id}/sources/{source_id}/locations/{location_id}`` - - ``projects/{projects_id}/sources/{source_id}/locations/{location_id}`` - resource_name (str): - Immutable. For findings on Google Cloud resources, the full - resource name of the Google Cloud resource this finding is - for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - state (google.cloud.securitycenter_v2.types.Finding.State): - Output only. The state of the finding. - category (str): - Immutable. The additional taxonomy group within findings - from a given source. Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (google.protobuf.timestamp_pb2.Timestamp): - The time the finding was first detected. If - an existing finding is updated, then this is the - time the update occurred. For example, if the - finding represents an open firewall, this - property captures the time the detector believes - the firewall became open. The accuracy is - determined by the detector. If the finding is - later resolved, then this time reflects when the - finding was resolved. This must not be set to a - value greater than the current timestamp. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the finding - was created in Security Command Center. - severity (google.cloud.securitycenter_v2.types.Finding.Severity): - The severity of the finding. This field is - managed by the source that writes the finding. - mute (google.cloud.securitycenter_v2.types.Finding.Mute): - Indicates the mute state of a finding (either - muted, unmuted or undefined). Unlike other - attributes of a finding, a finding provider - shouldn't set the value of mute. - mute_info (google.cloud.securitycenter_v2.types.Finding.MuteInfo): - Output only. The mute information regarding - this finding. - finding_class (google.cloud.securitycenter_v2.types.Finding.FindingClass): - The class of the finding. - indicator (google.cloud.securitycenter_v2.types.Indicator): - Represents what's commonly known as an *indicator of - compromise* (IoC) in computer forensics. This is an artifact - observed on a network or in an operating system that, with - high confidence, indicates a computer intrusion. For more - information, see `Indicator of - compromise `__. - vulnerability (google.cloud.securitycenter_v2.types.Vulnerability): - Represents vulnerability-specific fields like - CVE and CVSS scores. CVE stands for Common - Vulnerabilities and Exposures - (https://cve.mitre.org/about/) - mute_update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The most recent time this - finding was muted or unmuted. - external_systems (MutableMapping[str, google.cloud.securitycenter_v2.types.ExternalSystem]): - Output only. Third party SIEM/SOAR fields - within SCC, contains external system information - and external system finding fields. - mitre_attack (google.cloud.securitycenter_v2.types.MitreAttack): - MITRE ATT&CK tactics and techniques related - to this finding. See: https://attack.mitre.org - access (google.cloud.securitycenter_v2.types.Access): - Access details associated with the finding, - such as more information on the caller, which - method was accessed, and from where. - connections (MutableSequence[google.cloud.securitycenter_v2.types.Connection]): - Contains information about the IP connection - associated with the finding. - mute_initiator (str): - Records additional information about the mute operation, for - example, the `mute - configuration `__ - that muted the finding and the user who muted the finding. - processes (MutableSequence[google.cloud.securitycenter_v2.types.Process]): - Represents operating system processes - associated with the Finding. - contacts (MutableMapping[str, google.cloud.securitycenter_v2.types.ContactDetails]): - Output only. Map containing the points of contact for the - given finding. The key represents the type of contact, while - the value contains a list of all the contacts that pertain. - Please refer to: - https://cloud.google.com/resource-manager/docs/managing-notification-contacts#notification-categories - - :: - - { - "security": { - "contacts": [ - { - "email": "person1@company.com" - }, - { - "email": "person2@company.com" - } - ] - } - } - compliances (MutableSequence[google.cloud.securitycenter_v2.types.Compliance]): - Contains compliance information for security - standards associated to the finding. - parent_display_name (str): - Output only. The human readable display name - of the finding source such as "Event Threat - Detection" or "Security Health Analytics". - description (str): - Contains more details about the finding. - exfiltration (google.cloud.securitycenter_v2.types.Exfiltration): - Represents exfiltrations associated with the - finding. - iam_bindings (MutableSequence[google.cloud.securitycenter_v2.types.IamBinding]): - Represents IAM bindings associated with the - finding. - next_steps (str): - Steps to address the finding. - module_name (str): - Unique identifier of the module which - generated the finding. Example: - - folders/598186756061/securityHealthAnalyticsSettings/customModules/56799441161885 - containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): - Containers associated with the finding. This - field provides information for both Kubernetes - and non-Kubernetes containers. - kubernetes (google.cloud.securitycenter_v2.types.Kubernetes): - Kubernetes resources associated with the - finding. - database (google.cloud.securitycenter_v2.types.Database): - Database associated with the finding. - attack_exposure (google.cloud.securitycenter_v2.types.AttackExposure): - The results of an attack path simulation - relevant to this finding. - files (MutableSequence[google.cloud.securitycenter_v2.types.File]): - File associated with the finding. - cloud_dlp_inspection (google.cloud.securitycenter_v2.types.CloudDlpInspection): - Cloud Data Loss Prevention (Cloud DLP) - inspection results that are associated with the - finding. - cloud_dlp_data_profile (google.cloud.securitycenter_v2.types.CloudDlpDataProfile): - Cloud DLP data profile that is associated - with the finding. - kernel_rootkit (google.cloud.securitycenter_v2.types.KernelRootkit): - Signature of the kernel rootkit. - org_policies (MutableSequence[google.cloud.securitycenter_v2.types.OrgPolicy]): - Contains information about the org policies - associated with the finding. - application (google.cloud.securitycenter_v2.types.Application): - Represents an application associated with the - finding. - backup_disaster_recovery (google.cloud.securitycenter_v2.types.BackupDisasterRecovery): - Fields related to Backup and DR findings. - security_posture (google.cloud.securitycenter_v2.types.SecurityPosture): - The security posture associated with the - finding. - log_entries (MutableSequence[google.cloud.securitycenter_v2.types.LogEntry]): - Log entries that are relevant to the finding. - load_balancers (MutableSequence[google.cloud.securitycenter_v2.types.LoadBalancer]): - The load balancers associated with the - finding. - cloud_armor (google.cloud.securitycenter_v2.types.CloudArmor): - Fields related to Cloud Armor findings. - notebook (google.cloud.securitycenter_v2.types.Notebook): - Notebook associated with the finding. - toxic_combination (google.cloud.securitycenter_v2.types.ToxicCombination): - Contains details about a group of security - issues that, when the issues occur together, - represent a greater risk than when the issues - occur independently. A group of such issues is - referred to as a toxic combination. - This field cannot be updated. Its value is - ignored in all update requests. - group_memberships (MutableSequence[google.cloud.securitycenter_v2.types.GroupMembership]): - Contains details about groups of which this - finding is a member. A group is a collection of - findings that are related in some way. This - field cannot be updated. Its value is ignored in - all update requests. - """ - class State(proto.Enum): - r"""The state of the finding. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - ACTIVE (1): - The finding requires attention and has not - been addressed yet. - INACTIVE (2): - The finding has been fixed, triaged as a - non-issue or otherwise addressed and is no - longer active. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - class Severity(proto.Enum): - r"""The severity of the finding. - - Values: - SEVERITY_UNSPECIFIED (0): - This value is used for findings when a source - doesn't write a severity value. - CRITICAL (1): - Vulnerability: - - A critical vulnerability is easily discoverable - by an external actor, exploitable, and results - in the direct ability to execute arbitrary code, - exfiltrate data, and otherwise gain additional - access and privileges to cloud resources and - workloads. Examples include publicly accessible - unprotected user data and public SSH access with - weak or no passwords. - - Threat: - - Indicates a threat that is able to access, - modify, or delete data or execute unauthorized - code within existing resources. - HIGH (2): - Vulnerability: - - A high risk vulnerability can be easily - discovered and exploited in combination with - other vulnerabilities in order to gain direct - access and the ability to execute arbitrary - code, exfiltrate data, and otherwise gain - additional access and privileges to cloud - resources and workloads. An example is a - database with weak or no passwords that is only - accessible internally. This database could - easily be compromised by an actor that had - access to the internal network. - - Threat: - - Indicates a threat that is able to create new - computational resources in an environment but - not able to access data or execute code in - existing resources. - MEDIUM (3): - Vulnerability: - - A medium risk vulnerability could be used by an - actor to gain access to resources or privileges - that enable them to eventually (through multiple - steps or a complex exploit) gain access and the - ability to execute arbitrary code or exfiltrate - data. An example is a service account with - access to more projects than it should have. If - an actor gains access to the service account, - they could potentially use that access to - manipulate a project the service account was not - intended to. - - Threat: - - Indicates a threat that is able to cause - operational impact but may not access data or - execute unauthorized code. - LOW (4): - Vulnerability: - - A low risk vulnerability hampers a security - organization's ability to detect vulnerabilities - or active threats in their deployment, or - prevents the root cause investigation of - security issues. An example is monitoring and - logs being disabled for resource configurations - and access. - - Threat: - - Indicates a threat that has obtained minimal - access to an environment but is not able to - access data, execute code, or create resources. - """ - SEVERITY_UNSPECIFIED = 0 - CRITICAL = 1 - HIGH = 2 - MEDIUM = 3 - LOW = 4 - - class Mute(proto.Enum): - r"""Mute state a finding can be in. - - Values: - MUTE_UNSPECIFIED (0): - Unspecified. - MUTED (1): - Finding has been muted. - UNMUTED (2): - Finding has been unmuted. - UNDEFINED (3): - Finding has never been muted/unmuted. - """ - MUTE_UNSPECIFIED = 0 - MUTED = 1 - UNMUTED = 2 - UNDEFINED = 3 - - class FindingClass(proto.Enum): - r"""Represents what kind of Finding it is. - - Values: - FINDING_CLASS_UNSPECIFIED (0): - Unspecified finding class. - THREAT (1): - Describes unwanted or malicious activity. - VULNERABILITY (2): - Describes a potential weakness in software - that increases risk to Confidentiality & - Integrity & Availability. - MISCONFIGURATION (3): - Describes a potential weakness in cloud - resource/asset configuration that increases - risk. - OBSERVATION (4): - Describes a security observation that is for - informational purposes. - SCC_ERROR (5): - Describes an error that prevents some SCC - functionality. - POSTURE_VIOLATION (6): - Describes a potential security risk due to a - change in the security posture. - TOXIC_COMBINATION (7): - Describes a combination of security issues - that represent a more severe security problem - when taken together. - """ - FINDING_CLASS_UNSPECIFIED = 0 - THREAT = 1 - VULNERABILITY = 2 - MISCONFIGURATION = 3 - OBSERVATION = 4 - SCC_ERROR = 5 - POSTURE_VIOLATION = 6 - TOXIC_COMBINATION = 7 - - class MuteInfo(proto.Message): - r"""Mute information about the finding, including whether the - finding has a static mute or any matching dynamic mute rules. - - Attributes: - static_mute (google.cloud.securitycenter_v2.types.Finding.MuteInfo.StaticMute): - If set, the static mute applied to this - finding. Static mutes override dynamic mutes. If - unset, there is no static mute. - dynamic_mute_records (MutableSequence[google.cloud.securitycenter_v2.types.Finding.MuteInfo.DynamicMuteRecord]): - The list of dynamic mute rules that currently - match the finding. - """ - - class StaticMute(proto.Message): - r"""Information about the static mute state. A static mute state - overrides any dynamic mute rules that apply to this finding. The - static mute state can be set by a static mute rule or by muting - the finding directly. - - Attributes: - state (google.cloud.securitycenter_v2.types.Finding.Mute): - The static mute state. If the value is ``MUTED`` or - ``UNMUTED``, then the finding's overall mute state will have - the same value. - apply_time (google.protobuf.timestamp_pb2.Timestamp): - When the static mute was applied. - """ - - state: 'Finding.Mute' = proto.Field( - proto.ENUM, - number=1, - enum='Finding.Mute', - ) - apply_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - class DynamicMuteRecord(proto.Message): - r"""The record of a dynamic mute rule that matches the finding. - - Attributes: - mute_config (str): - The relative resource name of the mute rule, represented by - a mute config, that created this record, for example - ``organizations/123/muteConfigs/mymuteconfig`` or - ``organizations/123/locations/global/muteConfigs/mymuteconfig``. - match_time (google.protobuf.timestamp_pb2.Timestamp): - When the dynamic mute rule first matched the - finding. - """ - - mute_config: str = proto.Field( - proto.STRING, - number=1, - ) - match_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - static_mute: 'Finding.MuteInfo.StaticMute' = proto.Field( - proto.MESSAGE, - number=1, - message='Finding.MuteInfo.StaticMute', - ) - dynamic_mute_records: MutableSequence['Finding.MuteInfo.DynamicMuteRecord'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Finding.MuteInfo.DynamicMuteRecord', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=2, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - resource_name: str = proto.Field( - proto.STRING, - number=4, - ) - state: State = proto.Field( - proto.ENUM, - number=6, - enum=State, - ) - category: str = proto.Field( - proto.STRING, - number=7, - ) - external_uri: str = proto.Field( - proto.STRING, - number=8, - ) - source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=9, - message=struct_pb2.Value, - ) - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=10, - message=gcs_security_marks.SecurityMarks, - ) - event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - severity: Severity = proto.Field( - proto.ENUM, - number=14, - enum=Severity, - ) - mute: Mute = proto.Field( - proto.ENUM, - number=15, - enum=Mute, - ) - mute_info: MuteInfo = proto.Field( - proto.MESSAGE, - number=53, - message=MuteInfo, - ) - finding_class: FindingClass = proto.Field( - proto.ENUM, - number=16, - enum=FindingClass, - ) - indicator: gcs_indicator.Indicator = proto.Field( - proto.MESSAGE, - number=17, - message=gcs_indicator.Indicator, - ) - vulnerability: gcs_vulnerability.Vulnerability = proto.Field( - proto.MESSAGE, - number=18, - message=gcs_vulnerability.Vulnerability, - ) - mute_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=19, - message=timestamp_pb2.Timestamp, - ) - external_systems: MutableMapping[str, external_system.ExternalSystem] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=20, - message=external_system.ExternalSystem, - ) - mitre_attack: gcs_mitre_attack.MitreAttack = proto.Field( - proto.MESSAGE, - number=21, - message=gcs_mitre_attack.MitreAttack, - ) - access: gcs_access.Access = proto.Field( - proto.MESSAGE, - number=22, - message=gcs_access.Access, - ) - connections: MutableSequence[connection.Connection] = proto.RepeatedField( - proto.MESSAGE, - number=23, - message=connection.Connection, - ) - mute_initiator: str = proto.Field( - proto.STRING, - number=24, - ) - processes: MutableSequence[process.Process] = proto.RepeatedField( - proto.MESSAGE, - number=25, - message=process.Process, - ) - contacts: MutableMapping[str, contact_details.ContactDetails] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=26, - message=contact_details.ContactDetails, - ) - compliances: MutableSequence[compliance.Compliance] = proto.RepeatedField( - proto.MESSAGE, - number=27, - message=compliance.Compliance, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=29, - ) - description: str = proto.Field( - proto.STRING, - number=30, - ) - exfiltration: gcs_exfiltration.Exfiltration = proto.Field( - proto.MESSAGE, - number=31, - message=gcs_exfiltration.Exfiltration, - ) - iam_bindings: MutableSequence[iam_binding.IamBinding] = proto.RepeatedField( - proto.MESSAGE, - number=32, - message=iam_binding.IamBinding, - ) - next_steps: str = proto.Field( - proto.STRING, - number=33, - ) - module_name: str = proto.Field( - proto.STRING, - number=34, - ) - containers: MutableSequence[container.Container] = proto.RepeatedField( - proto.MESSAGE, - number=35, - message=container.Container, - ) - kubernetes: gcs_kubernetes.Kubernetes = proto.Field( - proto.MESSAGE, - number=36, - message=gcs_kubernetes.Kubernetes, - ) - database: gcs_database.Database = proto.Field( - proto.MESSAGE, - number=37, - message=gcs_database.Database, - ) - attack_exposure: gcs_attack_exposure.AttackExposure = proto.Field( - proto.MESSAGE, - number=38, - message=gcs_attack_exposure.AttackExposure, - ) - files: MutableSequence[file.File] = proto.RepeatedField( - proto.MESSAGE, - number=39, - message=file.File, - ) - cloud_dlp_inspection: gcs_cloud_dlp_inspection.CloudDlpInspection = proto.Field( - proto.MESSAGE, - number=40, - message=gcs_cloud_dlp_inspection.CloudDlpInspection, - ) - cloud_dlp_data_profile: gcs_cloud_dlp_data_profile.CloudDlpDataProfile = proto.Field( - proto.MESSAGE, - number=41, - message=gcs_cloud_dlp_data_profile.CloudDlpDataProfile, - ) - kernel_rootkit: gcs_kernel_rootkit.KernelRootkit = proto.Field( - proto.MESSAGE, - number=42, - message=gcs_kernel_rootkit.KernelRootkit, - ) - org_policies: MutableSequence[org_policy.OrgPolicy] = proto.RepeatedField( - proto.MESSAGE, - number=43, - message=org_policy.OrgPolicy, - ) - application: gcs_application.Application = proto.Field( - proto.MESSAGE, - number=45, - message=gcs_application.Application, - ) - backup_disaster_recovery: gcs_backup_disaster_recovery.BackupDisasterRecovery = proto.Field( - proto.MESSAGE, - number=47, - message=gcs_backup_disaster_recovery.BackupDisasterRecovery, - ) - security_posture: gcs_security_posture.SecurityPosture = proto.Field( - proto.MESSAGE, - number=48, - message=gcs_security_posture.SecurityPosture, - ) - log_entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( - proto.MESSAGE, - number=49, - message=log_entry.LogEntry, - ) - load_balancers: MutableSequence[load_balancer.LoadBalancer] = proto.RepeatedField( - proto.MESSAGE, - number=50, - message=load_balancer.LoadBalancer, - ) - cloud_armor: gcs_cloud_armor.CloudArmor = proto.Field( - proto.MESSAGE, - number=51, - message=gcs_cloud_armor.CloudArmor, - ) - notebook: gcs_notebook.Notebook = proto.Field( - proto.MESSAGE, - number=55, - message=gcs_notebook.Notebook, - ) - toxic_combination: gcs_toxic_combination.ToxicCombination = proto.Field( - proto.MESSAGE, - number=56, - message=gcs_toxic_combination.ToxicCombination, - ) - group_memberships: MutableSequence[group_membership.GroupMembership] = proto.RepeatedField( - proto.MESSAGE, - number=57, - message=group_membership.GroupMembership, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.py deleted file mode 100644 index 2f26d5d13947..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/folder.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.securitycenter.v2', - manifest={ - 'Folder', - }, -) - - -class Folder(proto.Message): - r"""Message that contains the resource name and display name of a - folder resource. - - Attributes: - resource_folder (str): - Full resource name of this folder. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_folder_display_name (str): - The user defined display name for this - folder. - """ - - resource_folder: str = proto.Field( - proto.STRING, - number=1, - ) - resource_folder_display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.py deleted file mode 100644 index bfe69eac6001..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/group_membership.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.cloud.securitycenter.v2', - manifest={ - 'GroupMembership', - }, -) - - -class GroupMembership(proto.Message): - r"""Contains details about groups of which this finding is a - member. A group is a collection of findings that are related in - some way. - - Attributes: - group_type (google.cloud.securitycenter_v2.types.GroupMembership.GroupType): - Type of group. - group_id (str): - ID of the group. - """ - class GroupType(proto.Enum): - r"""Possible types of groups. - - Values: - GROUP_TYPE_UNSPECIFIED (0): - Default value. - GROUP_TYPE_TOXIC_COMBINATION (1): - Group represents a toxic combination. - """ - GROUP_TYPE_UNSPECIFIED = 0 - GROUP_TYPE_TOXIC_COMBINATION = 1 - - group_type: GroupType = proto.Field( - proto.ENUM, - number=1, - enum=GroupType, - ) - group_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py deleted file mode 100644 index 17591c35825f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/iam_binding.py +++ /dev/null @@ -1,77 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v2', - manifest={ - 'IamBinding', - }, -) - - -class IamBinding(proto.Message): - r"""Represents a particular IAM binding, which captures a - member's role addition, removal, or state. - - Attributes: - action (google.cloud.securitycenter_v2.types.IamBinding.Action): - The action that was performed on a Binding. - role (str): - Role that is assigned to "members". - For example, "roles/viewer", "roles/editor", or - "roles/owner". - member (str): - A single identity requesting access for a - Cloud Platform resource, for example, - "foo@google.com". - """ - class Action(proto.Enum): - r"""The type of action performed on a Binding in a policy. - - Values: - ACTION_UNSPECIFIED (0): - Unspecified. - ADD (1): - Addition of a Binding. - REMOVE (2): - Removal of a Binding. - """ - ACTION_UNSPECIFIED = 0 - ADD = 1 - REMOVE = 2 - - action: Action = proto.Field( - proto.ENUM, - number=1, - enum=Action, - ) - role: str = proto.Field( - proto.STRING, - number=2, - ) - member: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py deleted file mode 100644 index 01b0184ef591..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/indicator.py +++ /dev/null @@ -1,186 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v2', - manifest={ - 'Indicator', - }, -) - - -class Indicator(proto.Message): - r"""Represents what's commonly known as an *indicator of compromise* - (IoC) in computer forensics. This is an artifact observed on a - network or in an operating system that, with high confidence, - indicates a computer intrusion. For more information, see `Indicator - of - compromise `__. - - Attributes: - ip_addresses (MutableSequence[str]): - The list of IP addresses that are associated - with the finding. - domains (MutableSequence[str]): - List of domains associated to the Finding. - signatures (MutableSequence[google.cloud.securitycenter_v2.types.Indicator.ProcessSignature]): - The list of matched signatures indicating - that the given process is present in the - environment. - uris (MutableSequence[str]): - The list of URIs associated to the Findings. - """ - - class ProcessSignature(proto.Message): - r"""Indicates what signature matched this process. - - 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: - memory_hash_signature (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.MemoryHashSignature): - Signature indicating that a binary family was - matched. - - This field is a member of `oneof`_ ``signature``. - yara_rule_signature (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.YaraRuleSignature): - Signature indicating that a YARA rule was - matched. - - This field is a member of `oneof`_ ``signature``. - signature_type (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.SignatureType): - Describes the type of resource associated - with the signature. - """ - class SignatureType(proto.Enum): - r"""Possible resource types to be associated with a signature. - - Values: - SIGNATURE_TYPE_UNSPECIFIED (0): - The default signature type. - SIGNATURE_TYPE_PROCESS (1): - Used for signatures concerning processes. - SIGNATURE_TYPE_FILE (2): - Used for signatures concerning disks. - """ - SIGNATURE_TYPE_UNSPECIFIED = 0 - SIGNATURE_TYPE_PROCESS = 1 - SIGNATURE_TYPE_FILE = 2 - - class MemoryHashSignature(proto.Message): - r"""A signature corresponding to memory page hashes. - - Attributes: - binary_family (str): - The binary family. - detections (MutableSequence[google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.MemoryHashSignature.Detection]): - The list of memory hash detections - contributing to the binary family match. - """ - - class Detection(proto.Message): - r"""Memory hash detection contributing to the binary family - match. - - Attributes: - binary (str): - The name of the binary associated with the - memory hash signature detection. - percent_pages_matched (float): - The percentage of memory page hashes in the - signature that were matched. - """ - - binary: str = proto.Field( - proto.STRING, - number=2, - ) - percent_pages_matched: float = proto.Field( - proto.DOUBLE, - number=3, - ) - - binary_family: str = proto.Field( - proto.STRING, - number=1, - ) - detections: MutableSequence['Indicator.ProcessSignature.MemoryHashSignature.Detection'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Indicator.ProcessSignature.MemoryHashSignature.Detection', - ) - - class YaraRuleSignature(proto.Message): - r"""A signature corresponding to a YARA rule. - - Attributes: - yara_rule (str): - The name of the YARA rule. - """ - - yara_rule: str = proto.Field( - proto.STRING, - number=5, - ) - - memory_hash_signature: 'Indicator.ProcessSignature.MemoryHashSignature' = proto.Field( - proto.MESSAGE, - number=6, - oneof='signature', - message='Indicator.ProcessSignature.MemoryHashSignature', - ) - yara_rule_signature: 'Indicator.ProcessSignature.YaraRuleSignature' = proto.Field( - proto.MESSAGE, - number=7, - oneof='signature', - message='Indicator.ProcessSignature.YaraRuleSignature', - ) - signature_type: 'Indicator.ProcessSignature.SignatureType' = proto.Field( - proto.ENUM, - number=8, - enum='Indicator.ProcessSignature.SignatureType', - ) - - ip_addresses: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - domains: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - signatures: MutableSequence[ProcessSignature] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=ProcessSignature, - ) - uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.py deleted file mode 100644 index c57d1db94570..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kernel_rootkit.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'KernelRootkit', - }, -) - - -class KernelRootkit(proto.Message): - r"""Kernel mode rootkit signatures. - - Attributes: - name (str): - Rootkit name, when available. - unexpected_code_modification (bool): - True if unexpected modifications of kernel - code memory are present. - unexpected_read_only_data_modification (bool): - True if unexpected modifications of kernel - read-only data memory are present. - unexpected_ftrace_handler (bool): - True if ``ftrace`` points are present with callbacks - pointing to regions that are not in the expected kernel or - module code range. - unexpected_kprobe_handler (bool): - True if ``kprobe`` points are present with callbacks - pointing to regions that are not in the expected kernel or - module code range. - unexpected_kernel_code_pages (bool): - True if kernel code pages that are not in the - expected kernel or module code regions are - present. - unexpected_system_call_handler (bool): - True if system call handlers that are are not - in the expected kernel or module code regions - are present. - unexpected_interrupt_handler (bool): - True if interrupt handlers that are are not - in the expected kernel or module code regions - are present. - unexpected_processes_in_runqueue (bool): - True if unexpected processes in the scheduler - run queue are present. Such processes are in the - run queue, but not in the process task list. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - unexpected_code_modification: bool = proto.Field( - proto.BOOL, - number=2, - ) - unexpected_read_only_data_modification: bool = proto.Field( - proto.BOOL, - number=3, - ) - unexpected_ftrace_handler: bool = proto.Field( - proto.BOOL, - number=4, - ) - unexpected_kprobe_handler: bool = proto.Field( - proto.BOOL, - number=5, - ) - unexpected_kernel_code_pages: bool = proto.Field( - proto.BOOL, - number=6, - ) - unexpected_system_call_handler: bool = proto.Field( - proto.BOOL, - number=7, - ) - unexpected_interrupt_handler: bool = proto.Field( - proto.BOOL, - number=8, - ) - unexpected_processes_in_runqueue: bool = proto.Field( - proto.BOOL, - number=9, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.py deleted file mode 100644 index 8bc758c1f961..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/kubernetes.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v2.types import container -from google.cloud.securitycenter_v2.types import label - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Kubernetes', - }, -) - - -class Kubernetes(proto.Message): - r"""Kubernetes-related attributes. - - Attributes: - pods (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Pod]): - Kubernetes - `Pods `__ - associated with the finding. This field contains Pod records - for each container that is owned by a Pod. - nodes (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Node]): - Provides Kubernetes - `node `__ - information. - node_pools (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.NodePool]): - GKE `node - pools `__ - associated with the finding. This field contains node pool - information for each node, when it is available. - roles (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Role]): - Provides Kubernetes role information for findings that - involve `Roles or - ClusterRoles `__. - bindings (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Binding]): - Provides Kubernetes role binding information for findings - that involve `RoleBindings or - ClusterRoleBindings `__. - access_reviews (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.AccessReview]): - Provides information on any Kubernetes access - reviews (privilege checks) relevant to the - finding. - objects (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Object]): - Kubernetes objects related to the finding. - """ - - class Pod(proto.Message): - r"""A Kubernetes Pod. - - Attributes: - ns (str): - Kubernetes Pod namespace. - name (str): - Kubernetes Pod name. - labels (MutableSequence[google.cloud.securitycenter_v2.types.Label]): - Pod labels. For Kubernetes containers, these - are applied to the container. - containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): - Pod containers associated with this finding, - if any. - """ - - ns: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - labels: MutableSequence[label.Label] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=label.Label, - ) - containers: MutableSequence[container.Container] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=container.Container, - ) - - class Node(proto.Message): - r"""Kubernetes nodes associated with the finding. - - Attributes: - name (str): - `Full resource - name `__ of - the Compute Engine VM running the cluster node. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - class NodePool(proto.Message): - r"""Provides GKE node pool information. - - Attributes: - name (str): - Kubernetes node pool name. - nodes (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Node]): - Nodes associated with the finding. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - nodes: MutableSequence['Kubernetes.Node'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Kubernetes.Node', - ) - - class Role(proto.Message): - r"""Kubernetes Role or ClusterRole. - - Attributes: - kind (google.cloud.securitycenter_v2.types.Kubernetes.Role.Kind): - Role type. - ns (str): - Role namespace. - name (str): - Role name. - """ - class Kind(proto.Enum): - r"""Types of Kubernetes roles. - - Values: - KIND_UNSPECIFIED (0): - Role type is not specified. - ROLE (1): - Kubernetes Role. - CLUSTER_ROLE (2): - Kubernetes ClusterRole. - """ - KIND_UNSPECIFIED = 0 - ROLE = 1 - CLUSTER_ROLE = 2 - - kind: 'Kubernetes.Role.Kind' = proto.Field( - proto.ENUM, - number=1, - enum='Kubernetes.Role.Kind', - ) - ns: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - class Binding(proto.Message): - r"""Represents a Kubernetes RoleBinding or ClusterRoleBinding. - - Attributes: - ns (str): - Namespace for the binding. - name (str): - Name for the binding. - role (google.cloud.securitycenter_v2.types.Kubernetes.Role): - The Role or ClusterRole referenced by the - binding. - subjects (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Subject]): - Represents one or more subjects that are - bound to the role. Not always available for - PATCH requests. - """ - - ns: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - role: 'Kubernetes.Role' = proto.Field( - proto.MESSAGE, - number=3, - message='Kubernetes.Role', - ) - subjects: MutableSequence['Kubernetes.Subject'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Kubernetes.Subject', - ) - - class Subject(proto.Message): - r"""Represents a Kubernetes subject. - - Attributes: - kind (google.cloud.securitycenter_v2.types.Kubernetes.Subject.AuthType): - Authentication type for the subject. - ns (str): - Namespace for the subject. - name (str): - Name for the subject. - """ - class AuthType(proto.Enum): - r"""Auth types that can be used for the subject's kind field. - - Values: - AUTH_TYPE_UNSPECIFIED (0): - Authentication is not specified. - USER (1): - User with valid certificate. - SERVICEACCOUNT (2): - Users managed by Kubernetes API with - credentials stored as secrets. - GROUP (3): - Collection of users. - """ - AUTH_TYPE_UNSPECIFIED = 0 - USER = 1 - SERVICEACCOUNT = 2 - GROUP = 3 - - kind: 'Kubernetes.Subject.AuthType' = proto.Field( - proto.ENUM, - number=1, - enum='Kubernetes.Subject.AuthType', - ) - ns: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - class AccessReview(proto.Message): - r"""Conveys information about a Kubernetes access review (such as one - returned by a - ```kubectl auth can-i`` `__ - command) that was involved in a finding. - - Attributes: - group (str): - The API group of the resource. "*" means all. - ns (str): - Namespace of the action being requested. - Currently, there is no distinction between no - namespace and all namespaces. Both are - represented by "" (empty). - name (str): - The name of the resource being requested. - Empty means all. - resource (str): - The optional resource type requested. "*" means all. - subresource (str): - The optional subresource type. - verb (str): - A Kubernetes resource API verb, like get, list, watch, - create, update, delete, proxy. "*" means all. - version (str): - The API version of the resource. "*" means all. - """ - - group: str = proto.Field( - proto.STRING, - number=1, - ) - ns: str = proto.Field( - proto.STRING, - number=2, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - resource: str = proto.Field( - proto.STRING, - number=4, - ) - subresource: str = proto.Field( - proto.STRING, - number=5, - ) - verb: str = proto.Field( - proto.STRING, - number=6, - ) - version: str = proto.Field( - proto.STRING, - number=7, - ) - - class Object(proto.Message): - r"""Kubernetes object related to the finding, uniquely identified - by GKNN. Used if the object Kind is not one of Pod, Node, - NodePool, Binding, or AccessReview. - - Attributes: - group (str): - Kubernetes object group, such as - "policy.k8s.io/v1". - kind (str): - Kubernetes object kind, such as "Namespace". - ns (str): - Kubernetes object namespace. Must be a valid - DNS label. Named "ns" to avoid collision with - C++ namespace keyword. For details see - https://kubernetes.io/docs/tasks/administer-cluster/namespaces/. - name (str): - Kubernetes object name. For details see - https://kubernetes.io/docs/concepts/overview/working-with-objects/names/. - containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): - Pod containers associated with this finding, - if any. - """ - - group: str = proto.Field( - proto.STRING, - number=1, - ) - kind: str = proto.Field( - proto.STRING, - number=2, - ) - ns: str = proto.Field( - proto.STRING, - number=3, - ) - name: str = proto.Field( - proto.STRING, - number=4, - ) - containers: MutableSequence[container.Container] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=container.Container, - ) - - pods: MutableSequence[Pod] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Pod, - ) - nodes: MutableSequence[Node] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Node, - ) - node_pools: MutableSequence[NodePool] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=NodePool, - ) - roles: MutableSequence[Role] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=Role, - ) - bindings: MutableSequence[Binding] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Binding, - ) - access_reviews: MutableSequence[AccessReview] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=AccessReview, - ) - objects: MutableSequence[Object] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Object, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.py deleted file mode 100644 index d2f158e10cf6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/label.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.securitycenter.v2', - manifest={ - 'Label', - }, -) - - -class Label(proto.Message): - r"""Represents a generic name-value label. A label has separate name and - value fields to support filtering with the ``contains()`` function. - For more information, see `Filtering on array-type - fields `__. - - Attributes: - name (str): - Name of the label. - value (str): - Value that corresponds to the label's name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.py deleted file mode 100644 index 95c16ba76680..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/load_balancer.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.cloud.securitycenter.v2', - manifest={ - 'LoadBalancer', - }, -) - - -class LoadBalancer(proto.Message): - r"""Contains information related to the load balancer associated - with the finding. - - Attributes: - name (str): - The name of the load balancer associated with - the finding. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py deleted file mode 100644 index 673caf996bad..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/log_entry.py +++ /dev/null @@ -1,95 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'LogEntry', - 'CloudLoggingEntry', - }, -) - - -class LogEntry(proto.Message): - r"""An individual entry in a log. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - cloud_logging_entry (google.cloud.securitycenter_v2.types.CloudLoggingEntry): - An individual entry in a log stored in Cloud - Logging. - - This field is a member of `oneof`_ ``log_entry``. - """ - - cloud_logging_entry: 'CloudLoggingEntry' = proto.Field( - proto.MESSAGE, - number=1, - oneof='log_entry', - message='CloudLoggingEntry', - ) - - -class CloudLoggingEntry(proto.Message): - r"""Metadata taken from a `Cloud Logging - LogEntry `__ - - Attributes: - insert_id (str): - A unique identifier for the log entry. - log_id (str): - The type of the log (part of ``log_name``. ``log_name`` is - the resource name of the log to which this log entry - belongs). For example: - ``cloudresourcemanager.googleapis.com/activity`` Note that - this field is not URL-encoded, unlike in ``LogEntry``. - resource_container (str): - The organization, folder, or project of the - monitored resource that produced this log entry. - timestamp (google.protobuf.timestamp_pb2.Timestamp): - The time the event described by the log entry - occurred. - """ - - insert_id: str = proto.Field( - proto.STRING, - number=1, - ) - log_id: str = proto.Field( - proto.STRING, - number=2, - ) - resource_container: str = proto.Field( - proto.STRING, - number=3, - ) - timestamp: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.py deleted file mode 100644 index d0a5c04b7853..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mitre_attack.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'MitreAttack', - }, -) - - -class MitreAttack(proto.Message): - r"""MITRE ATT&CK tactics and techniques related to this finding. - See: https://attack.mitre.org - - Attributes: - primary_tactic (google.cloud.securitycenter_v2.types.MitreAttack.Tactic): - The MITRE ATT&CK tactic most closely - represented by this finding, if any. - primary_techniques (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Technique]): - The MITRE ATT&CK technique most closely represented by this - finding, if any. primary_techniques is a repeated field - because there are multiple levels of MITRE ATT&CK - techniques. If the technique most closely represented by - this finding is a sub-technique (e.g. - ``SCANNING_IP_BLOCKS``), both the sub-technique and its - parent technique(s) will be listed (e.g. - ``SCANNING_IP_BLOCKS``, ``ACTIVE_SCANNING``). - additional_tactics (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Tactic]): - Additional MITRE ATT&CK tactics related to - this finding, if any. - additional_techniques (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Technique]): - Additional MITRE ATT&CK techniques related to - this finding, if any, along with any of their - respective parent techniques. - version (str): - The MITRE ATT&CK version referenced by the - above fields. E.g. "8". - """ - class Tactic(proto.Enum): - r"""MITRE ATT&CK tactics that can be referenced by SCC findings. - See: https://attack.mitre.org/tactics/enterprise/ - - Values: - TACTIC_UNSPECIFIED (0): - Unspecified value. - RECONNAISSANCE (1): - TA0043 - RESOURCE_DEVELOPMENT (2): - TA0042 - INITIAL_ACCESS (5): - TA0001 - EXECUTION (3): - TA0002 - PERSISTENCE (6): - TA0003 - PRIVILEGE_ESCALATION (8): - TA0004 - DEFENSE_EVASION (7): - TA0005 - CREDENTIAL_ACCESS (9): - TA0006 - DISCOVERY (10): - TA0007 - LATERAL_MOVEMENT (11): - TA0008 - COLLECTION (12): - TA0009 - COMMAND_AND_CONTROL (4): - TA0011 - EXFILTRATION (13): - TA0010 - IMPACT (14): - TA0040 - """ - TACTIC_UNSPECIFIED = 0 - RECONNAISSANCE = 1 - RESOURCE_DEVELOPMENT = 2 - INITIAL_ACCESS = 5 - EXECUTION = 3 - PERSISTENCE = 6 - PRIVILEGE_ESCALATION = 8 - DEFENSE_EVASION = 7 - CREDENTIAL_ACCESS = 9 - DISCOVERY = 10 - LATERAL_MOVEMENT = 11 - COLLECTION = 12 - COMMAND_AND_CONTROL = 4 - EXFILTRATION = 13 - IMPACT = 14 - - class Technique(proto.Enum): - r"""MITRE ATT&CK techniques that can be referenced by SCC - findings. See: https://attack.mitre.org/techniques/enterprise/ - Next ID: 65 - - Values: - TECHNIQUE_UNSPECIFIED (0): - Unspecified value. - MASQUERADING (49): - T1036 - MATCH_LEGITIMATE_NAME_OR_LOCATION (50): - T1036.005 - BOOT_OR_LOGON_INITIALIZATION_SCRIPTS (37): - T1037 - STARTUP_ITEMS (38): - T1037.005 - NETWORK_SERVICE_DISCOVERY (32): - T1046 - PROCESS_DISCOVERY (56): - T1057 - COMMAND_AND_SCRIPTING_INTERPRETER (6): - T1059 - UNIX_SHELL (7): - T1059.004 - PYTHON (59): - T1059.006 - EXPLOITATION_FOR_PRIVILEGE_ESCALATION (63): - T1068 - PERMISSION_GROUPS_DISCOVERY (18): - T1069 - CLOUD_GROUPS (19): - T1069.003 - INDICATOR_REMOVAL_FILE_DELETION (64): - T1070.004 - APPLICATION_LAYER_PROTOCOL (45): - T1071 - DNS (46): - T1071.004 - SOFTWARE_DEPLOYMENT_TOOLS (47): - T1072 - VALID_ACCOUNTS (14): - T1078 - DEFAULT_ACCOUNTS (35): - T1078.001 - LOCAL_ACCOUNTS (15): - T1078.003 - CLOUD_ACCOUNTS (16): - T1078.004 - PROXY (9): - T1090 - EXTERNAL_PROXY (10): - T1090.002 - MULTI_HOP_PROXY (11): - T1090.003 - ACCOUNT_MANIPULATION (22): - T1098 - ADDITIONAL_CLOUD_CREDENTIALS (40): - T1098.001 - SSH_AUTHORIZED_KEYS (23): - T1098.004 - ADDITIONAL_CONTAINER_CLUSTER_ROLES (58): - T1098.006 - INGRESS_TOOL_TRANSFER (3): - T1105 - NATIVE_API (4): - T1106 - BRUTE_FORCE (44): - T1110 - SHARED_MODULES (5): - T1129 - ACCESS_TOKEN_MANIPULATION (33): - T1134 - TOKEN_IMPERSONATION_OR_THEFT (39): - T1134.001 - EXPLOIT_PUBLIC_FACING_APPLICATION (27): - T1190 - DOMAIN_POLICY_MODIFICATION (30): - T1484 - DATA_DESTRUCTION (29): - T1485 - SERVICE_STOP (52): - T1489 - INHIBIT_SYSTEM_RECOVERY (36): - T1490 - RESOURCE_HIJACKING (8): - T1496 - NETWORK_DENIAL_OF_SERVICE (17): - T1498 - CLOUD_SERVICE_DISCOVERY (48): - T1526 - STEAL_APPLICATION_ACCESS_TOKEN (42): - T1528 - ACCOUNT_ACCESS_REMOVAL (51): - T1531 - STEAL_WEB_SESSION_COOKIE (25): - T1539 - CREATE_OR_MODIFY_SYSTEM_PROCESS (24): - T1543 - ABUSE_ELEVATION_CONTROL_MECHANISM (34): - T1548 - UNSECURED_CREDENTIALS (13): - T1552 - MODIFY_AUTHENTICATION_PROCESS (28): - T1556 - IMPAIR_DEFENSES (31): - T1562 - DISABLE_OR_MODIFY_TOOLS (55): - T1562.001 - EXFILTRATION_OVER_WEB_SERVICE (20): - T1567 - EXFILTRATION_TO_CLOUD_STORAGE (21): - T1567.002 - DYNAMIC_RESOLUTION (12): - T1568 - LATERAL_TOOL_TRANSFER (41): - T1570 - MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE (26): - T1578 - CREATE_SNAPSHOT (54): - T1578.001 - CLOUD_INFRASTRUCTURE_DISCOVERY (53): - T1580 - OBTAIN_CAPABILITIES (43): - T1588 - ACTIVE_SCANNING (1): - T1595 - SCANNING_IP_BLOCKS (2): - T1595.001 - CONTAINER_ADMINISTRATION_COMMAND (60): - T1609 - ESCAPE_TO_HOST (61): - T1611 - CONTAINER_AND_RESOURCE_DISCOVERY (57): - T1613 - STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES (62): - T1649 - """ - TECHNIQUE_UNSPECIFIED = 0 - MASQUERADING = 49 - MATCH_LEGITIMATE_NAME_OR_LOCATION = 50 - BOOT_OR_LOGON_INITIALIZATION_SCRIPTS = 37 - STARTUP_ITEMS = 38 - NETWORK_SERVICE_DISCOVERY = 32 - PROCESS_DISCOVERY = 56 - COMMAND_AND_SCRIPTING_INTERPRETER = 6 - UNIX_SHELL = 7 - PYTHON = 59 - EXPLOITATION_FOR_PRIVILEGE_ESCALATION = 63 - PERMISSION_GROUPS_DISCOVERY = 18 - CLOUD_GROUPS = 19 - INDICATOR_REMOVAL_FILE_DELETION = 64 - APPLICATION_LAYER_PROTOCOL = 45 - DNS = 46 - SOFTWARE_DEPLOYMENT_TOOLS = 47 - VALID_ACCOUNTS = 14 - DEFAULT_ACCOUNTS = 35 - LOCAL_ACCOUNTS = 15 - CLOUD_ACCOUNTS = 16 - PROXY = 9 - EXTERNAL_PROXY = 10 - MULTI_HOP_PROXY = 11 - ACCOUNT_MANIPULATION = 22 - ADDITIONAL_CLOUD_CREDENTIALS = 40 - SSH_AUTHORIZED_KEYS = 23 - ADDITIONAL_CONTAINER_CLUSTER_ROLES = 58 - INGRESS_TOOL_TRANSFER = 3 - NATIVE_API = 4 - BRUTE_FORCE = 44 - SHARED_MODULES = 5 - ACCESS_TOKEN_MANIPULATION = 33 - TOKEN_IMPERSONATION_OR_THEFT = 39 - EXPLOIT_PUBLIC_FACING_APPLICATION = 27 - DOMAIN_POLICY_MODIFICATION = 30 - DATA_DESTRUCTION = 29 - SERVICE_STOP = 52 - INHIBIT_SYSTEM_RECOVERY = 36 - RESOURCE_HIJACKING = 8 - NETWORK_DENIAL_OF_SERVICE = 17 - CLOUD_SERVICE_DISCOVERY = 48 - STEAL_APPLICATION_ACCESS_TOKEN = 42 - ACCOUNT_ACCESS_REMOVAL = 51 - STEAL_WEB_SESSION_COOKIE = 25 - CREATE_OR_MODIFY_SYSTEM_PROCESS = 24 - ABUSE_ELEVATION_CONTROL_MECHANISM = 34 - UNSECURED_CREDENTIALS = 13 - MODIFY_AUTHENTICATION_PROCESS = 28 - IMPAIR_DEFENSES = 31 - DISABLE_OR_MODIFY_TOOLS = 55 - EXFILTRATION_OVER_WEB_SERVICE = 20 - EXFILTRATION_TO_CLOUD_STORAGE = 21 - DYNAMIC_RESOLUTION = 12 - LATERAL_TOOL_TRANSFER = 41 - MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE = 26 - CREATE_SNAPSHOT = 54 - CLOUD_INFRASTRUCTURE_DISCOVERY = 53 - OBTAIN_CAPABILITIES = 43 - ACTIVE_SCANNING = 1 - SCANNING_IP_BLOCKS = 2 - CONTAINER_ADMINISTRATION_COMMAND = 60 - ESCAPE_TO_HOST = 61 - CONTAINER_AND_RESOURCE_DISCOVERY = 57 - STEAL_OR_FORGE_AUTHENTICATION_CERTIFICATES = 62 - - primary_tactic: Tactic = proto.Field( - proto.ENUM, - number=1, - enum=Tactic, - ) - primary_techniques: MutableSequence[Technique] = proto.RepeatedField( - proto.ENUM, - number=2, - enum=Technique, - ) - additional_tactics: MutableSequence[Tactic] = proto.RepeatedField( - proto.ENUM, - number=3, - enum=Tactic, - ) - additional_techniques: MutableSequence[Technique] = proto.RepeatedField( - proto.ENUM, - number=4, - enum=Technique, - ) - version: str = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.py deleted file mode 100644 index 47f95ac38c38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/mute_config.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.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'MuteConfig', - }, -) - - -class MuteConfig(proto.Message): - r"""A mute config is a Cloud SCC resource that contains the - configuration to mute create/update events of findings. - - Attributes: - name (str): - Identifier. This field will be ignored if provided on config - creation. The following list shows some examples of the - format: - - - ``organizations/{organization}/muteConfigs/{mute_config}`` - - - - ``organizations/{organization}locations/{location}//muteConfigs/{mute_config}`` - - - ``folders/{folder}/muteConfigs/{mute_config}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{mute_config}`` - - ``projects/{project}/muteConfigs/{mute_config}`` - - ``projects/{project}/locations/{location}/muteConfigs/{mute_config}`` - description (str): - A description of the mute config. - filter (str): - Required. An expression that defines the filter to apply - across create/update events of findings. While creating a - filter string, be mindful of the scope in which the mute - configuration is being created. E.g., If a filter contains - project = X but is created under the project = Y scope, it - might not match any findings. - - The following field and operator combinations are supported: - - - severity: ``=``, ``:`` - - category: ``=``, ``:`` - - resource.name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.folders.resource_folder: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - - finding_class: ``=``, ``:`` - - indicator.ip_addresses: ``=``, ``:`` - - indicator.domains: ``=``, ``:`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the mute - config was created. This field is set by the - server and will be ignored if provided on config - creation. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The most recent time at which - the mute config was updated. This field is set - by the server and will be ignored if provided on - config creation or update. - most_recent_editor (str): - Output only. Email address of the user who - last edited the mute config. This field is set - by the server and will be ignored if provided on - config creation or update. - type_ (google.cloud.securitycenter_v2.types.MuteConfig.MuteConfigType): - Required. The type of the mute config, which - determines what type of mute state the config - affects. Immutable after creation. - expiry_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The expiry of the mute config. Only - applicable for dynamic configs. If the expiry is - set, when the config expires, it is removed from - all findings. - """ - class MuteConfigType(proto.Enum): - r"""The type of MuteConfig. - - Values: - MUTE_CONFIG_TYPE_UNSPECIFIED (0): - Unused. - STATIC (1): - A static mute config, which sets the static - mute state of future matching findings to muted. - Once the static mute state has been set, finding - or config modifications will not affect the - state. - DYNAMIC (2): - A dynamic mute config, which is applied to - existing and future matching findings, setting - their dynamic mute state to "muted". If the - config is updated or deleted, or a matching - finding is updated, such that the finding - doesn't match the config, the config will be - removed from the finding, and the finding's - dynamic mute state may become "unmuted" (unless - other configs still match). - """ - MUTE_CONFIG_TYPE_UNSPECIFIED = 0 - STATIC = 1 - DYNAMIC = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - filter: str = proto.Field( - proto.STRING, - number=3, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - most_recent_editor: str = proto.Field( - proto.STRING, - number=6, - ) - type_: MuteConfigType = proto.Field( - proto.ENUM, - number=8, - enum=MuteConfigType, - ) - expiry_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py deleted file mode 100644 index 6fe873edc33e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notebook.py +++ /dev/null @@ -1,72 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter.v2', - manifest={ - 'Notebook', - }, -) - - -class Notebook(proto.Message): - r"""Represents a Jupyter notebook IPYNB file, such as a `Colab - Enterprise - notebook `__ file, - that is associated with a finding. - - Attributes: - name (str): - The name of the notebook. - service (str): - The source notebook service, for example, - "Colab Enterprise". - last_author (str): - The user ID of the latest author to modify - the notebook. - notebook_update_time (google.protobuf.timestamp_pb2.Timestamp): - The most recent time the notebook was - updated. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - service: str = proto.Field( - proto.STRING, - number=2, - ) - last_author: str = proto.Field( - proto.STRING, - number=3, - ) - notebook_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py deleted file mode 100644 index 73797dfbbbb8..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_config.py +++ /dev/null @@ -1,129 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v2', - manifest={ - 'NotificationConfig', - }, -) - - -class NotificationConfig(proto.Message): - r"""Cloud Security Command Center (Cloud SCC) notification - configs. - A notification config is a Cloud SCC resource that contains the - configuration to send notifications for create/update events of - findings, assets and etc. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Identifier. The relative resource name of this notification - config. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - The following list shows some examples: + - ``organizations/{organization_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` - + - ``folders/{folder_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` - + - ``projects/{project_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` - description (str): - The description of the notification config - (max of 1024 characters). - pubsub_topic (str): - The Pub/Sub topic to send notifications to. Its format is - "projects/[project_id]/topics/[topic]". - service_account (str): - Output only. The service account that needs - "pubsub.topics.publish" permission to publish to - the Pub/Sub topic. - streaming_config (google.cloud.securitycenter_v2.types.NotificationConfig.StreamingConfig): - The config for triggering streaming-based - notifications. - - This field is a member of `oneof`_ ``notify_config``. - """ - - class StreamingConfig(proto.Message): - r"""The config for streaming-based notifications, which send each - event as soon as it is detected. - - Attributes: - filter (str): - Expression that defines the filter to apply across - create/update events of assets or findings as specified by - the event type. The expression is a list of zero or more - restrictions combined via logical operators ``AND`` and - ``OR``. Parentheses are supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - """ - - filter: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - pubsub_topic: str = proto.Field( - proto.STRING, - number=3, - ) - service_account: str = proto.Field( - proto.STRING, - number=4, - ) - streaming_config: StreamingConfig = proto.Field( - proto.MESSAGE, - number=5, - oneof='notify_config', - message=StreamingConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.py deleted file mode 100644 index cbe17b52c42a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/notification_message.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import resource as gcs_resource - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'NotificationMessage', - }, -) - - -class NotificationMessage(proto.Message): - r"""Cloud SCC's Notification - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - notification_config_name (str): - Name of the notification config that - generated current notification. - finding (google.cloud.securitycenter_v2.types.Finding): - If it's a Finding based notification config, - this field will be populated. - - This field is a member of `oneof`_ ``event``. - resource (google.cloud.securitycenter_v2.types.Resource): - The Cloud resource tied to this - notification's Finding. - """ - - notification_config_name: str = proto.Field( - proto.STRING, - number=1, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=2, - oneof='event', - message=gcs_finding.Finding, - ) - resource: gcs_resource.Resource = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_resource.Resource, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.py deleted file mode 100644 index afd2ecb275f7..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/org_policy.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.cloud.securitycenter.v2', - manifest={ - 'OrgPolicy', - }, -) - - -class OrgPolicy(proto.Message): - r"""Contains information about the org policies associated with - the finding. - - Attributes: - name (str): - The resource name of the org policy. Example: - "organizations/{organization_id}/policies/{constraint_name}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py deleted file mode 100644 index 567e7cceaa35..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/process.py +++ /dev/null @@ -1,136 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v2.types import file - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Process', - 'EnvironmentVariable', - }, -) - - -class Process(proto.Message): - r"""Represents an operating system process. - - Attributes: - name (str): - The process name, as displayed in utilities like ``top`` and - ``ps``. This name can be accessed through - ``/proc/[pid]/comm`` and changed with - ``prctl(PR_SET_NAME)``. - binary (google.cloud.securitycenter_v2.types.File): - File information for the process executable. - libraries (MutableSequence[google.cloud.securitycenter_v2.types.File]): - File information for libraries loaded by the - process. - script (google.cloud.securitycenter_v2.types.File): - When the process represents the invocation of a script, - ``binary`` provides information about the interpreter, while - ``script`` provides information about the script file - provided to the interpreter. - args (MutableSequence[str]): - Process arguments as JSON encoded strings. - arguments_truncated (bool): - True if ``args`` is incomplete. - env_variables (MutableSequence[google.cloud.securitycenter_v2.types.EnvironmentVariable]): - Process environment variables. - env_variables_truncated (bool): - True if ``env_variables`` is incomplete. - pid (int): - The process ID. - parent_pid (int): - The parent process ID. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - binary: file.File = proto.Field( - proto.MESSAGE, - number=2, - message=file.File, - ) - libraries: MutableSequence[file.File] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=file.File, - ) - script: file.File = proto.Field( - proto.MESSAGE, - number=4, - message=file.File, - ) - args: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - arguments_truncated: bool = proto.Field( - proto.BOOL, - number=6, - ) - env_variables: MutableSequence['EnvironmentVariable'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='EnvironmentVariable', - ) - env_variables_truncated: bool = proto.Field( - proto.BOOL, - number=8, - ) - pid: int = proto.Field( - proto.INT64, - number=9, - ) - parent_pid: int = proto.Field( - proto.INT64, - number=10, - ) - - -class EnvironmentVariable(proto.Message): - r"""A name-value pair representing an environment variable used - in an operating system process. - - Attributes: - name (str): - Environment variable name as a JSON encoded - string. - val (str): - Environment variable value as a JSON encoded - string. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - val: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.py deleted file mode 100644 index 491062813849..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource.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 - -from google.cloud.securitycenter_v2.types import folder - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'CloudProvider', - 'Resource', - 'GcpMetadata', - 'AwsMetadata', - 'AzureMetadata', - 'ResourcePath', - }, -) - - -class CloudProvider(proto.Enum): - r"""The cloud provider the finding pertains to. - - Values: - CLOUD_PROVIDER_UNSPECIFIED (0): - The cloud provider is unspecified. - GOOGLE_CLOUD_PLATFORM (1): - The cloud provider is Google Cloud Platform. - AMAZON_WEB_SERVICES (2): - The cloud provider is Amazon Web Services. - MICROSOFT_AZURE (3): - The cloud provider is Microsoft Azure. - """ - CLOUD_PROVIDER_UNSPECIFIED = 0 - GOOGLE_CLOUD_PLATFORM = 1 - AMAZON_WEB_SERVICES = 2 - MICROSOFT_AZURE = 3 - - -class Resource(proto.Message): - r"""Information related to the Google Cloud 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): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - display_name (str): - The human readable name of the resource. - type_ (str): - The full resource type of the resource. - cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): - Indicates which cloud provider the finding is - from. - service (str): - The service or resource provider associated - with the resource. - location (str): - The region or location of the service (if - applicable). - gcp_metadata (google.cloud.securitycenter_v2.types.GcpMetadata): - The GCP metadata associated with the finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - aws_metadata (google.cloud.securitycenter_v2.types.AwsMetadata): - The AWS metadata associated with the finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - azure_metadata (google.cloud.securitycenter_v2.types.AzureMetadata): - The Azure metadata associated with the - finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - resource_path (google.cloud.securitycenter_v2.types.ResourcePath): - Provides the path to the resource within the - resource hierarchy. - resource_path_string (str): - A string representation of the resource path. For Google - Cloud, it has the format of - ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` - where there can be any number of folders. For AWS, it has - the format of - ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` - where there can be any number of organizational units. For - Azure, it has the format of - ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` - where there can be any number of management groups. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - type_: str = proto.Field( - proto.STRING, - number=3, - ) - cloud_provider: 'CloudProvider' = proto.Field( - proto.ENUM, - number=4, - enum='CloudProvider', - ) - service: str = proto.Field( - proto.STRING, - number=5, - ) - location: str = proto.Field( - proto.STRING, - number=6, - ) - gcp_metadata: 'GcpMetadata' = proto.Field( - proto.MESSAGE, - number=7, - oneof='cloud_provider_metadata', - message='GcpMetadata', - ) - aws_metadata: 'AwsMetadata' = proto.Field( - proto.MESSAGE, - number=8, - oneof='cloud_provider_metadata', - message='AwsMetadata', - ) - azure_metadata: 'AzureMetadata' = proto.Field( - proto.MESSAGE, - number=9, - oneof='cloud_provider_metadata', - message='AzureMetadata', - ) - resource_path: 'ResourcePath' = proto.Field( - proto.MESSAGE, - number=10, - message='ResourcePath', - ) - resource_path_string: str = proto.Field( - proto.STRING, - number=11, - ) - - -class GcpMetadata(proto.Message): - r"""GCP metadata associated with the resource, only applicable if - the finding's cloud provider is Google Cloud Platform. - - Attributes: - project (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The project ID that the resource belongs to. - parent (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (MutableSequence[google.cloud.securitycenter_v2.types.Folder]): - Output only. Contains a Folder message for - each folder in the assets ancestry. The first - folder is the deepest nested folder, and the - last folder is the folder directly under the - Organization. - organization (str): - The name of the organization that the - resource belongs to. - """ - - project: str = proto.Field( - proto.STRING, - number=1, - ) - project_display_name: str = proto.Field( - proto.STRING, - number=2, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - parent_display_name: str = proto.Field( - proto.STRING, - number=4, - ) - folders: MutableSequence[folder.Folder] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=folder.Folder, - ) - organization: str = proto.Field( - proto.STRING, - number=6, - ) - - -class AwsMetadata(proto.Message): - r"""AWS metadata associated with the resource, only applicable if - the finding's cloud provider is Amazon Web Services. - - Attributes: - organization (google.cloud.securitycenter_v2.types.AwsMetadata.AwsOrganization): - The AWS organization associated with the - resource. - organizational_units (MutableSequence[google.cloud.securitycenter_v2.types.AwsMetadata.AwsOrganizationalUnit]): - A list of AWS organizational units associated - with the resource, ordered from lowest level - (closest to the account) to highest level. - account (google.cloud.securitycenter_v2.types.AwsMetadata.AwsAccount): - The AWS account associated with the resource. - """ - - class AwsOrganization(proto.Message): - r"""An organization is a collection of accounts that are - centrally managed together using consolidated billing, organized - hierarchically with organizational units (OUs), and controlled - with policies. - - Attributes: - id (str): - The unique identifier (ID) for the - organization. The regex pattern for an - organization ID string requires "o-" followed by - from 10 to 32 lowercase letters or digits. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - - class AwsOrganizationalUnit(proto.Message): - r"""An Organizational Unit (OU) is a container of AWS accounts - within a root of an organization. Policies that are attached to - an OU apply to all accounts contained in that OU and in any - child OUs. - - Attributes: - id (str): - The unique identifier (ID) associated with - this OU. The regex pattern for an organizational - unit ID string requires "ou-" followed by from 4 - to 32 lowercase letters or digits (the ID of the - root that contains the OU). This string is - followed by a second "-" dash and from 8 to 32 - additional lowercase letters or digits. For - example, "ou-ab12-cd34ef56". - name (str): - The friendly name of the OU. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - - class AwsAccount(proto.Message): - r"""An AWS account that is a member of an organization. - - Attributes: - id (str): - The unique identifier (ID) of the account, - containing exactly 12 digits. - name (str): - The friendly name of this account. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - - organization: AwsOrganization = proto.Field( - proto.MESSAGE, - number=1, - message=AwsOrganization, - ) - organizational_units: MutableSequence[AwsOrganizationalUnit] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=AwsOrganizationalUnit, - ) - account: AwsAccount = proto.Field( - proto.MESSAGE, - number=3, - message=AwsAccount, - ) - - -class AzureMetadata(proto.Message): - r"""Azure metadata associated with the resource, only applicable - if the finding's cloud provider is Microsoft Azure. - - Attributes: - management_groups (MutableSequence[google.cloud.securitycenter_v2.types.AzureMetadata.AzureManagementGroup]): - A list of Azure management groups associated - with the resource, ordered from lowest level - (closest to the subscription) to highest level. - subscription (google.cloud.securitycenter_v2.types.AzureMetadata.AzureSubscription): - The Azure subscription associated with the - resource. - resource_group (google.cloud.securitycenter_v2.types.AzureMetadata.AzureResourceGroup): - The Azure resource group associated with the - resource. - """ - - class AzureManagementGroup(proto.Message): - r"""Represents an Azure management group. - - Attributes: - id (str): - The UUID of the Azure management group, for example, - ``20000000-0001-0000-0000-000000000000``. - display_name (str): - The display name of the Azure management - group. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - class AzureSubscription(proto.Message): - r"""Represents an Azure subscription. - - Attributes: - id (str): - The UUID of the Azure subscription, for example, - ``291bba3f-e0a5-47bc-a099-3bdcb2a50a05``. - display_name (str): - The display name of the Azure subscription. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - - class AzureResourceGroup(proto.Message): - r"""Represents an Azure resource group. - - Attributes: - name (str): - The name of the Azure resource group. This is - not a UUID. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - management_groups: MutableSequence[AzureManagementGroup] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=AzureManagementGroup, - ) - subscription: AzureSubscription = proto.Field( - proto.MESSAGE, - number=2, - message=AzureSubscription, - ) - resource_group: AzureResourceGroup = proto.Field( - proto.MESSAGE, - number=3, - message=AzureResourceGroup, - ) - - -class ResourcePath(proto.Message): - r"""Represents the path of resources leading up to the resource - this finding is about. - - Attributes: - nodes (MutableSequence[google.cloud.securitycenter_v2.types.ResourcePath.ResourcePathNode]): - The list of nodes that make the up resource - path, ordered from lowest level to highest - level. - """ - class ResourcePathNodeType(proto.Enum): - r"""The type of resource the node represents. - - Values: - RESOURCE_PATH_NODE_TYPE_UNSPECIFIED (0): - Node type is unspecified. - GCP_ORGANIZATION (1): - The node represents a Google Cloud - organization. - GCP_FOLDER (2): - The node represents a Google Cloud folder. - GCP_PROJECT (3): - The node represents a Google Cloud project. - AWS_ORGANIZATION (4): - The node represents an AWS organization. - AWS_ORGANIZATIONAL_UNIT (5): - The node represents an AWS organizational - unit. - AWS_ACCOUNT (6): - The node represents an AWS account. - AZURE_MANAGEMENT_GROUP (7): - The node represents an Azure management - group. - AZURE_SUBSCRIPTION (8): - The node represents an Azure subscription. - AZURE_RESOURCE_GROUP (9): - The node represents an Azure resource group. - """ - RESOURCE_PATH_NODE_TYPE_UNSPECIFIED = 0 - GCP_ORGANIZATION = 1 - GCP_FOLDER = 2 - GCP_PROJECT = 3 - AWS_ORGANIZATION = 4 - AWS_ORGANIZATIONAL_UNIT = 5 - AWS_ACCOUNT = 6 - AZURE_MANAGEMENT_GROUP = 7 - AZURE_SUBSCRIPTION = 8 - AZURE_RESOURCE_GROUP = 9 - - class ResourcePathNode(proto.Message): - r"""A node within the resource path. Each node represents a - resource within the resource hierarchy. - - Attributes: - node_type (google.cloud.securitycenter_v2.types.ResourcePath.ResourcePathNodeType): - The type of resource this node represents. - id (str): - The ID of the resource this node represents. - display_name (str): - The display name of the resource this node - represents. - """ - - node_type: 'ResourcePath.ResourcePathNodeType' = proto.Field( - proto.ENUM, - number=1, - enum='ResourcePath.ResourcePathNodeType', - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - - nodes: MutableSequence[ResourcePathNode] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ResourcePathNode, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py deleted file mode 100644 index 49a600dd79e3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/resource_value_config.py +++ /dev/null @@ -1,190 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v2.types import resource -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'ResourceValue', - 'ResourceValueConfig', - }, -) - - -class ResourceValue(proto.Enum): - r"""Value enum to map to a resource - - Values: - RESOURCE_VALUE_UNSPECIFIED (0): - Unspecific value - HIGH (1): - High resource value - MEDIUM (2): - Medium resource value - LOW (3): - Low resource value - NONE (4): - No resource value, e.g. ignore these - resources - """ - RESOURCE_VALUE_UNSPECIFIED = 0 - HIGH = 1 - MEDIUM = 2 - LOW = 3 - NONE = 4 - - -class ResourceValueConfig(proto.Message): - r"""A resource value configuration (RVC) is a mapping - configuration of user's resources to resource values. Used in - Attack path simulations. - - Attributes: - name (str): - Identifier. Name for the resource value - configuration - resource_value (google.cloud.securitycenter_v2.types.ResourceValue): - Resource value level this expression - represents Only required when there is no - Sensitive Data Protection mapping in the request - tag_values (MutableSequence[str]): - Tag values combined with ``AND`` to check against. Values in - the form "tagValues/123" Example: - ``[ "tagValues/123", "tagValues/456", "tagValues/789" ]`` - https://cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing - resource_type (str): - Apply resource_value only to resources that match - resource_type. resource_type will be checked with ``AND`` of - other resources. For example, - "storage.googleapis.com/Bucket" with resource_value "HIGH" - will apply "HIGH" value only to - "storage.googleapis.com/Bucket" resources. - scope (str): - Project or folder to scope this configuration to. For - example, "project/456" would apply this configuration only - to resources in "project/456" scope and will be checked with - ``AND`` of other resources. - resource_labels_selector (MutableMapping[str, str]): - List of resource labels to search for, evaluated with - ``AND``. For example, "resource_labels_selector": {"key": - "value", "env": "prod"} will match resources with labels - "key": "value" ``AND`` "env": "prod" - https://cloud.google.com/resource-manager/docs/creating-managing-labels - description (str): - Description of the resource value - configuration. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp this resource value - configuration was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp this resource value - configuration was last updated. - cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): - Cloud provider this configuration applies to - sensitive_data_protection_mapping (google.cloud.securitycenter_v2.types.ResourceValueConfig.SensitiveDataProtectionMapping): - A mapping of the sensitivity on Sensitive Data Protection - finding to resource values. This mapping can only be used in - combination with a resource_type that is related to - BigQuery, e.g. "bigquery.googleapis.com/Dataset". - """ - - class SensitiveDataProtectionMapping(proto.Message): - r"""Resource value mapping for Sensitive Data Protection findings If any - of these mappings have a resource value that is not unspecified, the - resource_value field will be ignored when reading this - configuration. - - Attributes: - high_sensitivity_mapping (google.cloud.securitycenter_v2.types.ResourceValue): - Resource value mapping for high-sensitivity - Sensitive Data Protection findings - medium_sensitivity_mapping (google.cloud.securitycenter_v2.types.ResourceValue): - Resource value mapping for medium-sensitivity - Sensitive Data Protection findings - """ - - high_sensitivity_mapping: 'ResourceValue' = proto.Field( - proto.ENUM, - number=1, - enum='ResourceValue', - ) - medium_sensitivity_mapping: 'ResourceValue' = proto.Field( - proto.ENUM, - number=2, - enum='ResourceValue', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - resource_value: 'ResourceValue' = proto.Field( - proto.ENUM, - number=2, - enum='ResourceValue', - ) - tag_values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - resource_type: str = proto.Field( - proto.STRING, - number=4, - ) - scope: str = proto.Field( - proto.STRING, - number=5, - ) - resource_labels_selector: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=6, - ) - description: str = proto.Field( - proto.STRING, - number=7, - ) - 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, - ) - cloud_provider: resource.CloudProvider = proto.Field( - proto.ENUM, - number=10, - enum=resource.CloudProvider, - ) - sensitive_data_protection_mapping: SensitiveDataProtectionMapping = proto.Field( - proto.MESSAGE, - number=11, - message=SensitiveDataProtectionMapping, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py deleted file mode 100644 index 69a449132422..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_marks.py +++ /dev/null @@ -1,101 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License 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.securitycenter.v2', - manifest={ - 'SecurityMarks', - }, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - The following list shows some examples: - - - ``organizations/{organization_id}/assets/{asset_id}/securityMarks`` - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` - marks (MutableMapping[str, str]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - canonical_name (str): - The canonical name of the marks. The following list shows - some examples: - - - ``organizations/{organization_id}/assets/{asset_id}/securityMarks`` - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` - - - ``folders/{folder_id}/assets/{asset_id}/securityMarks`` - - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks`` - + - ``folders/{folder_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` - - - ``projects/{project_number}/assets/{asset_id}/securityMarks`` - - - - ``projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks`` - + - ``projects/{project_number}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - marks: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.py deleted file mode 100644 index efa7cfc0b14d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/security_posture.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'SecurityPosture', - }, -) - - -class SecurityPosture(proto.Message): - r"""Represents a posture that is deployed on Google Cloud by the - Security Command Center Posture Management service. A posture - contains one or more policy sets. A policy set is a group of - policies that enforce a set of security rules on Google Cloud. - - Attributes: - name (str): - Name of the posture, for example, ``CIS-Posture``. - revision_id (str): - The version of the posture, for example, ``c7cfa2a8``. - posture_deployment_resource (str): - The project, folder, or organization on which the posture is - deployed, for example, ``projects/{project_number}``. - posture_deployment (str): - The name of the posture deployment, for example, - ``organizations/{org_id}/posturedeployments/{posture_deployment_id}``. - changed_policy (str): - The name of the updated policy, for example, - ``projects/{project_id}/policies/{constraint_name}``. - policy_set (str): - The name of the updated policy set, for example, - ``cis-policyset``. - policy (str): - The ID of the updated policy, for example, - ``compute-policy-1``. - policy_drift_details (MutableSequence[google.cloud.securitycenter_v2.types.SecurityPosture.PolicyDriftDetails]): - The details about a change in an updated - policy that violates the deployed posture. - """ - - class PolicyDriftDetails(proto.Message): - r"""The policy field that violates the deployed posture and its - expected and detected values. - - Attributes: - field (str): - The name of the updated field, for example - constraint.implementation.policy_rules[0].enforce - expected_value (str): - The value of this field that was configured in a posture, - for example, ``true`` or - ``allowed_values={"projects/29831892"}``. - detected_value (str): - The detected value that violates the deployed posture, for - example, ``false`` or - ``allowed_values={"projects/22831892"}``. - """ - - field: str = proto.Field( - proto.STRING, - number=1, - ) - expected_value: str = proto.Field( - proto.STRING, - number=2, - ) - detected_value: str = proto.Field( - proto.STRING, - number=3, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - ) - posture_deployment_resource: str = proto.Field( - proto.STRING, - number=3, - ) - posture_deployment: str = proto.Field( - proto.STRING, - number=4, - ) - changed_policy: str = proto.Field( - proto.STRING, - number=5, - ) - policy_set: str = proto.Field( - proto.STRING, - number=6, - ) - policy: str = proto.Field( - proto.STRING, - number=7, - ) - policy_drift_details: MutableSequence[PolicyDriftDetails] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=PolicyDriftDetails, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py deleted file mode 100644 index fdc56c6556a4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/securitycenter_service.py +++ /dev/null @@ -1,1932 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v2.types import attack_path -from google.cloud.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import resource as gcs_resource -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import valued_resource -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'BatchCreateResourceValueConfigsRequest', - 'BatchCreateResourceValueConfigsResponse', - 'BulkMuteFindingsRequest', - 'BulkMuteFindingsResponse', - 'CreateBigQueryExportRequest', - 'CreateFindingRequest', - 'CreateMuteConfigRequest', - 'CreateNotificationConfigRequest', - 'CreateResourceValueConfigRequest', - 'CreateSourceRequest', - 'DeleteBigQueryExportRequest', - 'DeleteMuteConfigRequest', - 'DeleteNotificationConfigRequest', - 'DeleteResourceValueConfigRequest', - 'GetBigQueryExportRequest', - 'GetMuteConfigRequest', - 'GetNotificationConfigRequest', - 'GetResourceValueConfigRequest', - 'GetSourceRequest', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAttackPathsRequest', - 'ListAttackPathsResponse', - 'GetSimulationRequest', - 'GetValuedResourceRequest', - 'ListBigQueryExportsRequest', - 'ListBigQueryExportsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListMuteConfigsRequest', - 'ListMuteConfigsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListResourceValueConfigsRequest', - 'ListResourceValueConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListValuedResourcesRequest', - 'ListValuedResourcesResponse', - 'SetFindingStateRequest', - 'SetMuteRequest', - 'UpdateBigQueryExportRequest', - 'UpdateExternalSystemRequest', - 'UpdateFindingRequest', - 'UpdateMuteConfigRequest', - 'UpdateNotificationConfigRequest', - 'UpdateResourceValueConfigRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - }, -) - - -class BatchCreateResourceValueConfigsRequest(proto.Message): - r"""Request message to create multiple resource value configs - - Attributes: - parent (str): - Required. Resource name of the new - ResourceValueConfig's parent. The parent field - in the CreateResourceValueConfigRequest messages - must either be empty or match this field. - requests (MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]): - Required. The resource value configs to be - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - requests: MutableSequence['CreateResourceValueConfigRequest'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='CreateResourceValueConfigRequest', - ) - - -class BatchCreateResourceValueConfigsResponse(proto.Message): - r"""Response message for BatchCreateResourceValueConfigs - - Attributes: - resource_value_configs (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfig]): - The resource value configs created - """ - - resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_resource_value_config.ResourceValueConfig, - ) - - -class BulkMuteFindingsRequest(proto.Message): - r"""Request message for bulk findings update. - - Note: - - 1. If multiple bulk update requests match the same resource, the - order in which they get executed is not defined. - 2. Once a bulk operation is started, there is no way to stop it. - - Attributes: - parent (str): - Required. The parent, at which bulk action needs to be - applied. If no location is specified, findings are updated - in global. The following list shows some examples: - - - ``organizations/[organization_id]`` - - ``organizations/[organization_id]/locations/[location_id]`` - - ``folders/[folder_id]`` - - ``folders/[folder_id]/locations/[location_id]`` - - ``projects/[project_id]`` - - ``projects/[project_id]/locations/[location_id]`` - filter (str): - Expression that identifies findings that should be updated. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - mute_state (google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest.MuteState): - Optional. All findings matching the given filter will have - their mute state set to this value. The default value is - ``MUTED``. Setting this to ``UNDEFINED`` will clear the mute - state on all matching findings. - """ - class MuteState(proto.Enum): - r"""The mute state. - - Values: - MUTE_STATE_UNSPECIFIED (0): - Unused. - MUTED (1): - Matching findings will be muted (default). - UNDEFINED (2): - Matching findings will have their mute state - cleared. - """ - MUTE_STATE_UNSPECIFIED = 0 - MUTED = 1 - UNDEFINED = 2 - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - mute_state: MuteState = proto.Field( - proto.ENUM, - number=3, - enum=MuteState, - ) - - -class BulkMuteFindingsResponse(proto.Message): - r"""The response to a BulkMute request. Contains the LRO - information. - - """ - - -class CreateBigQueryExportRequest(proto.Message): - r"""Request message for creating a BigQuery export. - - Attributes: - parent (str): - Required. The name of the parent resource of the new - BigQuery export. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): - Required. The BigQuery export being created. - big_query_export_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must consist - of only lowercase letters, numbers, and hyphens, - must start with a letter, must end with either a - letter or a number, and must be 63 characters or - less. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - big_query_export: bigquery_export.BigQueryExport = proto.Field( - proto.MESSAGE, - number=2, - message=bigquery_export.BigQueryExport, - ) - big_query_export_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - - Attributes: - parent (str): - Required. Resource name of the new finding's parent. The - following list shows some examples of the format: + - ``organizations/[organization_id]/sources/[source_id]`` + - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - alphanumeric and less than or equal to 32 - characters and greater than 0 characters in - length. - finding (google.cloud.securitycenter_v2.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - finding_id: str = proto.Field( - proto.STRING, - number=2, - ) - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_finding.Finding, - ) - - -class CreateMuteConfigRequest(proto.Message): - r"""Request message for creating a mute config. - - Attributes: - parent (str): - Required. Resource name of the new mute configs's parent. - Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - mute_config (google.cloud.securitycenter_v2.types.MuteConfig): - Required. The mute config being created. - mute_config_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must consist - of only lowercase letters, numbers, and hyphens, - must start with a letter, must end with either a - letter or a number, and must be 63 characters or - less. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - mute_config: gcs_mute_config.MuteConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_mute_config.MuteConfig, - ) - mute_config_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class CreateNotificationConfigRequest(proto.Message): - r"""Request message for creating a notification config. - - Attributes: - parent (str): - Required. Resource name of the new notification config's - parent. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - config_id (str): - Required. - Unique identifier provided by the client within - the parent scope. It must be between 1 and 128 - characters and contain alphanumeric characters, - underscores, or hyphens only. - notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): - Required. The notification config being - created. The name and the service account will - be ignored as they are both output only fields - on this resource. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - config_id: str = proto.Field( - proto.STRING, - number=2, - ) - notification_config: gcs_notification_config.NotificationConfig = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_notification_config.NotificationConfig, - ) - - -class CreateResourceValueConfigRequest(proto.Message): - r"""Request message to create single resource value config - - Attributes: - parent (str): - Required. Resource name of the new - ResourceValueConfig's parent. - resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): - Required. The resource value config being - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_resource_value_config.ResourceValueConfig, - ) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be ``organizations/[organization_id]``. - source (google.cloud.securitycenter_v2.types.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_source.Source, - ) - - -class DeleteBigQueryExportRequest(proto.Message): - r"""Request message for deleting a BigQuery export. - - Attributes: - name (str): - Required. The name of the BigQuery export to delete. The - following list shows some examples of the format: - - - - - ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` - - - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` - - ``projects/{project}/locations/{location}/bigQueryExports/{export_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteMuteConfigRequest(proto.Message): - r"""Request message for deleting a mute config. If no location is - specified, default is global. - - Attributes: - name (str): - Required. Name of the mute config to delete. The following - list shows some examples of the format: - - - ``organizations/{organization}/muteConfigs/{config_id}`` - - - - ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` - - - ``folders/{folder}/muteConfigs/{config_id}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` - - ``projects/{project}/muteConfigs/{config_id}`` - - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteNotificationConfigRequest(proto.Message): - r"""Request message for deleting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to delete. The - following list shows some examples of the format: - - - - - ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` - + - ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_id]`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteResourceValueConfigRequest(proto.Message): - r"""Request message to delete resource value config - - Attributes: - name (str): - Required. Name of the ResourceValueConfig to - delete - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetBigQueryExportRequest(proto.Message): - r"""Request message for retrieving a BigQuery export. - - Attributes: - name (str): - Required. Name of the BigQuery export to retrieve. The - following list shows some examples of the format: - - - - - ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` - - - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` - - ``projects/{project}locations/{location}//bigQueryExports/{export_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetMuteConfigRequest(proto.Message): - r"""Request message for retrieving a mute config. If no location - is specified, default is global. - - Attributes: - name (str): - Required. Name of the mute config to retrieve. The following - list shows some examples of the format: - - - ``organizations/{organization}/muteConfigs/{config_id}`` - - - - ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` - - - ``folders/{folder}/muteConfigs/{config_id}`` - - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` - - ``projects/{project}/muteConfigs/{config_id}`` - - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetNotificationConfigRequest(proto.Message): - r"""Request message for getting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to get. The - following list shows some examples of the format: - - - - - ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` - + - ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_id]`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetResourceValueConfigRequest(proto.Message): - r"""Request message to get resource value config - - Attributes: - name (str): - Required. Name of the resource value config to retrieve. Its - format is - organizations/{organization}/resourceValueConfigs/{config_id}. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is ``organizations/[organization_id]/source/[source_id]``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - - Attributes: - parent (str): - Required. Name of the source to groupBy. If no location is - specified, finding is assumed to be in global. The following - list shows some examples: - - - ``organizations/[organization_id]/sources/[source_id]`` - - - - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - - ``folders/[folder_id]/sources/[source_id]`` - - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` - - ``projects/[project_id]/sources/[source_id]`` - - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` - - To groupBy across all sources provide a source_id of ``-``. - The following list shows some examples: - - - ``organizations/{organization_id}/sources/-`` - - ``organizations/{organization_id}/sources/-/locations/[location_id]`` - - ``folders/{folder_id}/sources/-`` - - ``folders/{folder_id}/sources/-/locations/[location_id]`` - - ``projects/{project_id}/sources/-`` - - ``projects/{project_id}/sources/-/locations/[location_id]`` - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - severity: ``=``, ``:`` - - - security_marks.marks: ``=``, ``:`` - - - resource: - - - resource.name: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "parent,resource_name". - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - group_by: str = proto.Field( - proto.STRING, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - page_size: int = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - - Attributes: - group_by_results (MutableSequence[google.cloud.securitycenter_v2.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results: MutableSequence['GroupResult'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message=struct_pb2.Value, - ) - count: int = proto.Field( - proto.INT64, - number=2, - ) - - -class ListAttackPathsRequest(proto.Message): - r"""Request message for listing the attack paths for a given - simulation or valued resource. - - Attributes: - parent (str): - Required. Name of parent to list attack paths. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - filter (str): - The filter expression that filters the attack path in the - response. Supported fields: - - - ``valued_resources`` supports = - page_token (str): - The value returned by the last ``ListAttackPathsResponse``; - indicates that this is a continuation of a prior - ``ListAttackPaths`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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 ListAttackPathsResponse(proto.Message): - r"""Response message for listing the attack paths for a given - simulation or valued resource. - - Attributes: - attack_paths (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath]): - The attack paths that the attack path - simulation identified. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - attack_paths: MutableSequence[attack_path.AttackPath] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=attack_path.AttackPath, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetSimulationRequest(proto.Message): - r"""Request message for getting simulation. - Simulation name can include "latest" to retrieve the latest - simulation For example, "organizations/123/simulations/latest" - - Attributes: - name (str): - Required. The organization name or simulation name of this - simulation - - Valid format: - ``organizations/{organization}/simulations/latest`` - ``organizations/{organization}/simulations/{simulation}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetValuedResourceRequest(proto.Message): - r"""Request message for getting a valued resource. - - Attributes: - name (str): - Required. The name of this valued resource - - Valid format: - ``organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListBigQueryExportsRequest(proto.Message): - r"""Request message for listing BigQuery exports at a given scope - e.g. organization, folder or project. - - Attributes: - parent (str): - Required. The parent, which owns the collection of BigQuery - exports. Its format is - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, or - ``projects/[project_id]/locations/[location_id]``. - page_size (int): - The maximum number of configs to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - A page token, received from a previous - ``ListBigQueryExports`` call. Provide this to retrieve the - subsequent page. When paginating, all other parameters - provided to ``ListBigQueryExports`` 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 ListBigQueryExportsResponse(proto.Message): - r"""Response message for listing BigQuery exports. - - Attributes: - big_query_exports (MutableSequence[google.cloud.securitycenter_v2.types.BigQueryExport]): - The BigQuery exports from the specified - parent. - 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 - - big_query_exports: MutableSequence[bigquery_export.BigQueryExport] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=bigquery_export.BigQueryExport, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - - Attributes: - parent (str): - Required. Name of the source the findings belong to. If no - location is specified, the default is global. The following - list shows some examples: - - - ``organizations/[organization_id]/sources/[source_id]`` - - - - ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` - - - ``folders/[folder_id]/sources/[source_id]`` - - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` - - ``projects/[project_id]/sources/[source_id]`` - - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` - - To list across all sources provide a source_id of ``-``. The - following list shows some examples: - - - ``organizations/{organization_id}/sources/-`` - - ``organizations/{organization_id}/sources/-/locations/{location_id}`` - - ``folders/{folder_id}/sources/-`` - - ``folders/{folder_id}/sources/-locations/{location_id}`` - - ``projects/{projects_id}/sources/-`` - - ``projects/{projects_id}/sources/-/locations/{location_id}`` - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - severity: ``=``, ``:`` - - - security_marks.marks: ``=``, ``:`` - - - resource: - - - resource.name: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - - resource.folders.resource_folder: ``=``, ``:`` - - resource.display_name: ``=``, ``:`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: "name,parent". The - default sorting order is ascending. To specify descending - order for a field, a suffix " desc" should be appended to - the field name. For example: "name desc,parent". Redundant - space characters in the syntax are insignificant. "name - desc,parent" and " name desc , parent " are equivalent. - - The following fields are supported: name parent state - category resource_name event_time security_marks.marks - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the Finding fields to - be listed in the response. An empty field mask - will list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - order_by: str = proto.Field( - proto.STRING, - number=3, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token: str = proto.Field( - proto.STRING, - number=8, - ) - page_size: int = proto.Field( - proto.INT32, - number=9, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - - Attributes: - list_findings_results (MutableSequence[google.cloud.securitycenter_v2.types.ListFindingsResponse.ListFindingsResult]): - Findings matching the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - class ListFindingsResult(proto.Message): - r"""Result containing the Finding. - - Attributes: - finding (google.cloud.securitycenter_v2.types.Finding): - Finding matching the search request. - resource (google.cloud.securitycenter_v2.types.ListFindingsResponse.ListFindingsResult.Resource): - Output only. Resource that is associated with - this finding. - """ - - class Resource(proto.Message): - r"""Information related to the Google Cloud resource that is - associated with this finding. - - 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): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - display_name (str): - The human readable name of the resource. - type_ (str): - The full resource type of the resource. - cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): - Indicates which cloud provider the finding is - from. - service (str): - The service or resource provider associated - with the resource. - location (str): - The region or location of the service (if - applicable). - gcp_metadata (google.cloud.securitycenter_v2.types.GcpMetadata): - The GCP metadata associated with the finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - aws_metadata (google.cloud.securitycenter_v2.types.AwsMetadata): - The AWS metadata associated with the finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - azure_metadata (google.cloud.securitycenter_v2.types.AzureMetadata): - The Azure metadata associated with the - finding. - - This field is a member of `oneof`_ ``cloud_provider_metadata``. - resource_path (google.cloud.securitycenter_v2.types.ResourcePath): - Provides the path to the resource within the - resource hierarchy. - resource_path_string (str): - A string representation of the resource path. For Google - Cloud, it has the format of - ``organizations/{organization_id}/folders/{folder_id}/folders/{folder_id}/projects/{project_id}`` - where there can be any number of folders. For AWS, it has - the format of - ``org/{organization_id}/ou/{organizational_unit_id}/ou/{organizational_unit_id}/account/{account_id}`` - where there can be any number of organizational units. For - Azure, it has the format of - ``mg/{management_group_id}/mg/{management_group_id}/subscription/{subscription_id}/rg/{resource_group_name}`` - where there can be any number of management groups. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - type_: str = proto.Field( - proto.STRING, - number=3, - ) - cloud_provider: gcs_resource.CloudProvider = proto.Field( - proto.ENUM, - number=4, - enum=gcs_resource.CloudProvider, - ) - service: str = proto.Field( - proto.STRING, - number=5, - ) - location: str = proto.Field( - proto.STRING, - number=6, - ) - gcp_metadata: gcs_resource.GcpMetadata = proto.Field( - proto.MESSAGE, - number=7, - oneof='cloud_provider_metadata', - message=gcs_resource.GcpMetadata, - ) - aws_metadata: gcs_resource.AwsMetadata = proto.Field( - proto.MESSAGE, - number=8, - oneof='cloud_provider_metadata', - message=gcs_resource.AwsMetadata, - ) - azure_metadata: gcs_resource.AzureMetadata = proto.Field( - proto.MESSAGE, - number=9, - oneof='cloud_provider_metadata', - message=gcs_resource.AzureMetadata, - ) - resource_path: gcs_resource.ResourcePath = proto.Field( - proto.MESSAGE, - number=10, - message=gcs_resource.ResourcePath, - ) - resource_path_string: str = proto.Field( - proto.STRING, - number=11, - ) - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - resource: 'ListFindingsResponse.ListFindingsResult.Resource' = proto.Field( - proto.MESSAGE, - number=3, - message='ListFindingsResponse.ListFindingsResult.Resource', - ) - - @property - def raw_page(self): - return self - - list_findings_results: MutableSequence[ListFindingsResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListFindingsResult, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_size: int = proto.Field( - proto.INT32, - number=4, - ) - - -class ListMuteConfigsRequest(proto.Message): - r"""Request message for listing mute configs at a given scope - e.g. organization, folder or project. If no location is - specified, default is global. - - Attributes: - parent (str): - Required. The parent, which owns the collection of mute - configs. Its format is - ``organizations/[organization_id]", "folders/[folder_id]``, - ``projects/[project_id]``, - ``organizations/[organization_id]/locations/[location_id]``, - ``folders/[folder_id]/locations/[location_id]``, - ``projects/[project_id]/locations/[location_id]``. - page_size (int): - The maximum number of configs to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - A page token, received from a previous ``ListMuteConfigs`` - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListMuteConfigs`` 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 ListMuteConfigsResponse(proto.Message): - r"""Response message for listing mute configs. - - Attributes: - mute_configs (MutableSequence[google.cloud.securitycenter_v2.types.MuteConfig]): - The mute configs from the specified parent. - 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 - - mute_configs: MutableSequence[gcs_mute_config.MuteConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_mute_config.MuteConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListNotificationConfigsRequest(proto.Message): - r"""Request message for listing notification configs. - - Attributes: - parent (str): - Required. The name of the parent in which to list the - notification configurations. Its format is - "organizations/[organization_id]/locations/[location_id]", - "folders/[folder_id]/locations/[location_id]", or - "projects/[project_id]/locations/[location_id]". - page_token (str): - The value returned by the last - ``ListNotificationConfigsResponse``; indicates that this is - a continuation of a prior ``ListNotificationConfigs`` call, - and that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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 ListNotificationConfigsResponse(proto.Message): - r"""Response message for listing notification configs. - - Attributes: - notification_configs (MutableSequence[google.cloud.securitycenter_v2.types.NotificationConfig]): - Notification configs belonging to the - requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - notification_configs: MutableSequence[gcs_notification_config.NotificationConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListResourceValueConfigsRequest(proto.Message): - r"""Request message to list resource value configs of a parent - - Attributes: - parent (str): - Required. The parent, which owns the collection of resource - value configs. Its format is - ``organizations/[organization_id]`` - page_size (int): - The maximum number of configs to return. The - service may return fewer than this value. - If unspecified, at most 10 configs will be - returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - A page token, received from a previous - ``ListResourceValueConfigs`` call. Provide this to retrieve - the subsequent page. - - When paginating, all other parameters provided to - ``ListResourceValueConfigs`` must match the call that - provided the page token. - - page_size can be specified, and the new page_size 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, - ) - - -class ListResourceValueConfigsResponse(proto.Message): - r"""Response message to list resource value configs - - Attributes: - resource_value_configs (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfig]): - The resource value configs from the specified - parent. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is empty, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - resource_value_configs: MutableSequence[gcs_resource_value_config.ResourceValueConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_resource_value_config.ResourceValueConfig, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be ``organizations/[organization_id]``, - ``folders/[folder_id]``, or ``projects/[project_id]``. - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - 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=7, - ) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - - Attributes: - sources (MutableSequence[google.cloud.securitycenter_v2.types.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListValuedResourcesRequest(proto.Message): - r"""Request message for listing the valued resources for a given - simulation. - - Attributes: - parent (str): - Required. Name of parent to list exposed resources. - - Valid formats: ``organizations/{organization}``, - ``organizations/{organization}/simulations/{simulation}`` - ``organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}`` - filter (str): - The filter expression that filters the valued resources in - the response. Supported fields: - - - ``resource_value`` supports = - - ``resource_type`` supports = - page_token (str): - The value returned by the last - ``ListValuedResourcesResponse``; indicates that this is a - continuation of a prior ``ListValuedResources`` call, and - that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - order_by (str): - Optional. The fields by which to order the valued resources - response. - - Supported fields: - - - ``exposed_score`` - - - ``resource_value`` - - - ``resource_type`` - - Values should be a comma separated list of fields. For - example: ``exposed_score,resource_value``. - - The default sorting order is descending. To specify - ascending or descending order for a field, append a " ASC" - or a " DESC" suffix, respectively; for example: - ``exposed_score DESC``. - """ - - 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, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListValuedResourcesResponse(proto.Message): - r"""Response message for listing the valued resources for a given - simulation. - - Attributes: - valued_resources (MutableSequence[google.cloud.securitycenter_v2.types.ValuedResource]): - The valued resources that the attack path - simulation identified. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The estimated total number of results - matching the query. - """ - - @property - def raw_page(self): - return self - - valued_resources: MutableSequence[valued_resource.ValuedResource] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=valued_resource.ValuedResource, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - - Attributes: - name (str): - Required. The `relative resource - name `__ - of the finding. If no location is specified, finding is - assumed to be in global. The following list shows some - examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - state (google.cloud.securitycenter_v2.types.Finding.State): - Required. The desired State of the finding. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: gcs_finding.Finding.State = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.State, - ) - - -class SetMuteRequest(proto.Message): - r"""Request message for updating a finding's mute status. - - Attributes: - name (str): - Required. The `relative resource - name `__ - of the finding. If no location is specified, finding is - assumed to be in global. The following list shows some - examples: - - - - - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` - + - ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - - - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` - - - - ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` - mute (google.cloud.securitycenter_v2.types.Finding.Mute): - Required. The desired state of the Mute. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - mute: gcs_finding.Finding.Mute = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.Mute, - ) - - -class UpdateBigQueryExportRequest(proto.Message): - r"""Request message for updating a BigQuery export. - - Attributes: - big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): - Required. The BigQuery export being updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - If empty all mutable fields will be updated. - """ - - big_query_export: bigquery_export.BigQueryExport = proto.Field( - proto.MESSAGE, - number=1, - message=bigquery_export.BigQueryExport, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateExternalSystemRequest(proto.Message): - r"""Request message for updating a ExternalSystem resource. - - Attributes: - external_system (google.cloud.securitycenter_v2.types.ExternalSystem): - Required. The external system resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - external system resource. - If empty all mutable fields will be updated. - """ - - external_system: gcs_external_system.ExternalSystem = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_external_system.ExternalSystem, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - - Attributes: - finding (google.cloud.securitycenter_v2.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must be alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing source_properties. - Individual source_properties can be added/updated by using - "source_properties." in the field mask. - """ - - finding: gcs_finding.Finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateMuteConfigRequest(proto.Message): - r"""Request message for updating a mute config. - - Attributes: - mute_config (google.cloud.securitycenter_v2.types.MuteConfig): - Required. The mute config being updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. - If empty all mutable fields will be updated. - """ - - mute_config: gcs_mute_config.MuteConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_mute_config.MuteConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateNotificationConfigRequest(proto.Message): - r"""Request message for updating a notification config. - - Attributes: - notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): - Required. The notification config to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - notification config. - If empty all mutable fields will be updated. - """ - - notification_config: gcs_notification_config.NotificationConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateResourceValueConfigRequest(proto.Message): - r"""Request message to update resource value config - - Attributes: - resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): - Required. The resource value config being - updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. If empty all mutable - fields will be updated. - - To update nested fields, include the top level field in the - mask For example, to update gcp_metadata.resource_type, - include the "gcp_metadata" field mask - """ - - resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_resource_value_config.ResourceValueConfig, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - - Attributes: - security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): - Required. The security marks resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If empty - or set to "marks", all marks will be replaced. Individual - marks can be updated using "marks.". - """ - - security_marks: gcs_security_marks.SecurityMarks = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_security_marks.SecurityMarks, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - - Attributes: - source (google.cloud.securitycenter_v2.types.Source): - Required. The source resource to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the source - resource. - If empty all mutable fields will be updated. - """ - - source: gcs_source.Source = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - 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-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py deleted file mode 100644 index 5c64646490da..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/simulation.py +++ /dev/null @@ -1,73 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the 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.securitycenter_v2.types import resource -from google.cloud.securitycenter_v2.types import valued_resource -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Simulation', - }, -) - - -class Simulation(proto.Message): - r"""Attack path simulation - - Attributes: - name (str): - Full resource name of the Simulation: - ``organizations/123/simulations/456`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time simulation was created - resource_value_configs_metadata (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfigMetadata]): - Resource value configurations' metadata used - in this simulation. Maximum of 100. - cloud_provider (google.cloud.securitycenter_v2.types.CloudProvider): - Indicates which cloud provider was used in - this simulation. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - resource_value_configs_metadata: MutableSequence[valued_resource.ResourceValueConfigMetadata] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=valued_resource.ResourceValueConfigMetadata, - ) - cloud_provider: resource.CloudProvider = proto.Field( - proto.ENUM, - number=4, - enum=resource.CloudProvider, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.py deleted file mode 100644 index 006e16a02f4a..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/source.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'Source', - }, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, and other tools. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and outdated or - insecure libraries.". - canonical_name (str): - The canonical name of the finding source. It's either - "organizations/{organization_id}/sources/{source_id}", - "folders/{folder_id}/sources/{source_id}", or - "projects/{project_number}/sources/{source_id}", depending - on the closest CRM ancestor of the resource associated with - the finding. - """ - - 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, - ) - canonical_name: str = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.py deleted file mode 100644 index e70d9aa2e281..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/toxic_combination.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'ToxicCombination', - }, -) - - -class ToxicCombination(proto.Message): - r"""Contains details about a group of security issues that, when - the issues occur together, represent a greater risk than when - the issues occur independently. A group of such issues is - referred to as a toxic combination. - - Attributes: - attack_exposure_score (float): - The `Attack exposure - score `__ - of this toxic combination. The score is a measure of how - much this toxic combination exposes one or more high-value - resources to potential attack. - related_findings (MutableSequence[str]): - List of resource names of findings associated with this - toxic combination. For example, - ``organizations/123/sources/456/findings/789``. - """ - - attack_exposure_score: float = proto.Field( - proto.DOUBLE, - number=1, - ) - related_findings: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.py deleted file mode 100644 index ed481ba587b6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/valued_resource.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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v2', - manifest={ - 'ValuedResource', - 'ResourceValueConfigMetadata', - }, -) - - -class ValuedResource(proto.Message): - r"""A resource that is determined to have value to a user's - system - - Attributes: - name (str): - Valued resource name, for example, e.g.: - ``organizations/123/simulations/456/valuedResources/789`` - resource (str): - The `full resource - name `__ - of the valued resource. - resource_type (str): - The `resource - type `__ - of the valued resource. - display_name (str): - Human-readable name of the valued resource. - resource_value (google.cloud.securitycenter_v2.types.ValuedResource.ResourceValue): - How valuable this resource is. - exposed_score (float): - Exposed score for this valued resource. A - value of 0 means no exposure was detected - exposure. - resource_value_configs_used (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfigMetadata]): - List of resource value configurations' - metadata used to determine the value of this - resource. Maximum of 100. - """ - class ResourceValue(proto.Enum): - r"""How valuable the resource is. - - Values: - RESOURCE_VALUE_UNSPECIFIED (0): - The resource value isn't specified. - RESOURCE_VALUE_LOW (1): - This is a low-value resource. - RESOURCE_VALUE_MEDIUM (2): - This is a medium-value resource. - RESOURCE_VALUE_HIGH (3): - This is a high-value resource. - """ - RESOURCE_VALUE_UNSPECIFIED = 0 - RESOURCE_VALUE_LOW = 1 - RESOURCE_VALUE_MEDIUM = 2 - RESOURCE_VALUE_HIGH = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - resource: str = proto.Field( - proto.STRING, - number=2, - ) - resource_type: str = proto.Field( - proto.STRING, - number=3, - ) - display_name: str = proto.Field( - proto.STRING, - number=4, - ) - resource_value: ResourceValue = proto.Field( - proto.ENUM, - number=5, - enum=ResourceValue, - ) - exposed_score: float = proto.Field( - proto.DOUBLE, - number=6, - ) - resource_value_configs_used: MutableSequence['ResourceValueConfigMetadata'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='ResourceValueConfigMetadata', - ) - - -class ResourceValueConfigMetadata(proto.Message): - r"""Metadata about a ResourceValueConfig. For example, id and - name. - - Attributes: - name (str): - Resource value config name - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.py b/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.py deleted file mode 100644 index 79c7e06db637..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/google/cloud/securitycenter_v2/types/vulnerability.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. -# -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.securitycenter.v2', - manifest={ - 'Vulnerability', - 'Cve', - 'Reference', - 'Cvssv3', - 'Package', - 'SecurityBulletin', - }, -) - - -class Vulnerability(proto.Message): - r"""Refers to common vulnerability fields e.g. cve, cvss, cwe - etc. - - Attributes: - cve (google.cloud.securitycenter_v2.types.Cve): - CVE stands for Common Vulnerabilities and - Exposures (https://cve.mitre.org/about/) - offending_package (google.cloud.securitycenter_v2.types.Package): - The offending package is relevant to the - finding. - fixed_package (google.cloud.securitycenter_v2.types.Package): - The fixed package is relevant to the finding. - security_bulletin (google.cloud.securitycenter_v2.types.SecurityBulletin): - The security bulletin is relevant to this - finding. - """ - - cve: 'Cve' = proto.Field( - proto.MESSAGE, - number=1, - message='Cve', - ) - offending_package: 'Package' = proto.Field( - proto.MESSAGE, - number=2, - message='Package', - ) - fixed_package: 'Package' = proto.Field( - proto.MESSAGE, - number=3, - message='Package', - ) - security_bulletin: 'SecurityBulletin' = proto.Field( - proto.MESSAGE, - number=4, - message='SecurityBulletin', - ) - - -class Cve(proto.Message): - r"""CVE stands for Common Vulnerabilities and Exposures. Information - from the `CVE - record `__ that - describes this vulnerability. - - Attributes: - id (str): - The unique identifier for the vulnerability. - e.g. CVE-2021-34527 - references (MutableSequence[google.cloud.securitycenter_v2.types.Reference]): - Additional information about the CVE. - e.g. - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527 - cvssv3 (google.cloud.securitycenter_v2.types.Cvssv3): - Describe Common Vulnerability Scoring System - specified at - https://www.first.org/cvss/v3.1/specification-document - upstream_fix_available (bool): - Whether upstream fix is available for the - CVE. - impact (google.cloud.securitycenter_v2.types.Cve.RiskRating): - The potential impact of the vulnerability if - it was to be exploited. - exploitation_activity (google.cloud.securitycenter_v2.types.Cve.ExploitationActivity): - The exploitation activity of the - vulnerability in the wild. - observed_in_the_wild (bool): - Whether or not the vulnerability has been - observed in the wild. - zero_day (bool): - Whether or not the vulnerability was zero day - when the finding was published. - exploit_release_date (google.protobuf.timestamp_pb2.Timestamp): - Date the first publicly available exploit or - PoC was released. - """ - class RiskRating(proto.Enum): - r"""The possible values of impact of the vulnerability if it was - to be exploited. - - Values: - RISK_RATING_UNSPECIFIED (0): - Invalid or empty value. - LOW (1): - Exploitation would have little to no security - impact. - MEDIUM (2): - Exploitation would enable attackers to - perform activities, or could allow attackers to - have a direct impact, but would require - additional steps. - HIGH (3): - Exploitation would enable attackers to have a - notable direct impact without needing to - overcome any major mitigating factors. - CRITICAL (4): - Exploitation would fundamentally undermine - the security of affected systems, enable actors - to perform significant attacks with minimal - effort, with little to no mitigating factors to - overcome. - """ - RISK_RATING_UNSPECIFIED = 0 - LOW = 1 - MEDIUM = 2 - HIGH = 3 - CRITICAL = 4 - - class ExploitationActivity(proto.Enum): - r"""The possible values of exploitation activity of the - vulnerability in the wild. - - Values: - EXPLOITATION_ACTIVITY_UNSPECIFIED (0): - Invalid or empty value. - WIDE (1): - Exploitation has been reported or confirmed - to widely occur. - CONFIRMED (2): - Limited reported or confirmed exploitation - activities. - AVAILABLE (3): - Exploit is publicly available. - ANTICIPATED (4): - No known exploitation activity, but has a - high potential for exploitation. - NO_KNOWN (5): - No known exploitation activity. - """ - EXPLOITATION_ACTIVITY_UNSPECIFIED = 0 - WIDE = 1 - CONFIRMED = 2 - AVAILABLE = 3 - ANTICIPATED = 4 - NO_KNOWN = 5 - - id: str = proto.Field( - proto.STRING, - number=1, - ) - references: MutableSequence['Reference'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Reference', - ) - cvssv3: 'Cvssv3' = proto.Field( - proto.MESSAGE, - number=3, - message='Cvssv3', - ) - upstream_fix_available: bool = proto.Field( - proto.BOOL, - number=4, - ) - impact: RiskRating = proto.Field( - proto.ENUM, - number=5, - enum=RiskRating, - ) - exploitation_activity: ExploitationActivity = proto.Field( - proto.ENUM, - number=6, - enum=ExploitationActivity, - ) - observed_in_the_wild: bool = proto.Field( - proto.BOOL, - number=7, - ) - zero_day: bool = proto.Field( - proto.BOOL, - number=8, - ) - exploit_release_date: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - - -class Reference(proto.Message): - r"""Additional Links - - Attributes: - source (str): - Source of the reference e.g. NVD - uri (str): - Uri for the mentioned source e.g. - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527. - """ - - source: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Cvssv3(proto.Message): - r"""Common Vulnerability Scoring System version 3. - - Attributes: - base_score (float): - The base score is a function of the base - metric scores. - attack_vector (google.cloud.securitycenter_v2.types.Cvssv3.AttackVector): - Base Metrics - Represents the intrinsic characteristics of a - vulnerability that are constant over time and - across user environments. This metric reflects - the context by which vulnerability exploitation - is possible. - attack_complexity (google.cloud.securitycenter_v2.types.Cvssv3.AttackComplexity): - This metric describes the conditions beyond - the attacker's control that must exist in order - to exploit the vulnerability. - privileges_required (google.cloud.securitycenter_v2.types.Cvssv3.PrivilegesRequired): - This metric describes the level of privileges - an attacker must possess before successfully - exploiting the vulnerability. - user_interaction (google.cloud.securitycenter_v2.types.Cvssv3.UserInteraction): - This metric captures the requirement for a - human user, other than the attacker, to - participate in the successful compromise of the - vulnerable component. - scope (google.cloud.securitycenter_v2.types.Cvssv3.Scope): - The Scope metric captures whether a - vulnerability in one vulnerable component - impacts resources in components beyond its - security scope. - confidentiality_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): - This metric measures the impact to the - confidentiality of the information resources - managed by a software component due to a - successfully exploited vulnerability. - integrity_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): - This metric measures the impact to integrity - of a successfully exploited vulnerability. - availability_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): - This metric measures the impact to the - availability of the impacted component resulting - from a successfully exploited vulnerability. - """ - class AttackVector(proto.Enum): - r"""This metric reflects the context by which vulnerability - exploitation is possible. - - Values: - ATTACK_VECTOR_UNSPECIFIED (0): - Invalid value. - ATTACK_VECTOR_NETWORK (1): - The vulnerable component is bound to the - network stack and the set of possible attackers - extends beyond the other options listed below, - up to and including the entire Internet. - ATTACK_VECTOR_ADJACENT (2): - The vulnerable component is bound to the - network stack, but the attack is limited at the - protocol level to a logically adjacent topology. - ATTACK_VECTOR_LOCAL (3): - The vulnerable component is not bound to the - network stack and the attacker's path is via - read/write/execute capabilities. - ATTACK_VECTOR_PHYSICAL (4): - The attack requires the attacker to - physically touch or manipulate the vulnerable - component. - """ - ATTACK_VECTOR_UNSPECIFIED = 0 - ATTACK_VECTOR_NETWORK = 1 - ATTACK_VECTOR_ADJACENT = 2 - ATTACK_VECTOR_LOCAL = 3 - ATTACK_VECTOR_PHYSICAL = 4 - - class AttackComplexity(proto.Enum): - r"""This metric describes the conditions beyond the attacker's - control that must exist in order to exploit the vulnerability. - - Values: - ATTACK_COMPLEXITY_UNSPECIFIED (0): - Invalid value. - ATTACK_COMPLEXITY_LOW (1): - Specialized access conditions or extenuating - circumstances do not exist. An attacker can - expect repeatable success when attacking the - vulnerable component. - ATTACK_COMPLEXITY_HIGH (2): - A successful attack depends on conditions - beyond the attacker's control. That is, a - successful attack cannot be accomplished at - will, but requires the attacker to invest in - some measurable amount of effort in preparation - or execution against the vulnerable component - before a successful attack can be expected. - """ - ATTACK_COMPLEXITY_UNSPECIFIED = 0 - ATTACK_COMPLEXITY_LOW = 1 - ATTACK_COMPLEXITY_HIGH = 2 - - class PrivilegesRequired(proto.Enum): - r"""This metric describes the level of privileges an attacker - must possess before successfully exploiting the vulnerability. - - Values: - PRIVILEGES_REQUIRED_UNSPECIFIED (0): - Invalid value. - PRIVILEGES_REQUIRED_NONE (1): - The attacker is unauthorized prior to attack, - and therefore does not require any access to - settings or files of the vulnerable system to - carry out an attack. - PRIVILEGES_REQUIRED_LOW (2): - The attacker requires privileges that provide - basic user capabilities that could normally - affect only settings and files owned by a user. - Alternatively, an attacker with Low privileges - has the ability to access only non-sensitive - resources. - PRIVILEGES_REQUIRED_HIGH (3): - The attacker requires privileges that provide - significant (e.g., administrative) control over - the vulnerable component allowing access to - component-wide settings and files. - """ - PRIVILEGES_REQUIRED_UNSPECIFIED = 0 - PRIVILEGES_REQUIRED_NONE = 1 - PRIVILEGES_REQUIRED_LOW = 2 - PRIVILEGES_REQUIRED_HIGH = 3 - - class UserInteraction(proto.Enum): - r"""This metric captures the requirement for a human user, other - than the attacker, to participate in the successful compromise - of the vulnerable component. - - Values: - USER_INTERACTION_UNSPECIFIED (0): - Invalid value. - USER_INTERACTION_NONE (1): - The vulnerable system can be exploited - without interaction from any user. - USER_INTERACTION_REQUIRED (2): - Successful exploitation of this vulnerability - requires a user to take some action before the - vulnerability can be exploited. - """ - USER_INTERACTION_UNSPECIFIED = 0 - USER_INTERACTION_NONE = 1 - USER_INTERACTION_REQUIRED = 2 - - class Scope(proto.Enum): - r"""The Scope metric captures whether a vulnerability in one - vulnerable component impacts resources in components beyond its - security scope. - - Values: - SCOPE_UNSPECIFIED (0): - Invalid value. - SCOPE_UNCHANGED (1): - An exploited vulnerability can only affect - resources managed by the same security - authority. - SCOPE_CHANGED (2): - An exploited vulnerability can affect - resources beyond the security scope managed by - the security authority of the vulnerable - component. - """ - SCOPE_UNSPECIFIED = 0 - SCOPE_UNCHANGED = 1 - SCOPE_CHANGED = 2 - - class Impact(proto.Enum): - r"""The Impact metrics capture the effects of a successfully - exploited vulnerability on the component that suffers the worst - outcome that is most directly and predictably associated with - the attack. - - Values: - IMPACT_UNSPECIFIED (0): - Invalid value. - IMPACT_HIGH (1): - High impact. - IMPACT_LOW (2): - Low impact. - IMPACT_NONE (3): - No impact. - """ - IMPACT_UNSPECIFIED = 0 - IMPACT_HIGH = 1 - IMPACT_LOW = 2 - IMPACT_NONE = 3 - - base_score: float = proto.Field( - proto.DOUBLE, - number=1, - ) - attack_vector: AttackVector = proto.Field( - proto.ENUM, - number=2, - enum=AttackVector, - ) - attack_complexity: AttackComplexity = proto.Field( - proto.ENUM, - number=3, - enum=AttackComplexity, - ) - privileges_required: PrivilegesRequired = proto.Field( - proto.ENUM, - number=4, - enum=PrivilegesRequired, - ) - user_interaction: UserInteraction = proto.Field( - proto.ENUM, - number=5, - enum=UserInteraction, - ) - scope: Scope = proto.Field( - proto.ENUM, - number=6, - enum=Scope, - ) - confidentiality_impact: Impact = proto.Field( - proto.ENUM, - number=7, - enum=Impact, - ) - integrity_impact: Impact = proto.Field( - proto.ENUM, - number=8, - enum=Impact, - ) - availability_impact: Impact = proto.Field( - proto.ENUM, - number=9, - enum=Impact, - ) - - -class Package(proto.Message): - r"""Package is a generic definition of a package. - - Attributes: - package_name (str): - The name of the package where the - vulnerability was detected. - cpe_uri (str): - The CPE URI where the vulnerability was - detected. - package_type (str): - Type of package, for example, os, maven, or - go. - package_version (str): - The version of the package. - """ - - package_name: str = proto.Field( - proto.STRING, - number=1, - ) - cpe_uri: str = proto.Field( - proto.STRING, - number=2, - ) - package_type: str = proto.Field( - proto.STRING, - number=3, - ) - package_version: str = proto.Field( - proto.STRING, - number=4, - ) - - -class SecurityBulletin(proto.Message): - r"""SecurityBulletin are notifications of vulnerabilities of - Google products. - - Attributes: - bulletin_id (str): - ID of the bulletin corresponding to the - vulnerability. - submission_time (google.protobuf.timestamp_pb2.Timestamp): - Submission time of this Security Bulletin. - suggested_upgrade_version (str): - This represents a version that the cluster - receiving this notification should be upgraded - to, based on its current version. For example, - 1.15.0 - """ - - bulletin_id: str = proto.Field( - proto.STRING, - number=1, - ) - submission_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - suggested_upgrade_version: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini b/owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/noxfile.py b/owl-bot-staging/google-cloud-securitycenter/v2/noxfile.py deleted file mode 100644 index cd78e7c39a06..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-securitycenter' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -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"): - 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/securitycenter_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"): - 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", - "grpcio", - "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/securitycenter_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( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): - # Ignore release of mypy 1.11.0 which may have a regression - 'mypy!=1.11.0', - '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-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py deleted file mode 100644 index e74e57a22631..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - requests = securitycenter_v2.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - - request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py deleted file mode 100644 index d6c2ad8428ff..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_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 BatchCreateResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_batch_create_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - requests = securitycenter_v2.CreateResourceValueConfigRequest() - requests.parent = "parent_value" - - request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_resource_value_configs(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py deleted file mode 100644 index 4b2fd03c3f02..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_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 BulkMuteFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py deleted file mode 100644 index 743d1302b400..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_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 BulkMuteFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_bulk_mute_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.BulkMuteFindingsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.bulk_mute_findings(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py deleted file mode 100644 index 1698ad6adc92..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_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 CreateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_create_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = await client.create_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py deleted file mode 100644 index becab1857b3c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_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 CreateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_create_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateBigQueryExportRequest( - parent="parent_value", - big_query_export_id="big_query_export_id_value", - ) - - # Make the request - response = client.create_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py deleted file mode 100644 index 3a2c089e9019..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_create_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = await client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py deleted file mode 100644 index 4294f4ffd397..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_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 CreateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_create_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateFindingRequest( - parent="parent_value", - finding_id="finding_id_value", - ) - - # Make the request - response = client.create_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py deleted file mode 100644 index c858b59a6586..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_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 CreateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_create_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = await client.create_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py deleted file mode 100644 index a0de28b38bbd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_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 CreateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_create_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.CreateMuteConfigRequest( - parent="parent_value", - mute_config=mute_config, - mute_config_id="mute_config_id_value", - ) - - # Make the request - response = client.create_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py deleted file mode 100644 index ae681f4e8f3e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_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 CreateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_create_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.create_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py deleted file mode 100644 index 0bf75d6458fd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_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 CreateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_create_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateNotificationConfigRequest( - parent="parent_value", - config_id="config_id_value", - ) - - # Make the request - response = client.create_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py deleted file mode 100644 index 9afb50b6e83e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_create_source(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py deleted file mode 100644 index af9c2b763cc6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_create_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 CreateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_CreateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_create_source(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.CreateSourceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_CreateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py deleted file mode 100644 index 4aac72fa5605..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - await client.delete_big_query_export(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py deleted file mode 100644 index b278bde5e5ae..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_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 DeleteBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_delete_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteBigQueryExportRequest( - name="name_value", - ) - - # Make the request - client.delete_big_query_export(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py deleted file mode 100644 index 10ceee02e146..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_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 DeleteMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_delete_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_mute_config(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py deleted file mode 100644 index a051c7c17741..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_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 DeleteMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_delete_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteMuteConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_mute_config(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py deleted file mode 100644 index fceb0255c2bd..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_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 DeleteNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_delete_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_notification_config(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py deleted file mode 100644 index 906f2a39092c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_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 DeleteNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_delete_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteNotificationConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_notification_config(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py deleted file mode 100644 index 191842b98c8f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - await client.delete_resource_value_config(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py deleted file mode 100644 index e8aac97d4f8d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_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 DeleteResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_delete_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.DeleteResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - client.delete_resource_value_config(request=request) - - -# [END securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py deleted file mode 100644 index 14de594a963c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_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 GetBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = await client.get_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py deleted file mode 100644 index a8d4416456ab..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_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 GetBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetBigQueryExportRequest( - name="name_value", - ) - - # Make the request - response = client.get_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py deleted file mode 100644 index 04061abcf9a4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py deleted file mode 100644 index 4d9d6d45b825..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_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 GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py deleted file mode 100644 index 348376a0b9b4..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_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 GetMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py deleted file mode 100644 index 84adb2a92f59..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_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 GetMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetMuteConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py deleted file mode 100644 index 73885369a61e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_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 GetNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py deleted file mode 100644 index 84d892dabf5f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_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 GetNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetNotificationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py deleted file mode 100644 index 4076aa39fbc6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_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 GetResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py deleted file mode 100644 index 814ba5a717d0..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_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 GetResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetResourceValueConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py deleted file mode 100644 index 4cf61313cb96..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_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 GetSimulation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetSimulation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_simulation(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_simulation(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetSimulation_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py deleted file mode 100644 index 572655cf48c9..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_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 GetSimulation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetSimulation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_simulation(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSimulationRequest( - name="name_value", - ) - - # Make the request - response = client.get_simulation(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetSimulation_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py deleted file mode 100644 index 685b7f0cc423..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_source(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py deleted file mode 100644 index a33bef8b910d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_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 GetSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_source(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetSourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py deleted file mode 100644 index b0601f503c25..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_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 GetValuedResource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetValuedResource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_get_valued_resource(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_valued_resource(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetValuedResource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py deleted file mode 100644 index ed7d7630288d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_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 GetValuedResource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GetValuedResource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_get_valued_resource(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GetValuedResourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_valued_resource(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GetValuedResource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py deleted file mode 100644 index d829f16c868e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GroupFindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_group_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GroupFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py deleted file mode 100644 index d7e8c0a21523..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_group_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 GroupFindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_GroupFindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_group_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.GroupFindingsRequest( - parent="parent_value", - group_by="group_by_value", - ) - - # Make the request - page_result = client.group_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_GroupFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py deleted file mode 100644 index ed648fdea30d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_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 ListAttackPaths -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListAttackPaths_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_attack_paths(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListAttackPaths_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py deleted file mode 100644 index bdecd1972ff1..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_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 ListAttackPaths -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListAttackPaths_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_attack_paths(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListAttackPathsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_attack_paths(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListAttackPaths_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py deleted file mode 100644 index 405bc21b0f37..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_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 ListBigQueryExports -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py deleted file mode 100644 index ccb98f95fa3c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_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 ListBigQueryExports -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_big_query_exports(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListBigQueryExportsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_big_query_exports(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py deleted file mode 100644 index bb6c9e3c9bc9..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_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 securitycenter_v2 - - -async def sample_list_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListFindings_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py deleted file mode 100644 index 190548636c6f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_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 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-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_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 securitycenter_v2 - - -def sample_list_findings(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListFindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_findings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListFindings_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py deleted file mode 100644 index 50ec2b1fd631..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_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 ListMuteConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_mute_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py deleted file mode 100644 index d28a0e6adb61..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_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 ListMuteConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_mute_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListMuteConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_mute_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py deleted file mode 100644 index 7b12a639c763..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_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 ListNotificationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_notification_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py deleted file mode 100644 index d1cffc2d7793..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_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 ListNotificationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_notification_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListNotificationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_notification_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py deleted file mode 100644 index 9f8a6124f4d6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_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 ListResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py deleted file mode 100644 index cfc3651b5540..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_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 ListResourceValueConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_resource_value_configs(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListResourceValueConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_value_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py deleted file mode 100644 index 447f27ccaa16..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListSources_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_sources(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListSources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py deleted file mode 100644 index 9447d7eb91ee..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_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 ListSources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListSources_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_sources(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListSourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_sources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListSources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py deleted file mode 100644 index 1c17d84f91cb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_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 ListValuedResources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListValuedResources_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_list_valued_resources(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListValuedResources_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py deleted file mode 100644 index 616675828d82..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_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 ListValuedResources -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_ListValuedResources_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_list_valued_resources(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.ListValuedResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_valued_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_ListValuedResources_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py deleted file mode 100644 index 905eb5d7db22..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_SetFindingState_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_set_finding_state(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = await client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_SetFindingState_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py deleted file mode 100644 index 339e22bde563..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_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 SetFindingState -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_SetFindingState_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_set_finding_state(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetFindingStateRequest( - name="name_value", - state="INACTIVE", - ) - - # Make the request - response = client.set_finding_state(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_SetFindingState_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py deleted file mode 100644 index 2c74d459d83f..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py deleted file mode 100644 index 4e5ef3b13cbf..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_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 SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py deleted file mode 100644 index fa80c37c66ca..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_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 SetMute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_SetMute_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_set_mute(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = await client.set_mute(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_SetMute_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py deleted file mode 100644 index 9355527a6bac..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_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 SetMute -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_SetMute_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_set_mute(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.SetMuteRequest( - name="name_value", - mute="UNDEFINED", - ) - - # Make the request - response = client.set_mute(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_SetMute_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py deleted file mode 100644 index 3ccd4f4848bb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py deleted file mode 100644 index 6df1fda9cf90..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_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 TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py deleted file mode 100644 index 365c17bd2756..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_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 UpdateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateBigQueryExportRequest( - ) - - # Make the request - response = await client.update_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py deleted file mode 100644 index 18b99ec2462e..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_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 UpdateBigQueryExport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_big_query_export(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateBigQueryExportRequest( - ) - - # Make the request - response = client.update_big_query_export(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py deleted file mode 100644 index 179da29467bb..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_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 UpdateExternalSystem -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_external_system(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateExternalSystemRequest( - ) - - # Make the request - response = await client.update_external_system(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py deleted file mode 100644 index 6a68970514cc..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_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 UpdateExternalSystem -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_external_system(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateExternalSystemRequest( - ) - - # Make the request - response = client.update_external_system(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py deleted file mode 100644 index 245e358b0eea..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateFinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateFindingRequest( - ) - - # Make the request - response = await client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateFinding_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py deleted file mode 100644 index 512e315aa049..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_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 UpdateFinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateFinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_finding(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateFindingRequest( - ) - - # Make the request - response = client.update_finding(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateFinding_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py deleted file mode 100644 index 7796c39566e2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_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 UpdateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = await client.update_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py deleted file mode 100644 index 920f6986fb3b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_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 UpdateMuteConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_mute_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - mute_config = securitycenter_v2.MuteConfig() - mute_config.filter = "filter_value" - mute_config.type_ = "DYNAMIC" - - request = securitycenter_v2.UpdateMuteConfigRequest( - mute_config=mute_config, - ) - - # Make the request - response = client.update_mute_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py deleted file mode 100644 index bed9621bb2ea..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_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 UpdateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateNotificationConfigRequest( - ) - - # Make the request - response = await client.update_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py deleted file mode 100644 index ed5516437b4d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_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 UpdateNotificationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_notification_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateNotificationConfigRequest( - ) - - # Make the request - response = client.update_notification_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py deleted file mode 100644 index 0ecd6b7d2fd5..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_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 UpdateResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateResourceValueConfigRequest( - ) - - # Make the request - response = await client.update_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py deleted file mode 100644 index 2508104c843d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_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 UpdateResourceValueConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_resource_value_config(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateResourceValueConfigRequest( - ) - - # Make the request - response = client.update_resource_value_config(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py deleted file mode 100644 index faf2900ce05c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_security_marks(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSecurityMarksRequest( - ) - - # Make the request - response = await client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py deleted file mode 100644 index 9843735d4ad6..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_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 UpdateSecurityMarks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_security_marks(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSecurityMarksRequest( - ) - - # Make the request - response = client.update_security_marks(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py deleted file mode 100644 index 39f5bd6e19c2..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateSource_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -async def sample_update_source(): - # Create a client - client = securitycenter_v2.SecurityCenterAsyncClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSourceRequest( - ) - - # Make the request - response = await client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateSource_async] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py deleted file mode 100644 index f138fd97e1ec..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_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 UpdateSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-securitycenter - - -# [START securitycenter_v2_generated_SecurityCenter_UpdateSource_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import securitycenter_v2 - - -def sample_update_source(): - # Create a client - client = securitycenter_v2.SecurityCenterClient() - - # Initialize request argument(s) - request = securitycenter_v2.UpdateSourceRequest( - ) - - # Make the request - response = client.update_source(request=request) - - # Handle the response - print(response) - -# [END securitycenter_v2_generated_SecurityCenter_UpdateSource_sync] diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json b/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json deleted file mode 100644 index 3ebbbfe28b50..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json +++ /dev/null @@ -1,6607 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.securitycenter.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-cloud-securitycenter", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.batch_create_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BatchCreateResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BatchCreateResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "requests", - "type": "MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse", - "shortName": "batch_create_resource_value_configs" - }, - "description": "Sample for BatchCreateResourceValueConfigs", - "file": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.batch_create_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BatchCreateResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BatchCreateResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "requests", - "type": "MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse", - "shortName": "batch_create_resource_value_configs" - }, - "description": "Sample for BatchCreateResourceValueConfigs", - "file": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.bulk_mute_findings", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BulkMuteFindings", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BulkMuteFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest" - }, - { - "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.api_core.operation_async.AsyncOperation", - "shortName": "bulk_mute_findings" - }, - "description": "Sample for BulkMuteFindings", - "file": "securitycenter_v2_generated_security_center_bulk_mute_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v2_generated_security_center_bulk_mute_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.bulk_mute_findings", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BulkMuteFindings", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "BulkMuteFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest" - }, - { - "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.api_core.operation.Operation", - "shortName": "bulk_mute_findings" - }, - "description": "Sample for BulkMuteFindings", - "file": "securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v2.types.BigQueryExport" - }, - { - "name": "big_query_export_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.BigQueryExport", - "shortName": "create_big_query_export" - }, - "description": "Sample for CreateBigQueryExport", - "file": "securitycenter_v2_generated_security_center_create_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v2_generated_security_center_create_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v2.types.BigQueryExport" - }, - { - "name": "big_query_export_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.BigQueryExport", - "shortName": "create_big_query_export" - }, - "description": "Sample for CreateBigQueryExport", - "file": "securitycenter_v2_generated_security_center_create_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v2_generated_security_center_create_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v2.types.Finding" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v2_generated_security_center_create_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateFinding_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": "securitycenter_v2_generated_security_center_create_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_finding", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateFindingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v2.types.Finding" - }, - { - "name": "finding_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Finding", - "shortName": "create_finding" - }, - "description": "Sample for CreateFinding", - "file": "securitycenter_v2_generated_security_center_create_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateFinding_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": "securitycenter_v2_generated_security_center_create_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateMuteConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v2.types.MuteConfig" - }, - { - "name": "mute_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.cloud.securitycenter_v2.types.MuteConfig", - "shortName": "create_mute_config" - }, - "description": "Sample for CreateMuteConfig", - "file": "securitycenter_v2_generated_security_center_create_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v2_generated_security_center_create_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateMuteConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v2.types.MuteConfig" - }, - { - "name": "mute_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.cloud.securitycenter_v2.types.MuteConfig", - "shortName": "create_mute_config" - }, - "description": "Sample for CreateMuteConfig", - "file": "securitycenter_v2_generated_security_center_create_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_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": "securitycenter_v2_generated_security_center_create_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v2.types.NotificationConfig" - }, - { - "name": "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.cloud.securitycenter_v2.types.NotificationConfig", - "shortName": "create_notification_config" - }, - "description": "Sample for CreateNotificationConfig", - "file": "securitycenter_v2_generated_security_center_create_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v2_generated_security_center_create_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v2.types.NotificationConfig" - }, - { - "name": "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.cloud.securitycenter_v2.types.NotificationConfig", - "shortName": "create_notification_config" - }, - "description": "Sample for CreateNotificationConfig", - "file": "securitycenter_v2_generated_security_center_create_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v2_generated_security_center_create_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v2.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v2_generated_security_center_create_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_create_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_source", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateSource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "CreateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.CreateSourceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v2.types.Source" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Source", - "shortName": "create_source" - }, - "description": "Sample for CreateSource", - "file": "securitycenter_v2_generated_security_center_create_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_create_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest" - }, - { - "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_big_query_export" - }, - "description": "Sample for DeleteBigQueryExport", - "file": "securitycenter_v2_generated_security_center_delete_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v2_generated_security_center_delete_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest" - }, - { - "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_big_query_export" - }, - "description": "Sample for DeleteBigQueryExport", - "file": "securitycenter_v2_generated_security_center_delete_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v2_generated_security_center_delete_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest" - }, - { - "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_mute_config" - }, - "description": "Sample for DeleteMuteConfig", - "file": "securitycenter_v2_generated_security_center_delete_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v2_generated_security_center_delete_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest" - }, - { - "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_mute_config" - }, - "description": "Sample for DeleteMuteConfig", - "file": "securitycenter_v2_generated_security_center_delete_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v2_generated_security_center_delete_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest" - }, - { - "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_config" - }, - "description": "Sample for DeleteNotificationConfig", - "file": "securitycenter_v2_generated_security_center_delete_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v2_generated_security_center_delete_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest" - }, - { - "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_config" - }, - "description": "Sample for DeleteNotificationConfig", - "file": "securitycenter_v2_generated_security_center_delete_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v2_generated_security_center_delete_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest" - }, - { - "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_resource_value_config" - }, - "description": "Sample for DeleteResourceValueConfig", - "file": "securitycenter_v2_generated_security_center_delete_resource_value_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v2_generated_security_center_delete_resource_value_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "DeleteResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest" - }, - { - "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_resource_value_config" - }, - "description": "Sample for DeleteResourceValueConfig", - "file": "securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetBigQueryExportRequest" - }, - { - "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.securitycenter_v2.types.BigQueryExport", - "shortName": "get_big_query_export" - }, - "description": "Sample for GetBigQueryExport", - "file": "securitycenter_v2_generated_security_center_get_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetBigQueryExportRequest" - }, - { - "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.securitycenter_v2.types.BigQueryExport", - "shortName": "get_big_query_export" - }, - "description": "Sample for GetBigQueryExport", - "file": "securitycenter_v2_generated_security_center_get_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v2_generated_security_center_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "securitycenter_v2_generated_security_center_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetMuteConfigRequest" - }, - { - "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.securitycenter_v2.types.MuteConfig", - "shortName": "get_mute_config" - }, - "description": "Sample for GetMuteConfig", - "file": "securitycenter_v2_generated_security_center_get_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetMuteConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetMuteConfigRequest" - }, - { - "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.securitycenter_v2.types.MuteConfig", - "shortName": "get_mute_config" - }, - "description": "Sample for GetMuteConfig", - "file": "securitycenter_v2_generated_security_center_get_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetMuteConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetNotificationConfigRequest" - }, - { - "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.securitycenter_v2.types.NotificationConfig", - "shortName": "get_notification_config" - }, - "description": "Sample for GetNotificationConfig", - "file": "securitycenter_v2_generated_security_center_get_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetNotificationConfigRequest" - }, - { - "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.securitycenter_v2.types.NotificationConfig", - "shortName": "get_notification_config" - }, - "description": "Sample for GetNotificationConfig", - "file": "securitycenter_v2_generated_security_center_get_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest" - }, - { - "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.securitycenter_v2.types.ResourceValueConfig", - "shortName": "get_resource_value_config" - }, - "description": "Sample for GetResourceValueConfig", - "file": "securitycenter_v2_generated_security_center_get_resource_value_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_resource_value_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest" - }, - { - "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.securitycenter_v2.types.ResourceValueConfig", - "shortName": "get_resource_value_config" - }, - "description": "Sample for GetResourceValueConfig", - "file": "securitycenter_v2_generated_security_center_get_resource_value_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_resource_value_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_simulation", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSimulation", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSimulation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetSimulationRequest" - }, - { - "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.securitycenter_v2.types.Simulation", - "shortName": "get_simulation" - }, - "description": "Sample for GetSimulation", - "file": "securitycenter_v2_generated_security_center_get_simulation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSimulation_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_simulation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_simulation", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSimulation", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSimulation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetSimulationRequest" - }, - { - "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.securitycenter_v2.types.Simulation", - "shortName": "get_simulation" - }, - "description": "Sample for GetSimulation", - "file": "securitycenter_v2_generated_security_center_get_simulation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSimulation_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_simulation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetSourceRequest" - }, - { - "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.securitycenter_v2.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v2_generated_security_center_get_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_source", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetSourceRequest" - }, - { - "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.securitycenter_v2.types.Source", - "shortName": "get_source" - }, - "description": "Sample for GetSource", - "file": "securitycenter_v2_generated_security_center_get_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_valued_resource", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetValuedResource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetValuedResource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetValuedResourceRequest" - }, - { - "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.securitycenter_v2.types.ValuedResource", - "shortName": "get_valued_resource" - }, - "description": "Sample for GetValuedResource", - "file": "securitycenter_v2_generated_security_center_get_valued_resource_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetValuedResource_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_valued_resource_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_valued_resource", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetValuedResource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GetValuedResource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GetValuedResourceRequest" - }, - { - "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.securitycenter_v2.types.ValuedResource", - "shortName": "get_valued_resource" - }, - "description": "Sample for GetValuedResource", - "file": "securitycenter_v2_generated_security_center_get_valued_resource_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GetValuedResource_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_get_valued_resource_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsAsyncPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v2_generated_security_center_group_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GroupFindings_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": "securitycenter_v2_generated_security_center_group_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.group_findings", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GroupFindings", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "GroupFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.GroupFindingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "group_by", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsPager", - "shortName": "group_findings" - }, - "description": "Sample for GroupFindings", - "file": "securitycenter_v2_generated_security_center_group_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_GroupFindings_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": "securitycenter_v2_generated_security_center_group_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_attack_paths", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListAttackPaths", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAttackPaths" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListAttackPathsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListAttackPathsAsyncPager", - "shortName": "list_attack_paths" - }, - "description": "Sample for ListAttackPaths", - "file": "securitycenter_v2_generated_security_center_list_attack_paths_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v2_generated_security_center_list_attack_paths_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_attack_paths", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListAttackPaths", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListAttackPaths" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListAttackPathsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListAttackPathsPager", - "shortName": "list_attack_paths" - }, - "description": "Sample for ListAttackPaths", - "file": "securitycenter_v2_generated_security_center_list_attack_paths_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v2_generated_security_center_list_attack_paths_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_big_query_exports", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListBigQueryExports", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListBigQueryExports" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsAsyncPager", - "shortName": "list_big_query_exports" - }, - "description": "Sample for ListBigQueryExports", - "file": "securitycenter_v2_generated_security_center_list_big_query_exports_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v2_generated_security_center_list_big_query_exports_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_big_query_exports", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListBigQueryExports", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListBigQueryExports" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsPager", - "shortName": "list_big_query_exports" - }, - "description": "Sample for ListBigQueryExports", - "file": "securitycenter_v2_generated_security_center_list_big_query_exports_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v2_generated_security_center_list_big_query_exports_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListFindingsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListFindingsAsyncPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v2_generated_security_center_list_findings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListFindings_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": "securitycenter_v2_generated_security_center_list_findings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_findings", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListFindings", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListFindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListFindingsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListFindingsPager", - "shortName": "list_findings" - }, - "description": "Sample for ListFindings", - "file": "securitycenter_v2_generated_security_center_list_findings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListFindings_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": "securitycenter_v2_generated_security_center_list_findings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_mute_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListMuteConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListMuteConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListMuteConfigsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsAsyncPager", - "shortName": "list_mute_configs" - }, - "description": "Sample for ListMuteConfigs", - "file": "securitycenter_v2_generated_security_center_list_mute_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v2_generated_security_center_list_mute_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_mute_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListMuteConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListMuteConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListMuteConfigsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsPager", - "shortName": "list_mute_configs" - }, - "description": "Sample for ListMuteConfigs", - "file": "securitycenter_v2_generated_security_center_list_mute_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v2_generated_security_center_list_mute_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_notification_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListNotificationConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListNotificationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsAsyncPager", - "shortName": "list_notification_configs" - }, - "description": "Sample for ListNotificationConfigs", - "file": "securitycenter_v2_generated_security_center_list_notification_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v2_generated_security_center_list_notification_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_notification_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListNotificationConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListNotificationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsPager", - "shortName": "list_notification_configs" - }, - "description": "Sample for ListNotificationConfigs", - "file": "securitycenter_v2_generated_security_center_list_notification_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v2_generated_security_center_list_notification_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsAsyncPager", - "shortName": "list_resource_value_configs" - }, - "description": "Sample for ListResourceValueConfigs", - "file": "securitycenter_v2_generated_security_center_list_resource_value_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v2_generated_security_center_list_resource_value_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_resource_value_configs", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListResourceValueConfigs", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListResourceValueConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsPager", - "shortName": "list_resource_value_configs" - }, - "description": "Sample for ListResourceValueConfigs", - "file": "securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListSourcesRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListSourcesAsyncPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v2_generated_security_center_list_sources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListSources_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": "securitycenter_v2_generated_security_center_list_sources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_sources", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListSources", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListSources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListSourcesRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListSourcesPager", - "shortName": "list_sources" - }, - "description": "Sample for ListSources", - "file": "securitycenter_v2_generated_security_center_list_sources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListSources_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": "securitycenter_v2_generated_security_center_list_sources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_valued_resources", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListValuedResources", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListValuedResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListValuedResourcesRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesAsyncPager", - "shortName": "list_valued_resources" - }, - "description": "Sample for ListValuedResources", - "file": "securitycenter_v2_generated_security_center_list_valued_resources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v2_generated_security_center_list_valued_resources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_valued_resources", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListValuedResources", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "ListValuedResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.ListValuedResourcesRequest" - }, - { - "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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesPager", - "shortName": "list_valued_resources" - }, - "description": "Sample for ListValuedResources", - "file": "securitycenter_v2_generated_security_center_list_valued_resources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v2_generated_security_center_list_valued_resources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v2.types.Finding.State" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v2_generated_security_center_set_finding_state_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_SetFindingState_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": "securitycenter_v2_generated_security_center_set_finding_state_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_finding_state", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetFindingState", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetFindingState" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.SetFindingStateRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "state", - "type": "google.cloud.securitycenter_v2.types.Finding.State" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Finding", - "shortName": "set_finding_state" - }, - "description": "Sample for SetFindingState", - "file": "securitycenter_v2_generated_security_center_set_finding_state_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_SetFindingState_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": "securitycenter_v2_generated_security_center_set_finding_state_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v2_generated_security_center_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_iam_policy", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetIamPolicy", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "securitycenter_v2_generated_security_center_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_mute", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetMute", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetMute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.SetMuteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "mute", - "type": "google.cloud.securitycenter_v2.types.Finding.Mute" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Finding", - "shortName": "set_mute" - }, - "description": "Sample for SetMute", - "file": "securitycenter_v2_generated_security_center_set_mute_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_SetMute_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": "securitycenter_v2_generated_security_center_set_mute_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_mute", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetMute", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "SetMute" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.SetMuteRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "mute", - "type": "google.cloud.securitycenter_v2.types.Finding.Mute" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.securitycenter_v2.types.Finding", - "shortName": "set_mute" - }, - "description": "Sample for SetMute", - "file": "securitycenter_v2_generated_security_center_set_mute_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_SetMute_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": "securitycenter_v2_generated_security_center_set_mute_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v2_generated_security_center_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.TestIamPermissions", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "securitycenter_v2_generated_security_center_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "securitycenter_v2_generated_security_center_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v2.types.BigQueryExport" - }, - { - "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.securitycenter_v2.types.BigQueryExport", - "shortName": "update_big_query_export" - }, - "description": "Sample for UpdateBigQueryExport", - "file": "securitycenter_v2_generated_security_center_update_big_query_export_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v2_generated_security_center_update_big_query_export_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_big_query_export", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateBigQueryExport", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateBigQueryExport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest" - }, - { - "name": "big_query_export", - "type": "google.cloud.securitycenter_v2.types.BigQueryExport" - }, - { - "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.securitycenter_v2.types.BigQueryExport", - "shortName": "update_big_query_export" - }, - "description": "Sample for UpdateBigQueryExport", - "file": "securitycenter_v2_generated_security_center_update_big_query_export_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_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": "securitycenter_v2_generated_security_center_update_big_query_export_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_external_system", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateExternalSystem", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateExternalSystem" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest" - }, - { - "name": "external_system", - "type": "google.cloud.securitycenter_v2.types.ExternalSystem" - }, - { - "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.securitycenter_v2.types.ExternalSystem", - "shortName": "update_external_system" - }, - "description": "Sample for UpdateExternalSystem", - "file": "securitycenter_v2_generated_security_center_update_external_system_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v2_generated_security_center_update_external_system_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_external_system", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateExternalSystem", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateExternalSystem" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest" - }, - { - "name": "external_system", - "type": "google.cloud.securitycenter_v2.types.ExternalSystem" - }, - { - "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.securitycenter_v2.types.ExternalSystem", - "shortName": "update_external_system" - }, - "description": "Sample for UpdateExternalSystem", - "file": "securitycenter_v2_generated_security_center_update_external_system_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_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": "securitycenter_v2_generated_security_center_update_external_system_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v2.types.Finding" - }, - { - "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.securitycenter_v2.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v2_generated_security_center_update_finding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v2_generated_security_center_update_finding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_finding", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateFinding", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateFinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateFindingRequest" - }, - { - "name": "finding", - "type": "google.cloud.securitycenter_v2.types.Finding" - }, - { - "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.securitycenter_v2.types.Finding", - "shortName": "update_finding" - }, - "description": "Sample for UpdateFinding", - "file": "securitycenter_v2_generated_security_center_update_finding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateFinding_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": "securitycenter_v2_generated_security_center_update_finding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v2.types.MuteConfig" - }, - { - "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.securitycenter_v2.types.MuteConfig", - "shortName": "update_mute_config" - }, - "description": "Sample for UpdateMuteConfig", - "file": "securitycenter_v2_generated_security_center_update_mute_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v2_generated_security_center_update_mute_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_mute_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateMuteConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateMuteConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest" - }, - { - "name": "mute_config", - "type": "google.cloud.securitycenter_v2.types.MuteConfig" - }, - { - "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.securitycenter_v2.types.MuteConfig", - "shortName": "update_mute_config" - }, - "description": "Sample for UpdateMuteConfig", - "file": "securitycenter_v2_generated_security_center_update_mute_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_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": "securitycenter_v2_generated_security_center_update_mute_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v2.types.NotificationConfig" - }, - { - "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.securitycenter_v2.types.NotificationConfig", - "shortName": "update_notification_config" - }, - "description": "Sample for UpdateNotificationConfig", - "file": "securitycenter_v2_generated_security_center_update_notification_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v2_generated_security_center_update_notification_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_notification_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateNotificationConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateNotificationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest" - }, - { - "name": "notification_config", - "type": "google.cloud.securitycenter_v2.types.NotificationConfig" - }, - { - "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.securitycenter_v2.types.NotificationConfig", - "shortName": "update_notification_config" - }, - "description": "Sample for UpdateNotificationConfig", - "file": "securitycenter_v2_generated_security_center_update_notification_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_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": "securitycenter_v2_generated_security_center_update_notification_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest" - }, - { - "name": "resource_value_config", - "type": "google.cloud.securitycenter_v2.types.ResourceValueConfig" - }, - { - "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.securitycenter_v2.types.ResourceValueConfig", - "shortName": "update_resource_value_config" - }, - "description": "Sample for UpdateResourceValueConfig", - "file": "securitycenter_v2_generated_security_center_update_resource_value_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v2_generated_security_center_update_resource_value_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_resource_value_config", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateResourceValueConfig", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateResourceValueConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest" - }, - { - "name": "resource_value_config", - "type": "google.cloud.securitycenter_v2.types.ResourceValueConfig" - }, - { - "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.securitycenter_v2.types.ResourceValueConfig", - "shortName": "update_resource_value_config" - }, - "description": "Sample for UpdateResourceValueConfig", - "file": "securitycenter_v2_generated_security_center_update_resource_value_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_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": "securitycenter_v2_generated_security_center_update_resource_value_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v2.types.SecurityMarks" - }, - { - "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.securitycenter_v2.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v2_generated_security_center_update_security_marks_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v2_generated_security_center_update_security_marks_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_security_marks", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSecurityMarks", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSecurityMarks" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest" - }, - { - "name": "security_marks", - "type": "google.cloud.securitycenter_v2.types.SecurityMarks" - }, - { - "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.securitycenter_v2.types.SecurityMarks", - "shortName": "update_security_marks" - }, - "description": "Sample for UpdateSecurityMarks", - "file": "securitycenter_v2_generated_security_center_update_security_marks_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_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": "securitycenter_v2_generated_security_center_update_security_marks_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", - "shortName": "SecurityCenterAsyncClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v2.types.Source" - }, - { - "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.securitycenter_v2.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v2_generated_security_center_update_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSource_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": "securitycenter_v2_generated_security_center_update_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", - "shortName": "SecurityCenterClient" - }, - "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_source", - "method": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSource", - "service": { - "fullName": "google.cloud.securitycenter.v2.SecurityCenter", - "shortName": "SecurityCenter" - }, - "shortName": "UpdateSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.securitycenter_v2.types.UpdateSourceRequest" - }, - { - "name": "source", - "type": "google.cloud.securitycenter_v2.types.Source" - }, - { - "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.securitycenter_v2.types.Source", - "shortName": "update_source" - }, - "description": "Sample for UpdateSource", - "file": "securitycenter_v2_generated_security_center_update_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSource_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": "securitycenter_v2_generated_security_center_update_source_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py b/owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py deleted file mode 100644 index f95da838422b..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/scripts/fixup_securitycenter_v2_keywords.py +++ /dev/null @@ -1,215 +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 securitycenterCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_create_resource_value_configs': ('parent', 'requests', ), - 'bulk_mute_findings': ('parent', 'filter', 'mute_state', ), - 'create_big_query_export': ('parent', 'big_query_export', 'big_query_export_id', ), - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_mute_config': ('parent', 'mute_config', 'mute_config_id', ), - 'create_notification_config': ('parent', 'config_id', 'notification_config', ), - 'create_source': ('parent', 'source', ), - 'delete_big_query_export': ('name', ), - 'delete_mute_config': ('name', ), - 'delete_notification_config': ('name', ), - 'delete_resource_value_config': ('name', ), - 'get_big_query_export': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_mute_config': ('name', ), - 'get_notification_config': ('name', ), - 'get_resource_value_config': ('name', ), - 'get_simulation': ('name', ), - 'get_source': ('name', ), - 'get_valued_resource': ('name', ), - 'group_findings': ('parent', 'group_by', 'filter', 'page_token', 'page_size', ), - 'list_attack_paths': ('parent', 'filter', 'page_token', 'page_size', ), - 'list_big_query_exports': ('parent', 'page_size', 'page_token', ), - 'list_findings': ('parent', 'filter', 'order_by', 'field_mask', 'page_token', 'page_size', ), - 'list_mute_configs': ('parent', 'page_size', 'page_token', ), - 'list_notification_configs': ('parent', 'page_token', 'page_size', ), - 'list_resource_value_configs': ('parent', 'page_size', 'page_token', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'list_valued_resources': ('parent', 'filter', 'page_token', 'page_size', 'order_by', ), - 'set_finding_state': ('name', 'state', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'set_mute': ('name', 'mute', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_big_query_export': ('big_query_export', 'update_mask', ), - 'update_external_system': ('external_system', 'update_mask', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_mute_config': ('mute_config', 'update_mask', ), - 'update_notification_config': ('notification_config', 'update_mask', ), - 'update_resource_value_config': ('resource_value_config', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', ), - 'update_source': ('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=securitycenterCallTransformer(), -): - """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 securitycenter 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-securitycenter/v2/setup.py b/owl-bot-staging/google-cloud-securitycenter/v2/setup.py deleted file mode 100644 index c4538ec101f3..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/setup.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. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-securitycenter' - - -description = "Google Cloud Securitycenter API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/securitycenter/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", - "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", -] -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter" - -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-securitycenter/v2/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-securitycenter/v2/tests/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/tests/unit/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/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-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/__init__.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_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-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py b/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py deleted file mode 100644 index 6104ead93daa..000000000000 --- a/owl-bot-staging/google-cloud-securitycenter/v2/tests/unit/gapic/securitycenter_v2/test_security_center.py +++ /dev/null @@ -1,31716 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR 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 -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 - -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.securitycenter_v2.services.security_center import SecurityCenterAsyncClient -from google.cloud.securitycenter_v2.services.security_center import SecurityCenterClient -from google.cloud.securitycenter_v2.services.security_center import pagers -from google.cloud.securitycenter_v2.services.security_center import transports -from google.cloud.securitycenter_v2.types import access -from google.cloud.securitycenter_v2.types import application -from google.cloud.securitycenter_v2.types import attack_exposure -from google.cloud.securitycenter_v2.types import attack_path -from google.cloud.securitycenter_v2.types import backup_disaster_recovery -from google.cloud.securitycenter_v2.types import bigquery_export -from google.cloud.securitycenter_v2.types import cloud_armor -from google.cloud.securitycenter_v2.types import cloud_dlp_data_profile -from google.cloud.securitycenter_v2.types import cloud_dlp_inspection -from google.cloud.securitycenter_v2.types import compliance -from google.cloud.securitycenter_v2.types import connection -from google.cloud.securitycenter_v2.types import contact_details -from google.cloud.securitycenter_v2.types import container -from google.cloud.securitycenter_v2.types import database -from google.cloud.securitycenter_v2.types import exfiltration -from google.cloud.securitycenter_v2.types import external_system -from google.cloud.securitycenter_v2.types import external_system as gcs_external_system -from google.cloud.securitycenter_v2.types import file -from google.cloud.securitycenter_v2.types import finding -from google.cloud.securitycenter_v2.types import finding as gcs_finding -from google.cloud.securitycenter_v2.types import group_membership -from google.cloud.securitycenter_v2.types import iam_binding -from google.cloud.securitycenter_v2.types import indicator -from google.cloud.securitycenter_v2.types import kernel_rootkit -from google.cloud.securitycenter_v2.types import kubernetes -from google.cloud.securitycenter_v2.types import label -from google.cloud.securitycenter_v2.types import load_balancer -from google.cloud.securitycenter_v2.types import log_entry -from google.cloud.securitycenter_v2.types import mitre_attack -from google.cloud.securitycenter_v2.types import mute_config -from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config -from google.cloud.securitycenter_v2.types import notebook -from google.cloud.securitycenter_v2.types import notification_config -from google.cloud.securitycenter_v2.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v2.types import org_policy -from google.cloud.securitycenter_v2.types import process -from google.cloud.securitycenter_v2.types import resource -from google.cloud.securitycenter_v2.types import resource_value_config -from google.cloud.securitycenter_v2.types import resource_value_config as gcs_resource_value_config -from google.cloud.securitycenter_v2.types import security_marks -from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v2.types import security_posture -from google.cloud.securitycenter_v2.types import securitycenter_service -from google.cloud.securitycenter_v2.types import simulation -from google.cloud.securitycenter_v2.types import source -from google.cloud.securitycenter_v2.types import source as gcs_source -from google.cloud.securitycenter_v2.types import toxic_combination -from google.cloud.securitycenter_v2.types import valued_resource -from google.cloud.securitycenter_v2.types import vulnerability -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 duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls 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 SecurityCenterClient._get_default_mtls_endpoint(None) is None - assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert SecurityCenterClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert SecurityCenterClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._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 SecurityCenterClient._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 SecurityCenterClient._get_client_cert_source(None, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert SecurityCenterClient._get_client_cert_source(None, True) is mock_default_cert_source - assert SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert SecurityCenterClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - assert SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - SecurityCenterClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert SecurityCenterClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert SecurityCenterClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert SecurityCenterClient._get_universe_domain(None, None) == SecurityCenterClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - SecurityCenterClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SecurityCenterGrpcTransport, "grpc"), - (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - 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", [ - (SecurityCenterClient, "grpc"), - (SecurityCenterAsyncClient, "grpc_asyncio"), - (SecurityCenterClient, "rest"), -]) -def test_security_center_client_from_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 == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://securitycenter.googleapis.com' - ) - - -def test_security_center_client_get_transport_class(): - transport = SecurityCenterClient.get_transport_class() - available_transports = [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterRestTransport, - ] - assert transport in available_transports - - transport = SecurityCenterClient.get_transport_class("grpc") - assert transport == transports.SecurityCenterGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(SecurityCenterClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_security_center_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, 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", [ - SecurityCenterClient, SecurityCenterAsyncClient -]) -@mock.patch.object(SecurityCenterClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(SecurityCenterAsyncClient)) -def test_security_center_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = SecurityCenterClient._DEFAULT_UNIVERSE - default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), -]) -def test_security_center_client_client_options_scopes(client_class, transport_class, 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), -]) -def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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_security_center_client_client_options_from_dict(): - with mock.patch('google.cloud.securitycenter_v2.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", grpc_helpers), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_security_center_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.BatchCreateResourceValueConfigsRequest, - dict, -]) -def test_batch_create_resource_value_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse( - ) - response = client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) - - -def test_batch_create_resource_value_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_create_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() - - -def test_batch_create_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.BatchCreateResourceValueConfigsRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_create_resource_value_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest( - parent='parent_value', - ) - -def test_batch_create_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc - request = {} - client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_resource_value_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_batch_create_resource_value_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( - )) - response = await client.batch_create_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() - -@pytest.mark.asyncio -async def test_batch_create_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.batch_create_resource_value_configs] = mock_object - - request = {} - await client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.batch_create_resource_value_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse( - )) - response = await client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) - - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_async_from_dict(): - await test_batch_create_resource_value_configs_async(request_type=dict) - - -def test_batch_create_resource_value_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - client.batch_create_resource_value_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_batch_create_resource_value_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) - await client.batch_create_resource_value_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_batch_create_resource_value_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.batch_create_resource_value_configs( - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(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 - arg = args[0].requests - mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] - assert arg == mock_val - - -def test_batch_create_resource_value_configs_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_create_resource_value_configs( - securitycenter_service.BatchCreateResourceValueConfigsRequest(), - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], - ) - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.BatchCreateResourceValueConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.batch_create_resource_value_configs( - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(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 - arg = args[0].requests - mock_val = [securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_batch_create_resource_value_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.batch_create_resource_value_configs( - securitycenter_service.BatchCreateResourceValueConfigsRequest(), - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.BulkMuteFindingsRequest, - dict, -]) -def test_bulk_mute_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.bulk_mute_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BulkMuteFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_bulk_mute_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.bulk_mute_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BulkMuteFindingsRequest() - - -def test_bulk_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.BulkMuteFindingsRequest( - parent='parent_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.bulk_mute_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BulkMuteFindingsRequest( - parent='parent_value', - filter='filter_value', - ) - -def test_bulk_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc - request = {} - client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.BulkMuteFindingsRequest() - -@pytest.mark.asyncio -async def test_bulk_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.bulk_mute_findings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.bulk_mute_findings] = mock_object - - request = {} - await client.bulk_mute_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.bulk_mute_findings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_bulk_mute_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.BulkMuteFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.BulkMuteFindingsRequest() - 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_bulk_mute_findings_async_from_dict(): - await test_bulk_mute_findings_async(request_type=dict) - - -def test_bulk_mute_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BulkMuteFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.bulk_mute_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_bulk_mute_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.BulkMuteFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.bulk_mute_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_bulk_mute_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings( - 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_bulk_mute_findings_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.bulk_mute_findings( - securitycenter_service.BulkMuteFindingsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_bulk_mute_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bulk_mute_findings), - '__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.bulk_mute_findings( - 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_bulk_mute_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.bulk_mute_findings( - securitycenter_service.BulkMuteFindingsRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateBigQueryExportRequest, - dict, -]) -def test_create_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - response = client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -def test_create_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateBigQueryExportRequest() - - -def test_create_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateBigQueryExportRequest( - parent='parent_value', - big_query_export_id='big_query_export_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateBigQueryExportRequest( - parent='parent_value', - big_query_export_id='big_query_export_id_value', - ) - -def test_create_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - request = {} - client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_big_query_export(request) - - # Establish that a new wrapper 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_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.create_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_create_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_big_query_export] = mock_object - - request = {} - await client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -@pytest.mark.asyncio -async def test_create_big_query_export_async_from_dict(): - await test_create_big_query_export_async(request_type=dict) - - -def test_create_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateBigQueryExportRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value = bigquery_export.BigQueryExport() - client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateBigQueryExportRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - await client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_big_query_export( - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_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].big_query_export - mock_val = bigquery_export.BigQueryExport(name='name_value') - assert arg == mock_val - arg = args[0].big_query_export_id - mock_val = 'big_query_export_id_value' - assert arg == mock_val - - -def test_create_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.CreateBigQueryExportRequest(), - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_id_value', - ) - -@pytest.mark.asyncio -async def test_create_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_big_query_export( - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_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].big_query_export - mock_val = bigquery_export.BigQueryExport(name='name_value') - assert arg == mock_val - arg = args[0].big_query_export_id - mock_val = 'big_query_export_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_big_query_export( - securitycenter_service.CreateBigQueryExportRequest(), - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_create_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest( - parent='parent_value', - finding_id='finding_id_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.create_finding] = mock_rpc - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_finding] = mock_object - - request = {} - await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_create_finding_async_from_dict(): - await test_create_finding_async(request_type=dict) - - -def test_create_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_finding( - parent='parent_value', - finding=gcs_finding.Finding(name='name_value'), - finding_id='finding_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].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - - -def test_create_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding=gcs_finding.Finding(name='name_value'), - finding_id='finding_id_value', - ) - -@pytest.mark.asyncio -async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_finding( - parent='parent_value', - finding=gcs_finding.Finding(name='name_value'), - finding_id='finding_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].finding - mock_val = gcs_finding.Finding(name='name_value') - assert arg == mock_val - arg = args[0].finding_id - mock_val = 'finding_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding=gcs_finding.Finding(name='name_value'), - finding_id='finding_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateMuteConfigRequest, - dict, -]) -def test_create_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - ) - response = client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - - -def test_create_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateMuteConfigRequest() - - -def test_create_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateMuteConfigRequest( - parent='parent_value', - mute_config_id='mute_config_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateMuteConfigRequest( - parent='parent_value', - mute_config_id='mute_config_id_value', - ) - -def test_create_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - request = {} - client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.create_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateMuteConfigRequest() - -@pytest.mark.asyncio -async def test_create_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_mute_config] = mock_object - - request = {} - await client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - - -@pytest.mark.asyncio -async def test_create_mute_config_async_from_dict(): - await test_create_mute_config_async(request_type=dict) - -def test_create_mute_config_routing_parameters(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateMuteConfigRequest(**{"parent": "projects/sample1/locations/sample2"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.create_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateMuteConfigRequest(**{"parent": "organizations/sample1/locations/sample2"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.create_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateMuteConfigRequest(**{"parent": "folders/sample1/locations/sample2"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.create_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_create_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_mute_config( - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_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].mute_config - mock_val = gcs_mute_config.MuteConfig(name='name_value') - assert arg == mock_val - arg = args[0].mute_config_id - mock_val = 'mute_config_id_value' - assert arg == mock_val - - -def test_create_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.CreateMuteConfigRequest(), - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_mute_config( - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_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].mute_config - mock_val = gcs_mute_config.MuteConfig(name='name_value') - assert arg == mock_val - arg = args[0].mute_config_id - mock_val = 'mute_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_mute_config( - securitycenter_service.CreateMuteConfigRequest(), - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateNotificationConfigRequest, - dict, -]) -def test_create_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_create_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateNotificationConfigRequest( - parent='parent_value', - config_id='config_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest( - parent='parent_value', - config_id='config_id_value', - ) - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_create_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_notification_config] = mock_object - - request = {} - await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_create_notification_config_async_from_dict(): - await test_create_notification_config_async(request_type=dict) - - -def test_create_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.create_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.create_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_notification_config( - parent='parent_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - config_id='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].notification_config - mock_val = gcs_notification_config.NotificationConfig(name='name_value') - assert arg == mock_val - arg = args[0].config_id - mock_val = 'config_id_value' - assert arg == mock_val - - -def test_create_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - config_id='config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_notification_config( - parent='parent_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - config_id='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].notification_config - mock_val = gcs_notification_config.NotificationConfig(name='name_value') - assert arg == mock_val - arg = args[0].config_id - mock_val = 'config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_notification_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - config_id='config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_create_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest( - parent='parent_value', - ) - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - -@pytest.mark.asyncio -async def test_create_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_source] = mock_object - - request = {} - await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.CreateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_create_source_async_from_dict(): - await test_create_source_async(request_type=dict) - - -def test_create_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.create_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - - -def test_create_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_source( - parent='parent_value', - source=gcs_source.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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].source - mock_val = gcs_source.Source(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteBigQueryExportRequest, - dict, -]) -def test_delete_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() - - -def test_delete_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteBigQueryExportRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteBigQueryExportRequest( - name='name_value', - ) - -def test_delete_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - request = {} - client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_big_query_export(request) - - # Establish that a new wrapper 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_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_delete_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_big_query_export] = mock_object - - request = {} - await client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteBigQueryExportRequest() - 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_big_query_export_async_from_dict(): - await test_delete_big_query_export_async(request_type=dict) - - -def test_delete_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value = None - client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__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_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.DeleteBigQueryExportRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_big_query_export), - '__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_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_big_query_export( - securitycenter_service.DeleteBigQueryExportRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteMuteConfigRequest, - dict, -]) -def test_delete_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteMuteConfigRequest() - - -def test_delete_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteMuteConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteMuteConfigRequest( - name='name_value', - ) - -def test_delete_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - request = {} - client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteMuteConfigRequest() - -@pytest.mark.asyncio -async def test_delete_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_mute_config] = mock_object - - request = {} - await client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteMuteConfigRequest() - 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_mute_config_async_from_dict(): - await test_delete_mute_config_async(request_type=dict) - -def test_delete_mute_config_routing_parameters(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteMuteConfigRequest(**{"name": "projects/sample1/locations/sample2/muteConfigs/sample3"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value = None - client.delete_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteMuteConfigRequest(**{"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value = None - client.delete_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteMuteConfigRequest(**{"name": "folders/sample1/locations/sample2/muteConfigs/sample3"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_config), - '__call__') as call: - call.return_value = None - client.delete_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_delete_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.DeleteMuteConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_mute_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_mute_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_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_mute_config( - securitycenter_service.DeleteMuteConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteNotificationConfigRequest, - dict, -]) -def test_delete_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteNotificationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest( - name='name_value', - ) - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_delete_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_notification_config] = mock_object - - request = {} - await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteNotificationConfigRequest() - 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_config_async_from_dict(): - await test_delete_notification_config_async(request_type=dict) - - -def test_delete_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = None - client.delete_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_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_notification_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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_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_notification_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_notification_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteResourceValueConfigRequest, - dict, -]) -def test_delete_resource_value_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_resource_value_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() - - -def test_delete_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.DeleteResourceValueConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_resource_value_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest( - name='name_value', - ) - -def test_delete_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - request = {} - client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_resource_value_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_resource_value_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() - -@pytest.mark.asyncio -async def test_delete_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_resource_value_config] = mock_object - - request = {} - await client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.delete_resource_value_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteResourceValueConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.DeleteResourceValueConfigRequest() - 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_resource_value_config_async_from_dict(): - await test_delete_resource_value_config_async(request_type=dict) - - -def test_delete_resource_value_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value = None - client.delete_resource_value_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_resource_value_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_resource_value_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_resource_value_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_config( - securitycenter_service.DeleteResourceValueConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_resource_value_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_resource_value_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_resource_value_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_resource_value_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_resource_value_config( - securitycenter_service.DeleteResourceValueConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetBigQueryExportRequest, - dict, -]) -def test_get_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - response = client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -def test_get_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetBigQueryExportRequest() - - -def test_get_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetBigQueryExportRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetBigQueryExportRequest( - name='name_value', - ) - -def test_get_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc - request = {} - client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.get_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_get_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_big_query_export] = mock_object - - request = {} - await client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -@pytest.mark.asyncio -async def test_get_big_query_export_async_from_dict(): - await test_get_big_query_export_async(request_type=dict) - - -def test_get_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value = bigquery_export.BigQueryExport() - client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetBigQueryExportRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - await client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.GetBigQueryExportRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_big_query_export( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_big_query_export( - securitycenter_service.GetBigQueryExportRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSimulationRequest, - dict, -]) -def test_get_simulation(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - response = client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSimulationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, simulation.Simulation) - assert response.name == 'name_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -def test_get_simulation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_simulation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSimulationRequest() - - -def test_get_simulation_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSimulationRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_simulation(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSimulationRequest( - name='name_value', - ) - -def test_get_simulation_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_simulation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc - request = {} - client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_simulation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_simulation_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_simulation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSimulationRequest() - -@pytest.mark.asyncio -async def test_get_simulation_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_simulation in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_simulation] = mock_object - - request = {} - await client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_simulation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_simulation_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSimulationRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSimulationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, simulation.Simulation) - assert response.name == 'name_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -@pytest.mark.asyncio -async def test_get_simulation_async_from_dict(): - await test_get_simulation_async(request_type=dict) - - -def test_get_simulation_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSimulationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value = simulation.Simulation() - client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_simulation_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSimulationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) - await client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_simulation_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = simulation.Simulation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_simulation( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_simulation_flattened_error(): - client = SecurityCenterClient( - credentials=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_simulation( - securitycenter_service.GetSimulationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_simulation_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_simulation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = simulation.Simulation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(simulation.Simulation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_simulation( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_simulation_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_simulation( - securitycenter_service.GetSimulationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetValuedResourceRequest, - dict, -]) -def test_get_valued_resource(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - ) - response = client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetValuedResourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, valued_resource.ValuedResource) - assert response.name == 'name_value' - assert response.resource == 'resource_value' - assert response.resource_type == 'resource_type_value' - assert response.display_name == 'display_name_value' - assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW - assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) - - -def test_get_valued_resource_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_valued_resource() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetValuedResourceRequest() - - -def test_get_valued_resource_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetValuedResourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_valued_resource(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetValuedResourceRequest( - name='name_value', - ) - -def test_get_valued_resource_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_valued_resource in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc - request = {} - client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_valued_resource(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_valued_resource_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - )) - response = await client.get_valued_resource() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetValuedResourceRequest() - -@pytest.mark.asyncio -async def test_get_valued_resource_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_valued_resource in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_valued_resource] = mock_object - - request = {} - await client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_valued_resource(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_valued_resource_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetValuedResourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - )) - response = await client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetValuedResourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, valued_resource.ValuedResource) - assert response.name == 'name_value' - assert response.resource == 'resource_value' - assert response.resource_type == 'resource_type_value' - assert response.display_name == 'display_name_value' - assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW - assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) - - -@pytest.mark.asyncio -async def test_get_valued_resource_async_from_dict(): - await test_get_valued_resource_async(request_type=dict) - - -def test_get_valued_resource_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetValuedResourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value = valued_resource.ValuedResource() - client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_valued_resource_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetValuedResourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) - await client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_valued_resource_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = valued_resource.ValuedResource() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_valued_resource( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert 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_valued_resource_flattened_error(): - client = SecurityCenterClient( - credentials=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_valued_resource( - securitycenter_service.GetValuedResourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_valued_resource_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_valued_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = valued_resource.ValuedResource() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(valued_resource.ValuedResource()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_valued_resource( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_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_valued_resource_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_valued_resource( - securitycenter_service.GetValuedResourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.GetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest( - resource='resource_value', - ) - -def test_get_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_iam_policy] = mock_object - - request = {} - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.GetIamPolicyRequest() - 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_get_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetMuteConfigRequest, - dict, -]) -def test_get_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=mute_config.MuteConfig.MuteConfigType.STATIC, - ) - response = client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC - - -def test_get_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetMuteConfigRequest() - - -def test_get_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetMuteConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetMuteConfigRequest( - name='name_value', - ) - -def test_get_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_mute_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_mute_config] = mock_rpc - request = {} - client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.get_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetMuteConfigRequest() - -@pytest.mark.asyncio -async def test_get_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_mute_config] = mock_object - - request = {} - await client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC - - -@pytest.mark.asyncio -async def test_get_mute_config_async_from_dict(): - await test_get_mute_config_async(request_type=dict) - -def test_get_mute_config_routing_parameters(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetMuteConfigRequest(**{"name": "projects/sample1/locations/sample2/muteConfigs/sample3"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value = mute_config.MuteConfig() - client.get_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetMuteConfigRequest(**{"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value = mute_config.MuteConfig() - client.get_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetMuteConfigRequest(**{"name": "folders/sample1/locations/sample2/muteConfigs/sample3"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - call.return_value = mute_config.MuteConfig() - client.get_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_get_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mute_config.MuteConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_mute_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_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.GetMuteConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mute_config.MuteConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mute_config.MuteConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_mute_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_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_mute_config( - securitycenter_service.GetMuteConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetNotificationConfigRequest, - dict, -]) -def test_get_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_get_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetNotificationConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest( - name='name_value', - ) - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_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_notification_config] = mock_rpc - request = {} - client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_get_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_notification_config] = mock_object - - request = {} - await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_get_notification_config_async_from_dict(): - await test_get_notification_config_async(request_type=dict) - - -def test_get_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = notification_config.NotificationConfig() - client.get_notification_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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - 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_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - await client.get_notification_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_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_notification_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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_notification_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_notification_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetResourceValueConfigRequest, - dict, -]) -def test_get_resource_value_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - response = client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -def test_get_resource_value_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetResourceValueConfigRequest() - - -def test_get_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetResourceValueConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_resource_value_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetResourceValueConfigRequest( - name='name_value', - ) - -def test_get_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc - request = {} - client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_resource_value_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_resource_value_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetResourceValueConfigRequest() - -@pytest.mark.asyncio -async def test_get_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_resource_value_config] = mock_object - - request = {} - await client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_resource_value_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetResourceValueConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -@pytest.mark.asyncio -async def test_get_resource_value_config_async_from_dict(): - await test_get_resource_value_config_async(request_type=dict) - - -def test_get_resource_value_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value = resource_value_config.ResourceValueConfig() - client.get_resource_value_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_resource_value_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetResourceValueConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) - await client.get_resource_value_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_resource_value_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resource_value_config.ResourceValueConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_resource_value_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_resource_value_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_config( - securitycenter_service.GetResourceValueConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_resource_value_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resource_value_config.ResourceValueConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource_value_config.ResourceValueConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_resource_value_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_resource_value_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_resource_value_config( - securitycenter_service.GetResourceValueConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_get_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GetSourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest( - name='name_value', - ) - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - -@pytest.mark.asyncio -async def test_get_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_source] = mock_object - - request = {} - await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.get_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GetSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_get_source_async_from_dict(): - await test_get_source_async(request_type=dict) - - -def test_get_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = source.Source() - client.get_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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_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_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_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_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_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.group_findings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.group_findings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest( - parent='parent_value', - filter='filter_value', - group_by='group_by_value', - page_token='page_token_value', - ) - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - -@pytest.mark.asyncio -async def test_group_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.group_findings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.group_findings] = mock_object - - request = {} - await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.group_findings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.GroupFindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_findings_async_from_dict(): - await test_group_findings_async(request_type=dict) - - -def test_group_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_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_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - await client.group_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_group_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that the 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - - -def test_group_findings_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - -@pytest.mark.asyncio -async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that 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].group_by - mock_val = 'group_by_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_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, securitycenter_service.GroupResult) - for i in results) -def test_group_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_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_group_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_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, securitycenter_service.GroupResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - 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.group_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", [ - securitycenter_service.ListAttackPathsRequest, - dict, -]) -def test_list_attack_paths(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAttackPathsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttackPathsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_attack_paths_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_attack_paths() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAttackPathsRequest() - - -def test_list_attack_paths_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListAttackPathsRequest( - 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_attack_paths), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_attack_paths(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAttackPathsRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_value', - ) - -def test_list_attack_paths_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_attack_paths in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc - request = {} - client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_attack_paths(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_attack_paths_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_attack_paths() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAttackPathsRequest() - -@pytest.mark.asyncio -async def test_list_attack_paths_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_attack_paths in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_attack_paths] = mock_object - - request = {} - await client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_attack_paths(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_attack_paths_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAttackPathsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListAttackPathsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttackPathsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_attack_paths_async_from_dict(): - await test_list_attack_paths_async(request_type=dict) - - -def test_list_attack_paths_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAttackPathsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - call.return_value = securitycenter_service.ListAttackPathsResponse() - client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_attack_paths_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAttackPathsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) - await client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_attack_paths_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAttackPathsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_attack_paths( - 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_attack_paths_flattened_error(): - client = SecurityCenterClient( - credentials=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_attack_paths( - securitycenter_service.ListAttackPathsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_attack_paths_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAttackPathsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAttackPathsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_attack_paths( - 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_attack_paths_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_attack_paths( - securitycenter_service.ListAttackPathsRequest(), - parent='parent_value', - ) - - -def test_list_attack_paths_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_attack_paths(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, attack_path.AttackPath) - for i in results) -def test_list_attack_paths_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - RuntimeError, - ) - pages = list(client.list_attack_paths(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_attack_paths_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_attack_paths(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, attack_path.AttackPath) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_attack_paths_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_attack_paths), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - 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_attack_paths(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", [ - securitycenter_service.ListBigQueryExportsRequest, - dict, -]) -def test_list_big_query_exports(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListBigQueryExportsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryExportsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_big_query_exports_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_big_query_exports() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListBigQueryExportsRequest() - - -def test_list_big_query_exports_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListBigQueryExportsRequest( - 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_big_query_exports), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_big_query_exports(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListBigQueryExportsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_big_query_exports_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_big_query_exports in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc - request = {} - client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_big_query_exports(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_big_query_exports_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_big_query_exports() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListBigQueryExportsRequest() - -@pytest.mark.asyncio -async def test_list_big_query_exports_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_exports in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_big_query_exports] = mock_object - - request = {} - await client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_big_query_exports(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_big_query_exports_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListBigQueryExportsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListBigQueryExportsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryExportsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_big_query_exports_async_from_dict(): - await test_list_big_query_exports_async(request_type=dict) - - -def test_list_big_query_exports_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListBigQueryExportsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - call.return_value = securitycenter_service.ListBigQueryExportsResponse() - client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_big_query_exports_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListBigQueryExportsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) - await client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_big_query_exports_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListBigQueryExportsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_big_query_exports( - 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_big_query_exports_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_exports( - securitycenter_service.ListBigQueryExportsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_big_query_exports_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListBigQueryExportsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListBigQueryExportsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_big_query_exports( - 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_big_query_exports_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_big_query_exports( - securitycenter_service.ListBigQueryExportsRequest(), - parent='parent_value', - ) - - -def test_list_big_query_exports_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_big_query_exports(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, bigquery_export.BigQueryExport) - for i in results) -def test_list_big_query_exports_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - RuntimeError, - ) - pages = list(client.list_big_query_exports(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_big_query_exports_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_big_query_exports(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, bigquery_export.BigQueryExport) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_big_query_exports_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_exports), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - 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_big_query_exports(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", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -def test_list_findings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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] == securitycenter_service.ListFindingsRequest( - parent='parent_value', - filter='filter_value', - order_by='order_by_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - -@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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_findings] = mock_object - - request = {} - await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - 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 = securitycenter_service.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' - assert response.total_size == 1086 - - -@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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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 = securitycenter_service.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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.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(securitycenter_service.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 = SecurityCenterClient( - 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 = securitycenter_service.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', - ) - - # Establish that the 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_findings_flattened_error(): - client = SecurityCenterClient( - credentials=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( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_findings_flattened_async(): - client = SecurityCenterAsyncClient( - 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 = securitycenter_service.ListFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.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', - ) - - # Establish that 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_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_findings( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - - -def test_list_findings_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in results) -def test_list_findings_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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 = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_findings_async_pages(): - client = SecurityCenterAsyncClient( - 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__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - 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", [ - securitycenter_service.ListMuteConfigsRequest, - dict, -]) -def test_list_mute_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListMuteConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMuteConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_mute_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_mute_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListMuteConfigsRequest() - - -def test_list_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListMuteConfigsRequest( - 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_mute_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_mute_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListMuteConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_mute_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_mute_configs] = mock_rpc - request = {} - client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_mute_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_mute_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_mute_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListMuteConfigsRequest() - -@pytest.mark.asyncio -async def test_list_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_mute_configs] = mock_object - - request = {} - await client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_mute_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_mute_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListMuteConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListMuteConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMuteConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_mute_configs_async_from_dict(): - await test_list_mute_configs_async(request_type=dict) - -def test_list_mute_configs_routing_parameters(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListMuteConfigsRequest(**{"parent": "projects/sample1/locations/sample2/muteConfigs"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListMuteConfigsResponse() - client.list_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListMuteConfigsRequest(**{"parent": "organizations/sample1/locations/sample2/muteConfigs"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListMuteConfigsResponse() - client.list_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListMuteConfigsRequest(**{"parent": "folders/sample1/locations/sample2/muteConfigs"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListMuteConfigsResponse() - client.list_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_list_mute_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListMuteConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_mute_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_mute_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_configs( - securitycenter_service.ListMuteConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_mute_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListMuteConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListMuteConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_mute_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_mute_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_mute_configs( - securitycenter_service.ListMuteConfigsRequest(), - parent='parent_value', - ) - - -def test_list_mute_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.list_mute_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, mute_config.MuteConfig) - for i in results) -def test_list_mute_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_mute_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_mute_configs_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_mute_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, mute_config.MuteConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_mute_configs_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_mute_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - 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_mute_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", [ - securitycenter_service.ListNotificationConfigsRequest, - dict, -]) -def test_list_notification_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListNotificationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_notification_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListNotificationConfigsRequest( - 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_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_notification_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap 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_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_notification_configs] = mock_rpc - request = {} - client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_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_notification_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - -@pytest.mark.asyncio -async def test_list_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_notification_configs] = mock_object - - request = {} - await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_notification_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListNotificationConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_from_dict(): - await test_list_notification_configs_async(request_type=dict) - - -def test_list_notification_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - 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_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - client.list_notification_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_notification_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - 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_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - await client.list_notification_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_notification_configs_flattened(): - client = SecurityCenterClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_notification_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_notification_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_notification_configs_flattened_async(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_notification_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_notification_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_notification_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - 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_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, notification_config.NotificationConfig) - for i in results) -def test_list_notification_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_notification_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_notification_configs_async_pager(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_notification_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, notification_config.NotificationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_pages(): - client = SecurityCenterAsyncClient( - 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_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - 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_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", [ - securitycenter_service.ListResourceValueConfigsRequest, - dict, -]) -def test_list_resource_value_configs(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceValueConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_resource_value_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() - - -def test_list_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListResourceValueConfigsRequest( - 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_resource_value_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_resource_value_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListResourceValueConfigsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc - request = {} - client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_resource_value_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_resource_value_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_resource_value_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() - -@pytest.mark.asyncio -async def test_list_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_resource_value_configs] = mock_object - - request = {} - await client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_resource_value_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_resource_value_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListResourceValueConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListResourceValueConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceValueConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_resource_value_configs_async_from_dict(): - await test_list_resource_value_configs_async(request_type=dict) - - -def test_list_resource_value_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListResourceValueConfigsResponse() - client.list_resource_value_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_resource_value_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListResourceValueConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) - await client.list_resource_value_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_resource_value_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListResourceValueConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_resource_value_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_resource_value_configs_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_configs( - securitycenter_service.ListResourceValueConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_resource_value_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListResourceValueConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListResourceValueConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_resource_value_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_resource_value_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_resource_value_configs( - securitycenter_service.ListResourceValueConfigsRequest(), - parent='parent_value', - ) - - -def test_list_resource_value_configs_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_resource_value_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, resource_value_config.ResourceValueConfig) - for i in results) -def test_list_resource_value_configs_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_resource_value_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_resource_value_configs_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_resource_value_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, resource_value_config.ResourceValueConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_resource_value_configs_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_value_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - 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_resource_value_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", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_sources_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListSourcesRequest( - 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_sources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - -@pytest.mark.asyncio -async def test_list_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_sources in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_sources] = mock_object - - request = {} - await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_sources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListSourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_sources_async_from_dict(): - await test_list_sources_async(request_type=dict) - - -def test_list_sources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = securitycenter_service.ListSourcesResponse() - client.list_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_sources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - await client.list_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_sources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_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_sources_flattened_error(): - client = SecurityCenterClient( - credentials=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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_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_sources_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_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, source.Source) - for i in results) -def test_list_sources_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = list(client.list_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_sources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_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, source.Source) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - 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_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", [ - securitycenter_service.ListValuedResourcesRequest, - dict, -]) -def test_list_valued_resources(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListValuedResourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListValuedResourcesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_valued_resources_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_valued_resources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListValuedResourcesRequest() - - -def test_list_valued_resources_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.ListValuedResourcesRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_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_valued_resources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_valued_resources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListValuedResourcesRequest( - parent='parent_value', - filter='filter_value', - page_token='page_token_value', - order_by='order_by_value', - ) - -def test_list_valued_resources_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_valued_resources in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc - request = {} - client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_valued_resources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_valued_resources_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_valued_resources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListValuedResourcesRequest() - -@pytest.mark.asyncio -async def test_list_valued_resources_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_valued_resources in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_valued_resources] = mock_object - - request = {} - await client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.list_valued_resources(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_valued_resources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListValuedResourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.ListValuedResourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListValuedResourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_valued_resources_async_from_dict(): - await test_list_valued_resources_async(request_type=dict) - - -def test_list_valued_resources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListValuedResourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - call.return_value = securitycenter_service.ListValuedResourcesResponse() - client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_valued_resources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListValuedResourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) - await client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_valued_resources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListValuedResourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_valued_resources( - 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_valued_resources_flattened_error(): - client = SecurityCenterClient( - credentials=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_valued_resources( - securitycenter_service.ListValuedResourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_valued_resources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListValuedResourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListValuedResourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_valued_resources( - 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_valued_resources_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_valued_resources( - securitycenter_service.ListValuedResourcesRequest(), - parent='parent_value', - ) - - -def test_list_valued_resources_pager(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_valued_resources(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, valued_resource.ValuedResource) - for i in results) -def test_list_valued_resources_pages(transport_name: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - RuntimeError, - ) - pages = list(client.list_valued_resources(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_valued_resources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_valued_resources(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, valued_resource.ValuedResource) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_valued_resources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_valued_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - 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_valued_resources(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", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_set_finding_state_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_finding_state(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest( - name='name_value', - ) - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - -@pytest.mark.asyncio -async def test_set_finding_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_finding_state in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_finding_state] = mock_object - - request = {} - await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_finding_state(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetFindingStateRequest() - 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.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_set_finding_state_async_from_dict(): - await test_set_finding_state_async(request_type=dict) - - -def test_set_finding_state_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = finding.Finding() - client.set_finding_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_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_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_set_finding_state_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - - -def test_set_finding_state_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - ) - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__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.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].state - mock_val = finding.Finding.State.ACTIVE - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.SetIamPolicyRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_iam_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest( - resource='resource_value', - ) - -def test_set_iam_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_iam_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_iam_policy] = mock_object - - request = {} - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - request = iam_policy_pb2.SetIamPolicyRequest() - 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = SecurityCenterClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetMuteRequest, - dict, -]) -def test_set_mute(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetMuteRequest() - 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.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_set_mute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_mute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetMuteRequest() - - -def test_set_mute_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.SetMuteRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.set_mute(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetMuteRequest( - name='name_value', - ) - -def test_set_mute_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_mute in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc - request = {} - client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_mute(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_set_mute_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_mute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetMuteRequest() - -@pytest.mark.asyncio -async def test_set_mute_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.set_mute in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.set_mute] = mock_object - - request = {} - await client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.set_mute(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_set_mute_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetMuteRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.SetMuteRequest() - 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.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_set_mute_async_from_dict(): - await test_set_mute_async(request_type=dict) - - -def test_set_mute_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetMuteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value = finding.Finding() - client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_mute_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetMuteRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_set_mute_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__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.set_mute( - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].mute - mock_val = finding.Finding.Mute.MUTED - assert arg == mock_val - - -def test_set_mute_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_mute( - securitycenter_service.SetMuteRequest(), - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - -@pytest.mark.asyncio -async def test_set_mute_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_mute), - '__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.set_mute( - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].mute - mock_val = finding.Finding.Mute.MUTED - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_mute_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_mute( - securitycenter_service.SetMuteRequest(), - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = iam_policy_pb2.TestIamPermissionsRequest( - 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.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.test_iam_permissions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( - resource='resource_value', - ) - -def test_test_iam_permissions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # 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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.test_iam_permissions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.test_iam_permissions] = mock_object - - request = {} - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] - request = iam_policy_pb2.TestIamPermissionsRequest() - 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateBigQueryExportRequest, - dict, -]) -def test_update_big_query_export(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - response = client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -def test_update_big_query_export_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() - - -def test_update_big_query_export_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateBigQueryExportRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_big_query_export(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateBigQueryExportRequest( - ) - -def test_update_big_query_export_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc - request = {} - client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_big_query_export(request) - - # Establish that a new wrapper 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_big_query_export_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.update_big_query_export() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() - -@pytest.mark.asyncio -async def test_update_big_query_export_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_big_query_export in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_big_query_export] = mock_object - - request = {} - await client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_big_query_export(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_big_query_export_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateBigQueryExportRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - )) - response = await client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateBigQueryExportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - - -@pytest.mark.asyncio -async def test_update_big_query_export_async_from_dict(): - await test_update_big_query_export_async(request_type=dict) - - -def test_update_big_query_export_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateBigQueryExportRequest() - - request.big_query_export.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value = bigquery_export.BigQueryExport() - client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'big_query_export.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_big_query_export_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateBigQueryExportRequest() - - request.big_query_export.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - await client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'big_query_export.name=name_value', - ) in kw['metadata'] - - -def test_update_big_query_export_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_big_query_export( - big_query_export=bigquery_export.BigQueryExport(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].big_query_export - mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error(): - client = SecurityCenterClient( - credentials=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_big_query_export( - securitycenter_service.UpdateBigQueryExportRequest(), - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_big_query_export_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_big_query_export), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = bigquery_export.BigQueryExport() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(bigquery_export.BigQueryExport()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_big_query_export( - big_query_export=bigquery_export.BigQueryExport(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].big_query_export - mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_big_query_export( - securitycenter_service.UpdateBigQueryExportRequest(), - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateExternalSystemRequest, - dict, -]) -def test_update_external_system(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - ) - response = client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateExternalSystemRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_external_system.ExternalSystem) - assert response.name == 'name_value' - assert response.assignees == ['assignees_value'] - assert response.external_uid == 'external_uid_value' - assert response.status == 'status_value' - assert response.case_uri == 'case_uri_value' - assert response.case_priority == 'case_priority_value' - - -def test_update_external_system_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_external_system() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateExternalSystemRequest() - - -def test_update_external_system_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateExternalSystemRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_external_system(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateExternalSystemRequest( - ) - -def test_update_external_system_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_external_system in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc - request = {} - client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_external_system(request) - - # Establish that a new wrapper 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_external_system_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - )) - response = await client.update_external_system() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateExternalSystemRequest() - -@pytest.mark.asyncio -async def test_update_external_system_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_external_system in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_external_system] = mock_object - - request = {} - await client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_external_system(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_external_system_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateExternalSystemRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - )) - response = await client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateExternalSystemRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_external_system.ExternalSystem) - assert response.name == 'name_value' - assert response.assignees == ['assignees_value'] - assert response.external_uid == 'external_uid_value' - assert response.status == 'status_value' - assert response.case_uri == 'case_uri_value' - assert response.case_priority == 'case_priority_value' - - -@pytest.mark.asyncio -async def test_update_external_system_async_from_dict(): - await test_update_external_system_async(request_type=dict) - - -def test_update_external_system_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateExternalSystemRequest() - - request.external_system.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value = gcs_external_system.ExternalSystem() - client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'external_system.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_external_system_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateExternalSystemRequest() - - request.external_system.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) - await client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'external_system.name=name_value', - ) in kw['metadata'] - - -def test_update_external_system_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_external_system.ExternalSystem() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_external_system( - external_system=gcs_external_system.ExternalSystem(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].external_system - mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error(): - client = SecurityCenterClient( - credentials=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_external_system( - securitycenter_service.UpdateExternalSystemRequest(), - external_system=gcs_external_system.ExternalSystem(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_external_system_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_external_system), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_external_system.ExternalSystem() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_external_system.ExternalSystem()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_external_system( - external_system=gcs_external_system.ExternalSystem(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].external_system - mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_external_system( - securitycenter_service.UpdateExternalSystemRequest(), - external_system=gcs_external_system.ExternalSystem(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - response = client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -def test_update_finding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateFindingRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_finding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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.update_finding] = mock_rpc - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_finding in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_finding] = mock_object - - request = {} - await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_finding(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - )) - response = await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateFindingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - - -@pytest.mark.asyncio -async def test_update_finding_async_from_dict(): - await test_update_finding_async(request_type=dict) - - -def test_update_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_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', - 'finding.name=name_value', - ) in kw['metadata'] - - -def test_update_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_finding( - finding=gcs_finding.Finding(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].finding - mock_val = gcs_finding.Finding(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_finding_flattened_error(): - client = SecurityCenterClient( - credentials=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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_finding( - finding=gcs_finding.Finding(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].finding - mock_val = gcs_finding.Finding(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_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateMuteConfigRequest, - dict, -]) -def test_update_mute_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - ) - response = client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - - -def test_update_mute_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateMuteConfigRequest() - - -def test_update_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateMuteConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_mute_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateMuteConfigRequest( - ) - -def test_update_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - request = {} - client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_mute_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_mute_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.update_mute_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateMuteConfigRequest() - -@pytest.mark.asyncio -async def test_update_mute_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_mute_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_mute_config] = mock_object - - request = {} - await client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_mute_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_mute_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateMuteConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - )) - response = await client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateMuteConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - - -@pytest.mark.asyncio -async def test_update_mute_config_async_from_dict(): - await test_update_mute_config_async(request_type=dict) - -def test_update_mute_config_routing_parameters(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateMuteConfigRequest(**{"mute_config": {"name": "projects/sample1/locations/sample2/muteConfigs/sample3"}}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.update_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateMuteConfigRequest(**{"mute_config": {"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"}}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.update_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateMuteConfigRequest(**{"mute_config": {"name": "folders/sample1/locations/sample2/muteConfigs/sample3"}}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - call.return_value = gcs_mute_config.MuteConfig() - client.update_mute_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 - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_update_mute_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_mute_config( - mute_config=gcs_mute_config.MuteConfig(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].mute_config - mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_mute_config( - securitycenter_service.UpdateMuteConfigRequest(), - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_mute_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_mute_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_mute_config.MuteConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_mute_config.MuteConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_mute_config( - mute_config=gcs_mute_config.MuteConfig(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].mute_config - mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_mute_config( - securitycenter_service.UpdateMuteConfigRequest(), - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateNotificationConfigRequest, - dict, -]) -def test_update_notification_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - response = client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_update_notification_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateNotificationConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_notification_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest( - ) - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_notification_config] = mock_rpc - request = {} - client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_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_notification_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - -@pytest.mark.asyncio -async def test_update_notification_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_notification_config] = mock_object - - request = {} - await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_notification_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateNotificationConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_update_notification_config_async_from_dict(): - await test_update_notification_config_async(request_type=dict) - - -def test_update_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.update_notification_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', - 'notification_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.update_notification_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', - 'notification_config.name=name_value', - ) in kw['metadata'] - - -def test_update_notification_config_flattened(): - client = SecurityCenterClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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].notification_config - mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - 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_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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].notification_config - mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_notification_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateResourceValueConfigRequest, - dict, -]) -def test_update_resource_value_config(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - response = client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -def test_update_resource_value_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() - - -def test_update_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateResourceValueConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_resource_value_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest( - ) - -def test_update_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - request = {} - client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_resource_value_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_resource_value_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.update_resource_value_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() - -@pytest.mark.asyncio -async def test_update_resource_value_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_resource_value_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_resource_value_config] = mock_object - - request = {} - await client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_resource_value_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_resource_value_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateResourceValueConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - )) - response = await client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateResourceValueConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - - -@pytest.mark.asyncio -async def test_update_resource_value_config_async_from_dict(): - await test_update_resource_value_config_async(request_type=dict) - - -def test_update_resource_value_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateResourceValueConfigRequest() - - request.resource_value_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value = gcs_resource_value_config.ResourceValueConfig() - client.update_resource_value_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', - 'resource_value_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_resource_value_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateResourceValueConfigRequest() - - request.resource_value_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) - await client.update_resource_value_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', - 'resource_value_config.name=name_value', - ) in kw['metadata'] - - -def test_update_resource_value_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_resource_value_config.ResourceValueConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_resource_value_config( - resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config - mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error(): - client = SecurityCenterClient( - credentials=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_resource_value_config( - securitycenter_service.UpdateResourceValueConfigRequest(), - resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_resource_value_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_resource_value_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_resource_value_config.ResourceValueConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_resource_value_config.ResourceValueConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_resource_value_config( - resource_value_config=gcs_resource_value_config.ResourceValueConfig(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].resource_value_config - mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_resource_value_config( - securitycenter_service.UpdateResourceValueConfigRequest(), - resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - response = client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_security_marks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - -def test_update_security_marks_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSecurityMarksRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_security_marks(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest( - ) - -def test_update_security_marks_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish that a new wrapper 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_security_marks_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - -@pytest.mark.asyncio -async def test_update_security_marks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_security_marks in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_security_marks] = mock_object - - request = {} - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_security_marks(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSecurityMarksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_security_marks_async_from_dict(): - await test_update_security_marks_async(request_type=dict) - - -def test_update_security_marks_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_marks.name=name_value', - ) in kw['metadata'] - - -def test_update_security_marks_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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].security_marks - mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error(): - client = SecurityCenterClient( - credentials=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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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].security_marks - mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source(request_type, transport: str = 'grpc'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_source_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = securitycenter_service.UpdateSourceRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest( - ) - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should 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_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_source] = mock_rpc - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - -@pytest.mark.asyncio -async def test_update_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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap 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_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_source] = mock_object - - request = {} - await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.update_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = securitycenter_service.UpdateSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_source_async_from_dict(): - await test_update_source_async(request_type=dict) - - -def test_update_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_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', - 'source.name=name_value', - ) in kw['metadata'] - - -def test_update_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_source( - source=gcs_source.Source(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].source - mock_val = gcs_source.Source(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_source_flattened_error(): - client = SecurityCenterClient( - credentials=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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_source( - source=gcs_source.Source(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].source - mock_val = gcs_source.Source(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_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.BatchCreateResourceValueConfigsRequest, - dict, -]) -def test_batch_create_resource_value_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.BatchCreateResourceValueConfigsResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, securitycenter_service.BatchCreateResourceValueConfigsResponse) - -def test_batch_create_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_resource_value_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.batch_create_resource_value_configs] = mock_rpc - - request = {} - client.batch_create_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_resource_value_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_batch_create_resource_value_configs_rest_required_fields(request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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()).batch_create_resource_value_configs._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_create_resource_value_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_create_resource_value_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_resource_value_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_batch_create_resource_value_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_batch_create_resource_value_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb(securitycenter_service.BatchCreateResourceValueConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.BatchCreateResourceValueConfigsResponse.to_json(securitycenter_service.BatchCreateResourceValueConfigsResponse()) - - request = securitycenter_service.BatchCreateResourceValueConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - - client.batch_create_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_create_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_create_resource_value_configs(request) - - -def test_batch_create_resource_value_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(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 = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb(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.batch_create_resource_value_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/v2/{parent=organizations/*}/resourceValueConfigs:batchCreate" % client.transport._host, args[1]) - - -def test_batch_create_resource_value_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_create_resource_value_configs( - securitycenter_service.BatchCreateResourceValueConfigsRequest(), - parent='parent_value', - requests=[securitycenter_service.CreateResourceValueConfigRequest(parent='parent_value')], - ) - - -def test_batch_create_resource_value_configs_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.BulkMuteFindingsRequest, - dict, -]) -def test_bulk_mute_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = operations_pb2.Operation(name='operations/spam') - - # 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 - response = client.bulk_mute_findings(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -def test_bulk_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.bulk_mute_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.bulk_mute_findings] = mock_rpc - - request = {} - client.bulk_mute_findings(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.bulk_mute_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_bulk_mute_findings_rest_required_fields(request_type=securitycenter_service.BulkMuteFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).bulk_mute_findings._get_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()).bulk_mute_findings._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 = SecurityCenterClient( - 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.bulk_mute_findings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_bulk_mute_findings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.bulk_mute_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_bulk_mute_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_bulk_mute_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_bulk_mute_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.BulkMuteFindingsRequest.pb(securitycenter_service.BulkMuteFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = securitycenter_service.BulkMuteFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.bulk_mute_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_bulk_mute_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.BulkMuteFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.bulk_mute_findings(request) - - -def test_bulk_mute_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.bulk_mute_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/v2/{parent=organizations/*}/findings:bulkMute" % client.transport._host, args[1]) - - -def test_bulk_mute_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.bulk_mute_findings( - securitycenter_service.BulkMuteFindingsRequest(), - parent='parent_value', - ) - - -def test_bulk_mute_findings_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateBigQueryExportRequest, - dict, -]) -def test_create_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/locations/sample2'} - request_init["big_query_export"] = {'name': 'name_value', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.CreateBigQueryExportRequest.meta.fields["big_query_export"] - - 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["big_query_export"].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["big_query_export"][field])): - del request_init["big_query_export"][field][i][subfield] - else: - del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - -def test_create_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - - request = {} - client.create_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.CreateBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["big_query_export_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 "bigQueryExportId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "bigQueryExportId" in jsonified_request - assert jsonified_request["bigQueryExportId"] == request_init["big_query_export_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["bigQueryExportId"] = 'big_query_export_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_big_query_export._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("big_query_export_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 "bigQueryExportId" in jsonified_request - assert jsonified_request["bigQueryExportId"] == 'big_query_export_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - expected_params = [ - ( - "bigQueryExportId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(("bigQueryExportId", )) & set(("parent", "bigQueryExport", "bigQueryExportId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_big_query_export") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_big_query_export") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateBigQueryExportRequest.pb(securitycenter_service.CreateBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) - - request = securitycenter_service.CreateBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = bigquery_export.BigQueryExport() - - client.create_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_big_query_export(request) - - -def test_create_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=organizations/*/locations/*}/bigQueryExports" % client.transport._host, args[1]) - - -def test_create_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.CreateBigQueryExportRequest(), - parent='parent_value', - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - big_query_export_id='big_query_export_id_value', - ) - - -def test_create_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateFindingRequest, - dict, -]) -def test_create_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2/locations/sample3'} - request_init["finding"] = {'name': 'name_value', 'canonical_name': 'canonical_name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'mute': 1, 'mute_info': {'static_mute': {'state': 1, 'apply_time': {}}, 'dynamic_mute_records': [{'mute_config': 'mute_config_value', 'match_time': {}}]}, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True, 'exploit_release_date': {}}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.CreateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.create_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.create_finding] = mock_rpc - - request = {} - client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_create_finding_rest_required_fields(request_type=securitycenter_service.CreateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["finding_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 "findingId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "findingId" in jsonified_request - assert jsonified_request["findingId"] == request_init["finding_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["findingId"] = 'finding_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_finding._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request - assert jsonified_request["findingId"] == 'finding_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.create_finding(request) - - expected_params = [ - ( - "findingId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("findingId", )) & set(("parent", "findingId", "finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateFindingRequest.pb(securitycenter_service.CreateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.CreateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.create_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2/locations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_finding(request) - - -def test_create_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2/locations/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - finding=gcs_finding.Finding(name='name_value'), - finding_id='finding_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 = gcs_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.create_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/v2/{parent=organizations/*/sources/*/locations/*}/findings" % client.transport._host, args[1]) - - -def test_create_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding=gcs_finding.Finding(name='name_value'), - finding_id='finding_id_value', - ) - - -def test_create_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateMuteConfigRequest, - dict, -]) -def test_create_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/locations/sample2'} - request_init["mute_config"] = {'name': 'name_value', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'type_': 1, 'expiry_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 = securitycenter_service.CreateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): - del request_init["mute_config"][field][i][subfield] - else: - del request_init["mute_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 = gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - -def test_create_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - - request = {} - client.create_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.CreateMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["mute_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 "muteConfigId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "muteConfigId" in jsonified_request - assert jsonified_request["muteConfigId"] == request_init["mute_config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["muteConfigId"] = 'mute_config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_mute_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("mute_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 "muteConfigId" in jsonified_request - assert jsonified_request["muteConfigId"] == 'mute_config_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - expected_params = [ - ( - "muteConfigId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("muteConfigId", )) & set(("parent", "muteConfig", "muteConfigId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_mute_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_mute_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateMuteConfigRequest.pb(securitycenter_service.CreateMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) - - request = securitycenter_service.CreateMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_mute_config.MuteConfig() - - client.create_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_mute_config(request) - - -def test_create_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_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 = gcs_mute_config.MuteConfig.pb(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_mute_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/v2/{parent=organizations/*/locations/*}/muteConfigs" % client.transport._host, args[1]) - - -def test_create_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.CreateMuteConfigRequest(), - parent='parent_value', - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - mute_config_id='mute_config_id_value', - ) - - -def test_create_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateNotificationConfigRequest, - dict, -]) -def test_create_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/locations/sample2'} - request_init["notification_config"] = {'name': 'name_value', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.CreateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): - del request_init["notification_config"][field][i][subfield] - else: - del request_init["notification_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 = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_create_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.CreateNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["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 "configId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "configId" in jsonified_request - assert jsonified_request["configId"] == request_init["config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["configId"] = 'config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_notification_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("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 "configId" in jsonified_request - assert jsonified_request["configId"] == 'config_id_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ( - "configId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("configId", )) & set(("parent", "configId", "notificationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateNotificationConfigRequest.pb(securitycenter_service.CreateNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) - - request = securitycenter_service.CreateNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_notification_config.NotificationConfig() - - client.create_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_notification_config(request) - - -def test_create_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - config_id='config_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 = gcs_notification_config.NotificationConfig.pb(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_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/v2/{parent=organizations/*/locations/*}/notificationConfigs" % client.transport._host, args[1]) - - -def test_create_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - config_id='config_id_value', - ) - - -def test_create_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.CreateSourceRequest, - dict, -]) -def test_create_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1'} - request_init["source"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_create_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_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_source_rest_required_fields(request_type=securitycenter_service.CreateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_create_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_create_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.CreateSourceRequest.pb(securitycenter_service.CreateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.CreateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.create_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_source(request) - - -def test_create_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v2/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_create_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -def test_create_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteBigQueryExportRequest, - dict, -]) -def test_delete_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_big_query_export] = mock_rpc - - request = {} - client.delete_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.DeleteBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - 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_big_query_export(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_big_query_export") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteBigQueryExportRequest.pb(securitycenter_service.DeleteBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_big_query_export(request) - - -def test_delete_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/locations/sample2/bigQueryExports/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_big_query_export(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=organizations/*/locations/*/bigQueryExports/*}" % client.transport._host, args[1]) - - -def test_delete_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.DeleteBigQueryExportRequest(), - name='name_value', - ) - - -def test_delete_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteMuteConfigRequest, - dict, -]) -def test_delete_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/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 = 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - - request = {} - client.delete_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.DeleteMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( - 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_mute_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_mute_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteMuteConfigRequest.pb(securitycenter_service.DeleteMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_mute_config(request) - - -def test_delete_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/muteConfigs/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_mute_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/v2/{name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.DeleteMuteConfigRequest(), - name='name_value', - ) - - -def test_delete_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteNotificationConfigRequest, - dict, -]) -def test_delete_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = 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_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.DeleteNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_notification_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteNotificationConfigRequest.pb(securitycenter_service.DeleteNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_notification_config(request) - - -def test_delete_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/locations/sample2/notificationConfigs/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_notification_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/v2/{name=organizations/*/locations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -def test_delete_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.DeleteResourceValueConfigRequest, - dict, -]) -def test_delete_resource_value_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = 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_resource_value_config(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - - request = {} - client.delete_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.DeleteResourceValueConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( - 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_resource_value_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_resource_value_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_resource_value_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_resource_value_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_delete_resource_value_config") as pre: - pre.assert_not_called() - pb_message = securitycenter_service.DeleteResourceValueConfigRequest.pb(securitycenter_service.DeleteResourceValueConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = securitycenter_service.DeleteResourceValueConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.DeleteResourceValueConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_resource_value_config(request) - - -def test_delete_resource_value_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/resourceValueConfigs/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_resource_value_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/v2/{name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_resource_value_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_config( - securitycenter_service.DeleteResourceValueConfigRequest(), - name='name_value', - ) - - -def test_delete_resource_value_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetBigQueryExportRequest, - dict, -]) -def test_get_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - -def test_get_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_big_query_export] = mock_rpc - - request = {} - client.get_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.GetBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_big_query_export._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_big_query_export") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_big_query_export") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetBigQueryExportRequest.pb(securitycenter_service.GetBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) - - request = securitycenter_service.GetBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = bigquery_export.BigQueryExport() - - client.get_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_big_query_export(request) - - -def test_get_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=organizations/*/locations/*/bigQueryExports/*}" % client.transport._host, args[1]) - - -def test_get_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.GetBigQueryExportRequest(), - name='name_value', - ) - - -def test_get_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSimulationRequest, - dict, -]) -def test_get_simulation_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation( - name='name_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = simulation.Simulation.pb(return_value) - 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_simulation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, simulation.Simulation) - assert response.name == 'name_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - -def test_get_simulation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_simulation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_simulation] = mock_rpc - - request = {} - client.get_simulation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_simulation(request) - - # Establish 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_simulation_rest_required_fields(request_type=securitycenter_service.GetSimulationRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_simulation._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_simulation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = simulation.Simulation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = simulation.Simulation.pb(return_value) - 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_simulation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_simulation_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_simulation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_simulation_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_simulation") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_simulation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSimulationRequest.pb(securitycenter_service.GetSimulationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = simulation.Simulation.to_json(simulation.Simulation()) - - request = securitycenter_service.GetSimulationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = simulation.Simulation() - - client.get_simulation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_simulation_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSimulationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_simulation(request) - - -def test_get_simulation_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = simulation.Simulation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/simulations/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 = simulation.Simulation.pb(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_simulation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=organizations/*/simulations/*}" % client.transport._host, args[1]) - - -def test_get_simulation_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_simulation( - securitycenter_service.GetSimulationRequest(), - name='name_value', - ) - - -def test_get_simulation_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetValuedResourceRequest, - dict, -]) -def test_get_valued_resource_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource( - name='name_value', - resource='resource_value', - resource_type='resource_type_value', - display_name='display_name_value', - resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, - exposed_score=0.1395, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = valued_resource.ValuedResource.pb(return_value) - 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_valued_resource(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, valued_resource.ValuedResource) - assert response.name == 'name_value' - assert response.resource == 'resource_value' - assert response.resource_type == 'resource_type_value' - assert response.display_name == 'display_name_value' - assert response.resource_value == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW - assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) - -def test_get_valued_resource_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_valued_resource in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_valued_resource] = mock_rpc - - request = {} - client.get_valued_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_valued_resource(request) - - # Establish 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_valued_resource_rest_required_fields(request_type=securitycenter_service.GetValuedResourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_valued_resource._get_unset_required_fields(jsonified_request) - jsonified_request.update(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_valued_resource._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = valued_resource.ValuedResource() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = valued_resource.ValuedResource.pb(return_value) - 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_valued_resource(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_valued_resource_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_valued_resource._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_valued_resource_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_valued_resource") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_valued_resource") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetValuedResourceRequest.pb(securitycenter_service.GetValuedResourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = valued_resource.ValuedResource.to_json(valued_resource.ValuedResource()) - - request = securitycenter_service.GetValuedResourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = valued_resource.ValuedResource() - - client.get_valued_resource(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_valued_resource_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetValuedResourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_valued_resource(request) - - -def test_get_valued_resource_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = valued_resource.ValuedResource() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource.pb(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_valued_resource(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=organizations/*/simulations/*/valuedResources/*}" % client.transport._host, args[1]) - - -def test_get_valued_resource_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_valued_resource( - securitycenter_service.GetValuedResourceRequest(), - name='name_value', - ) - - -def test_get_valued_resource_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.get_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_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_iam_policy] = mock_rpc - - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_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_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_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_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.get_iam_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/v2/{resource=organizations/*/sources/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetMuteConfigRequest, - dict, -]) -def test_get_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=mute_config.MuteConfig.MuteConfigType.STATIC, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC - -def test_get_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_mute_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_mute_config] = mock_rpc - - request = {} - client.get_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.GetMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = mute_config.MuteConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_mute_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_mute_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetMuteConfigRequest.pb(securitycenter_service.GetMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = mute_config.MuteConfig.to_json(mute_config.MuteConfig()) - - request = securitycenter_service.GetMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = mute_config.MuteConfig() - - client.get_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/muteConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_mute_config(request) - - -def test_get_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = mute_config.MuteConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/muteConfigs/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 = mute_config.MuteConfig.pb(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_mute_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/v2/{name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) - - -def test_get_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.GetMuteConfigRequest(), - name='name_value', - ) - - -def test_get_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetNotificationConfigRequest, - dict, -]) -def test_get_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_get_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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_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_notification_config] = mock_rpc - - request = {} - client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.GetNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetNotificationConfigRequest.pb(securitycenter_service.GetNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = notification_config.NotificationConfig.to_json(notification_config.NotificationConfig()) - - request = securitycenter_service.GetNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = notification_config.NotificationConfig() - - client.get_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_notification_config(request) - - -def test_get_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = notification_config.NotificationConfig.pb(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_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/v2/{name=organizations/*/locations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_get_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -def test_get_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetResourceValueConfigRequest, - dict, -]) -def test_get_resource_value_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - -def test_get_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_resource_value_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_resource_value_config] = mock_rpc - - request = {} - client.get_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.GetResourceValueConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resource_value_config.ResourceValueConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_resource_value_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_resource_value_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_resource_value_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_resource_value_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_resource_value_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetResourceValueConfigRequest.pb(securitycenter_service.GetResourceValueConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resource_value_config.ResourceValueConfig.to_json(resource_value_config.ResourceValueConfig()) - - request = securitycenter_service.GetResourceValueConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resource_value_config.ResourceValueConfig() - - client.get_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetResourceValueConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/resourceValueConfigs/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_resource_value_config(request) - - -def test_get_resource_value_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resource_value_config.ResourceValueConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig.pb(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_resource_value_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/v2/{name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) - - -def test_get_resource_value_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_config( - securitycenter_service.GetResourceValueConfigRequest(), - name='name_value', - ) - - -def test_get_resource_value_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GetSourceRequest, - dict, -]) -def test_get_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/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 = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_get_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_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_source] = mock_rpc - - request = {} - client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_source_rest_required_fields(request_type=securitycenter_service.GetSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_get_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_get_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GetSourceRequest.pb(securitycenter_service.GetSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = source.Source.to_json(source.Source()) - - request = securitycenter_service.GetSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = source.Source() - - client.get_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_source(request) - - -def test_get_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/sources/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 = source.Source.pb(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_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/v2/{name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_get_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -def test_get_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.GroupFindingsRequest, - dict, -]) -def test_group_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.group_findings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_group_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.group_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.group_findings] = mock_rpc - - request = {} - client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.group_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_group_findings_rest_required_fields(request_type=securitycenter_service.GroupFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["group_by"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["groupBy"] = 'group_by_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).group_findings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "groupBy" in jsonified_request - assert jsonified_request["groupBy"] == 'group_by_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to 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 = securitycenter_service.GroupFindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.group_findings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_group_findings_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.group_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "groupBy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_group_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_group_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_group_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.GroupFindingsRequest.pb(securitycenter_service.GroupFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.GroupFindingsResponse.to_json(securitycenter_service.GroupFindingsResponse()) - - request = securitycenter_service.GroupFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.GroupFindingsResponse() - - client.group_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_group_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.group_findings(request) - - -def test_group_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.GroupFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - group_by='group_by_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_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/v2/{parent=organizations/*/sources/*}/findings:group" % client.transport._host, args[1]) - - -def test_group_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.GroupFindingsResponse.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': 'organizations/sample1/sources/sample2'} - - pager = client.group_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - - pages = list(client.group_findings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListAttackPathsRequest, - dict, -]) -def test_list_attack_paths_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) - 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_attack_paths(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAttackPathsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_attack_paths_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_attack_paths in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_attack_paths] = mock_rpc - - request = {} - client.list_attack_paths(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_attack_paths(request) - - # Establish 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_attack_paths_rest_required_fields(request_type=securitycenter_service.ListAttackPathsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_attack_paths._get_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_attack_paths._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAttackPathsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListAttackPathsResponse.pb(return_value) - 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_attack_paths(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_attack_paths_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_attack_paths._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_attack_paths_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_attack_paths") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_attack_paths") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListAttackPathsRequest.pb(securitycenter_service.ListAttackPathsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListAttackPathsResponse.to_json(securitycenter_service.ListAttackPathsResponse()) - - request = securitycenter_service.ListAttackPathsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListAttackPathsResponse() - - client.list_attack_paths(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_attack_paths_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListAttackPathsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_attack_paths(request) - - -def test_list_attack_paths_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListAttackPathsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse.pb(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_attack_paths(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=organizations/*/simulations/*}/attackPaths" % client.transport._host, args[1]) - - -def test_list_attack_paths_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_attack_paths( - securitycenter_service.ListAttackPathsRequest(), - parent='parent_value', - ) - - -def test_list_attack_paths_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[], - next_page_token='def', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAttackPathsResponse( - attack_paths=[ - attack_path.AttackPath(), - attack_path.AttackPath(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListAttackPathsResponse.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': 'organizations/sample1/simulations/sample2'} - - pager = client.list_attack_paths(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, attack_path.AttackPath) - for i in results) - - pages = list(client.list_attack_paths(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListBigQueryExportsRequest, - dict, -]) -def test_list_big_query_exports_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) - 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_big_query_exports(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryExportsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_big_query_exports_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_big_query_exports in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_big_query_exports] = mock_rpc - - request = {} - client.list_big_query_exports(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_big_query_exports(request) - - # Establish 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_big_query_exports_rest_required_fields(request_type=securitycenter_service.ListBigQueryExportsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_big_query_exports._get_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_big_query_exports._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListBigQueryExportsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListBigQueryExportsResponse.pb(return_value) - 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_big_query_exports(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_big_query_exports_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_big_query_exports._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_big_query_exports_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_big_query_exports") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_big_query_exports") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListBigQueryExportsRequest.pb(securitycenter_service.ListBigQueryExportsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListBigQueryExportsResponse.to_json(securitycenter_service.ListBigQueryExportsResponse()) - - request = securitycenter_service.ListBigQueryExportsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListBigQueryExportsResponse() - - client.list_big_query_exports(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_big_query_exports_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListBigQueryExportsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_big_query_exports(request) - - -def test_list_big_query_exports_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListBigQueryExportsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListBigQueryExportsResponse.pb(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_big_query_exports(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=organizations/*/locations/*}/bigQueryExports" % client.transport._host, args[1]) - - -def test_list_big_query_exports_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_exports( - securitycenter_service.ListBigQueryExportsRequest(), - parent='parent_value', - ) - - -def test_list_big_query_exports_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - next_page_token='abc', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[], - next_page_token='def', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListBigQueryExportsResponse( - big_query_exports=[ - bigquery_export.BigQueryExport(), - bigquery_export.BigQueryExport(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListBigQueryExportsResponse.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': 'organizations/sample1/locations/sample2'} - - pager = client.list_big_query_exports(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, bigquery_export.BigQueryExport) - for i in results) - - pages = list(client.list_big_query_exports(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListFindingsRequest, - dict, -]) -def test_list_findings_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.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' - assert response.total_size == 1086 - -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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=securitycenter_service.ListFindingsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_findings._get_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_findings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("field_mask", "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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.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 = securitycenter_service.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 = [ - ('$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.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_findings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("fieldMask", "filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_findings_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_findings") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_findings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListFindingsRequest.pb(securitycenter_service.ListFindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListFindingsResponse.to_json(securitycenter_service.ListFindingsResponse()) - - request = securitycenter_service.ListFindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListFindingsResponse() - - client.list_findings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_findings_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_findings(request) - - -def test_list_findings_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListFindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/sources/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 = securitycenter_service.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/v2/{parent=organizations/*/sources/*}/findings" % client.transport._host, args[1]) - - -def test_list_findings_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - - -def test_list_findings_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.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': 'organizations/sample1/sources/sample2'} - - pager = client.list_findings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) - 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 - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListMuteConfigsRequest, - dict, -]) -def test_list_mute_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) - 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_mute_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMuteConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_mute_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_mute_configs] = mock_rpc - - request = {} - client.list_mute_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_mute_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_mute_configs_rest_required_fields(request_type=securitycenter_service.ListMuteConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_mute_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_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListMuteConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListMuteConfigsResponse.pb(return_value) - 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_mute_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_mute_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_mute_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_mute_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_mute_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_mute_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListMuteConfigsRequest.pb(securitycenter_service.ListMuteConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListMuteConfigsResponse.to_json(securitycenter_service.ListMuteConfigsResponse()) - - request = securitycenter_service.ListMuteConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListMuteConfigsResponse() - - client.list_mute_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_mute_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListMuteConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_mute_configs(request) - - -def test_list_mute_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListMuteConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListMuteConfigsResponse.pb(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_mute_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/v2/{parent=organizations/*}/muteConfigs" % client.transport._host, args[1]) - - -def test_list_mute_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_configs( - securitycenter_service.ListMuteConfigsRequest(), - parent='parent_value', - ) - - -def test_list_mute_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[], - next_page_token='def', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListMuteConfigsResponse( - mute_configs=[ - mute_config.MuteConfig(), - mute_config.MuteConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListMuteConfigsResponse.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': 'organizations/sample1'} - - pager = client.list_mute_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, mute_config.MuteConfig) - for i in results) - - pages = list(client.list_mute_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListNotificationConfigsRequest, - dict, -]) -def test_list_notification_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) - 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_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap 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_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_notification_configs] = mock_rpc - - request = {} - client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_notification_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_notification_configs_rest_required_fields(request_type=securitycenter_service.ListNotificationConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListNotificationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListNotificationConfigsResponse.pb(return_value) - 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_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_notification_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_notification_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_notification_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_notification_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_notification_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListNotificationConfigsRequest.pb(securitycenter_service.ListNotificationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListNotificationConfigsResponse.to_json(securitycenter_service.ListNotificationConfigsResponse()) - - request = securitycenter_service.ListNotificationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListNotificationConfigsResponse() - - client.list_notification_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_notification_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_notification_configs(request) - - -def test_list_notification_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListNotificationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListNotificationConfigsResponse.pb(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_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/v2/{parent=organizations/*/locations/*}/notificationConfigs" % client.transport._host, args[1]) - - -def test_list_notification_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListNotificationConfigsResponse.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': 'organizations/sample1/locations/sample2'} - - pager = client.list_notification_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, notification_config.NotificationConfig) - for i in results) - - pages = list(client.list_notification_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListResourceValueConfigsRequest, - dict, -]) -def test_list_resource_value_configs_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceValueConfigsPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_resource_value_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_resource_value_configs] = mock_rpc - - request = {} - client.list_resource_value_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_resource_value_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_resource_value_configs_rest_required_fields(request_type=securitycenter_service.ListResourceValueConfigsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_resource_value_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_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListResourceValueConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListResourceValueConfigsResponse.pb(return_value) - 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_resource_value_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_resource_value_configs_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_resource_value_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_resource_value_configs_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_resource_value_configs") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_resource_value_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListResourceValueConfigsRequest.pb(securitycenter_service.ListResourceValueConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListResourceValueConfigsResponse.to_json(securitycenter_service.ListResourceValueConfigsResponse()) - - request = securitycenter_service.ListResourceValueConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListResourceValueConfigsResponse() - - client.list_resource_value_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_resource_value_configs_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListResourceValueConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_resource_value_configs(request) - - -def test_list_resource_value_configs_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListResourceValueConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListResourceValueConfigsResponse.pb(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_resource_value_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/v2/{parent=organizations/*}/resourceValueConfigs" % client.transport._host, args[1]) - - -def test_list_resource_value_configs_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_configs( - securitycenter_service.ListResourceValueConfigsRequest(), - parent='parent_value', - ) - - -def test_list_resource_value_configs_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[], - next_page_token='def', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListResourceValueConfigsResponse( - resource_value_configs=[ - resource_value_config.ResourceValueConfig(), - resource_value_config.ResourceValueConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListResourceValueConfigsResponse.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': 'organizations/sample1'} - - pager = client.list_resource_value_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resource_value_config.ResourceValueConfig) - for i in results) - - pages = list(client.list_resource_value_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListSourcesRequest, - dict, -]) -def test_list_sources_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - -def test_list_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_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_sources] = mock_rpc - - request = {} - client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_sources_rest_required_fields(request_type=securitycenter_service.ListSourcesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListSourcesResponse.pb(return_value) - 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_sources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_sources_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_sources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_sources_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_sources") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_sources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListSourcesRequest.pb(securitycenter_service.ListSourcesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListSourcesResponse.to_json(securitycenter_service.ListSourcesResponse()) - - request = securitycenter_service.ListSourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListSourcesResponse() - - client.list_sources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_sources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_sources(request) - - -def test_list_sources_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListSourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/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 = securitycenter_service.ListSourcesResponse.pb(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_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/v2/{parent=organizations/*}/sources" % client.transport._host, args[1]) - - -def test_list_sources_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListSourcesResponse.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': 'organizations/sample1'} - - pager = client.list_sources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, source.Source) - for i in results) - - pages = list(client.list_sources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.ListValuedResourcesRequest, - dict, -]) -def test_list_valued_resources_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) - 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_valued_resources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListValuedResourcesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_list_valued_resources_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_valued_resources in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_valued_resources] = mock_rpc - - request = {} - client.list_valued_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_valued_resources(request) - - # Establish 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_valued_resources_rest_required_fields(request_type=securitycenter_service.ListValuedResourcesRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_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_valued_resources._get_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_valued_resources._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListValuedResourcesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = securitycenter_service.ListValuedResourcesResponse.pb(return_value) - 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_valued_resources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_valued_resources_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_valued_resources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_valued_resources_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_list_valued_resources") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_list_valued_resources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.ListValuedResourcesRequest.pb(securitycenter_service.ListValuedResourcesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = securitycenter_service.ListValuedResourcesResponse.to_json(securitycenter_service.ListValuedResourcesResponse()) - - request = securitycenter_service.ListValuedResourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = securitycenter_service.ListValuedResourcesResponse() - - client.list_valued_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_valued_resources_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.ListValuedResourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/simulations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_valued_resources(request) - - -def test_list_valued_resources_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = securitycenter_service.ListValuedResourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse.pb(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_valued_resources(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{parent=organizations/*/simulations/*}/valuedResources" % client.transport._host, args[1]) - - -def test_list_valued_resources_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_valued_resources( - securitycenter_service.ListValuedResourcesRequest(), - parent='parent_value', - ) - - -def test_list_valued_resources_rest_pager(transport: str = 'rest'): - client = SecurityCenterClient( - 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 = ( - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - next_page_token='abc', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[], - next_page_token='def', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListValuedResourcesResponse( - valued_resources=[ - valued_resource.ValuedResource(), - valued_resource.ValuedResource(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(securitycenter_service.ListValuedResourcesResponse.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': 'organizations/sample1/simulations/sample2'} - - pager = client.list_valued_resources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, valued_resource.ValuedResource) - for i in results) - - pages = list(client.list_valued_resources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetFindingStateRequest, - dict, -]) -def test_set_finding_state_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # 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 - response = client.set_finding_state(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_set_finding_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_finding_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.set_finding_state] = mock_rpc - - request = {} - client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_finding_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_set_finding_state_rest_required_fields(request_type=securitycenter_service.SetFindingStateRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_finding_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()).set_finding_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 = SecurityCenterClient( - 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': "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 = 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.set_finding_state(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_finding_state_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_finding_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "state", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_finding_state_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_finding_state") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_finding_state") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SetFindingStateRequest.pb(securitycenter_service.SetFindingStateRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = finding.Finding.to_json(finding.Finding()) - - request = securitycenter_service.SetFindingStateRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.set_finding_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_finding_state_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_finding_state(request) - - -def test_set_finding_state_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - state=finding.Finding.State.ACTIVE, - ) - mock_args.update(sample_request) - - # 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.set_finding_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/v2/{name=organizations/*/sources/*/findings/*}:setState" % client.transport._host, args[1]) - - -def test_set_finding_state_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - ) - - -def test_set_finding_state_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # 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 - response = client.set_iam_policy(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_iam_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.set_iam_policy] = mock_rpc - - request = {} - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_iam_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_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_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.set_iam_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/v2/{resource=organizations/*/sources/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.SetMuteRequest, - dict, -]) -def test_set_mute_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - mute=finding.Finding.Mute.MUTED, - finding_class=finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # 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 - response = client.set_mute(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.mute == finding.Finding.Mute.MUTED - assert response.finding_class == finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_set_mute_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.set_mute in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.set_mute] = mock_rpc - - request = {} - client.set_mute(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.set_mute(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_set_mute_rest_required_fields(request_type=securitycenter_service.SetMuteRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_mute._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SecurityCenterClient( - 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': "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 = 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.set_mute(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_mute_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_mute._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "mute", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_mute_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_set_mute") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_set_mute") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.SetMuteRequest.pb(securitycenter_service.SetMuteRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = finding.Finding.to_json(finding.Finding()) - - request = securitycenter_service.SetMuteRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = finding.Finding() - - client.set_mute(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_mute_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.SetMuteRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_mute(request) - - -def test_set_mute_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'organizations/sample1/sources/sample2/findings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - mock_args.update(sample_request) - - # 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.set_mute(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{name=organizations/*/sources/*/findings/*}:setMute" % client.transport._host, args[1]) - - -def test_set_mute_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_mute( - securitycenter_service.SetMuteRequest(), - name='name_value', - mute=finding.Finding.Mute.MUTED, - ) - - -def test_set_mute_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # 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 - response = client.test_iam_permissions(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_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.test_iam_permissions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.test_iam_permissions] = mock_rpc - - request = {} - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.test_iam_permissions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.SecurityCenterRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/sample1/sources/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1/sources/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_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.test_iam_permissions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{resource=organizations/*/sources/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateBigQueryExportRequest, - dict, -]) -def test_update_big_query_export_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'big_query_export': {'name': 'organizations/sample1/locations/sample2/bigQueryExports/sample3'}} - request_init["big_query_export"] = {'name': 'organizations/sample1/locations/sample2/bigQueryExports/sample3', 'description': 'description_value', 'filter': 'filter_value', 'dataset': 'dataset_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'principal': 'principal_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 = securitycenter_service.UpdateBigQueryExportRequest.meta.fields["big_query_export"] - - 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["big_query_export"].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["big_query_export"][field])): - del request_init["big_query_export"][field][i][subfield] - else: - del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( - name='name_value', - description='description_value', - filter='filter_value', - dataset='dataset_value', - most_recent_editor='most_recent_editor_value', - principal='principal_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, bigquery_export.BigQueryExport) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.dataset == 'dataset_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.principal == 'principal_value' - -def test_update_big_query_export_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_big_query_export in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_big_query_export] = mock_rpc - - request = {} - client.update_big_query_export(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_big_query_export(request) - - # Establish 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_big_query_export_rest_required_fields(request_type=securitycenter_service.UpdateBigQueryExportRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_big_query_export._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_big_query_export._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = bigquery_export.BigQueryExport.pb(return_value) - 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_big_query_export(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_big_query_export_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_big_query_export._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("bigQueryExport", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_big_query_export_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_big_query_export") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_big_query_export") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateBigQueryExportRequest.pb(securitycenter_service.UpdateBigQueryExportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = bigquery_export.BigQueryExport.to_json(bigquery_export.BigQueryExport()) - - request = securitycenter_service.UpdateBigQueryExportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = bigquery_export.BigQueryExport() - - client.update_big_query_export(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_big_query_export_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateBigQueryExportRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'big_query_export': {'name': 'organizations/sample1/locations/sample2/bigQueryExports/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_big_query_export(request) - - -def test_update_big_query_export_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = bigquery_export.BigQueryExport() - - # get arguments that satisfy an http rule for this method - sample_request = {'big_query_export': {'name': 'organizations/sample1/locations/sample2/bigQueryExports/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - big_query_export=bigquery_export.BigQueryExport(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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{big_query_export.name=organizations/*/locations/*/bigQueryExports/*}" % client.transport._host, args[1]) - - -def test_update_big_query_export_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_big_query_export( - securitycenter_service.UpdateBigQueryExportRequest(), - big_query_export=bigquery_export.BigQueryExport(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_big_query_export_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateExternalSystemRequest, - dict, -]) -def test_update_external_system_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} - request_init["external_system"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4', 'assignees': ['assignees_value1', 'assignees_value2'], 'external_uid': 'external_uid_value', 'status': 'status_value', 'external_system_update_time': {'seconds': 751, 'nanos': 543}, 'case_uri': 'case_uri_value', 'case_priority': 'case_priority_value', 'case_sla': {}, 'case_create_time': {}, 'case_close_time': {}, 'ticket_info': {'id': 'id_value', 'assignee': 'assignee_value', 'description': 'description_value', 'uri': 'uri_value', 'status': 'status_value', 'update_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 = securitycenter_service.UpdateExternalSystemRequest.meta.fields["external_system"] - - 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["external_system"].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["external_system"][field])): - del request_init["external_system"][field][i][subfield] - else: - del request_init["external_system"][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 = gcs_external_system.ExternalSystem( - name='name_value', - assignees=['assignees_value'], - external_uid='external_uid_value', - status='status_value', - case_uri='case_uri_value', - case_priority='case_priority_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_external_system.ExternalSystem.pb(return_value) - 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_external_system(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_external_system.ExternalSystem) - assert response.name == 'name_value' - assert response.assignees == ['assignees_value'] - assert response.external_uid == 'external_uid_value' - assert response.status == 'status_value' - assert response.case_uri == 'case_uri_value' - assert response.case_priority == 'case_priority_value' - -def test_update_external_system_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_external_system in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_external_system] = mock_rpc - - request = {} - client.update_external_system(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_external_system(request) - - # Establish 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_external_system_rest_required_fields(request_type=securitycenter_service.UpdateExternalSystemRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_external_system._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_external_system._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_external_system.ExternalSystem() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_external_system.ExternalSystem.pb(return_value) - 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_external_system(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_external_system_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_external_system._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("externalSystem", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_external_system_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_external_system") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_external_system") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateExternalSystemRequest.pb(securitycenter_service.UpdateExternalSystemRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_external_system.ExternalSystem.to_json(gcs_external_system.ExternalSystem()) - - request = securitycenter_service.UpdateExternalSystemRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_external_system.ExternalSystem() - - client.update_external_system(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_external_system_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateExternalSystemRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_external_system(request) - - -def test_update_external_system_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_external_system.ExternalSystem() - - # get arguments that satisfy an http rule for this method - sample_request = {'external_system': {'name': 'organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - external_system=gcs_external_system.ExternalSystem(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 = gcs_external_system.ExternalSystem.pb(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_external_system(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}" % client.transport._host, args[1]) - - -def test_update_external_system_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_external_system( - securitycenter_service.UpdateExternalSystemRequest(), - external_system=gcs_external_system.ExternalSystem(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_external_system_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateFindingRequest, - dict, -]) -def test_update_finding_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - request_init["finding"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3', 'canonical_name': 'canonical_name_value', 'parent': 'parent_value', 'resource_name': 'resource_name_value', 'state': 1, 'category': 'category_value', 'external_uri': 'external_uri_value', 'source_properties': {}, 'security_marks': {'name': 'name_value', 'marks': {}, 'canonical_name': 'canonical_name_value'}, 'event_time': {'seconds': 751, 'nanos': 543}, 'create_time': {}, 'severity': 1, 'mute': 1, 'mute_info': {'static_mute': {'state': 1, 'apply_time': {}}, 'dynamic_mute_records': [{'mute_config': 'mute_config_value', 'match_time': {}}]}, 'finding_class': 1, 'indicator': {'ip_addresses': ['ip_addresses_value1', 'ip_addresses_value2'], 'domains': ['domains_value1', 'domains_value2'], 'signatures': [{'memory_hash_signature': {'binary_family': 'binary_family_value', 'detections': [{'binary': 'binary_value', 'percent_pages_matched': 0.2197}]}, 'yara_rule_signature': {'yara_rule': 'yara_rule_value'}, 'signature_type': 1}], 'uris': ['uris_value1', 'uris_value2']}, 'vulnerability': {'cve': {'id': 'id_value', 'references': [{'source': 'source_value', 'uri': 'uri_value'}], 'cvssv3': {'base_score': 0.1046, 'attack_vector': 1, 'attack_complexity': 1, 'privileges_required': 1, 'user_interaction': 1, 'scope': 1, 'confidentiality_impact': 1, 'integrity_impact': 1, 'availability_impact': 1}, 'upstream_fix_available': True, 'impact': 1, 'exploitation_activity': 1, 'observed_in_the_wild': True, 'zero_day': True, 'exploit_release_date': {}}, 'offending_package': {'package_name': 'package_name_value', 'cpe_uri': 'cpe_uri_value', 'package_type': 'package_type_value', 'package_version': 'package_version_value'}, 'fixed_package': {}, 'security_bulletin': {'bulletin_id': 'bulletin_id_value', 'submission_time': {}, 'suggested_upgrade_version': 'suggested_upgrade_version_value'}}, 'mute_update_time': {}, 'external_systems': {}, 'mitre_attack': {'primary_tactic': 1, 'primary_techniques': [49], 'additional_tactics': [1], 'additional_techniques': [49], 'version': 'version_value'}, 'access': {'principal_email': 'principal_email_value', 'caller_ip': 'caller_ip_value', 'caller_ip_geo': {'region_code': 'region_code_value'}, 'user_agent_family': 'user_agent_family_value', 'user_agent': 'user_agent_value', 'service_name': 'service_name_value', 'method_name': 'method_name_value', 'principal_subject': 'principal_subject_value', 'service_account_key_name': 'service_account_key_name_value', 'service_account_delegation_info': [{'principal_email': 'principal_email_value', 'principal_subject': 'principal_subject_value'}], 'user_name': 'user_name_value'}, 'connections': [{'destination_ip': 'destination_ip_value', 'destination_port': 1734, 'source_ip': 'source_ip_value', 'source_port': 1205, 'protocol': 1}], 'mute_initiator': 'mute_initiator_value', 'processes': [{'name': 'name_value', 'binary': {'path': 'path_value', 'size': 443, 'sha256': 'sha256_value', 'hashed_size': 1159, 'partially_hashed': True, 'contents': 'contents_value', 'disk_path': {'partition_uuid': 'partition_uuid_value', 'relative_path': 'relative_path_value'}}, 'libraries': {}, 'script': {}, 'args': ['args_value1', 'args_value2'], 'arguments_truncated': True, 'env_variables': [{'name': 'name_value', 'val': 'val_value'}], 'env_variables_truncated': True, 'pid': 317, 'parent_pid': 1062}], 'contacts': {}, 'compliances': [{'standard': 'standard_value', 'version': 'version_value', 'ids': ['ids_value1', 'ids_value2']}], 'parent_display_name': 'parent_display_name_value', 'description': 'description_value', 'exfiltration': {'sources': [{'name': 'name_value', 'components': ['components_value1', 'components_value2']}], 'targets': {}, 'total_exfiltrated_bytes': 2469}, 'iam_bindings': [{'action': 1, 'role': 'role_value', 'member': 'member_value'}], 'next_steps': 'next_steps_value', 'module_name': 'module_name_value', 'containers': [{'name': 'name_value', 'uri': 'uri_value', 'image_id': 'image_id_value', 'labels': [{'name': 'name_value', 'value': 'value_value'}], 'create_time': {}}], 'kubernetes': {'pods': [{'ns': 'ns_value', 'name': 'name_value', 'labels': {}, 'containers': {}}], 'nodes': [{'name': 'name_value'}], 'node_pools': [{'name': 'name_value', 'nodes': {}}], 'roles': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}], 'bindings': [{'ns': 'ns_value', 'name': 'name_value', 'role': {}, 'subjects': [{'kind': 1, 'ns': 'ns_value', 'name': 'name_value'}]}], 'access_reviews': [{'group': 'group_value', 'ns': 'ns_value', 'name': 'name_value', 'resource': 'resource_value', 'subresource': 'subresource_value', 'verb': 'verb_value', 'version': 'version_value'}], 'objects': [{'group': 'group_value', 'kind': 'kind_value', 'ns': 'ns_value', 'name': 'name_value', 'containers': {}}]}, 'database': {'name': 'name_value', 'display_name': 'display_name_value', 'user_name': 'user_name_value', 'query': 'query_value', 'grantees': ['grantees_value1', 'grantees_value2'], 'version': 'version_value'}, 'attack_exposure': {'score': 0.54, 'latest_calculation_time': {}, 'attack_exposure_result': 'attack_exposure_result_value', 'state': 1, 'exposed_high_value_resources_count': 3637, 'exposed_medium_value_resources_count': 3862, 'exposed_low_value_resources_count': 3559}, 'files': {}, 'cloud_dlp_inspection': {'inspect_job': 'inspect_job_value', 'info_type': 'info_type_value', 'info_type_count': 1621, 'full_scan': True}, 'cloud_dlp_data_profile': {'data_profile': 'data_profile_value', 'parent_type': 1}, 'kernel_rootkit': {'name': 'name_value', 'unexpected_code_modification': True, 'unexpected_read_only_data_modification': True, 'unexpected_ftrace_handler': True, 'unexpected_kprobe_handler': True, 'unexpected_kernel_code_pages': True, 'unexpected_system_call_handler': True, 'unexpected_interrupt_handler': True, 'unexpected_processes_in_runqueue': True}, 'org_policies': [{'name': 'name_value'}], 'application': {'base_uri': 'base_uri_value', 'full_uri': 'full_uri_value'}, 'backup_disaster_recovery': {'backup_template': 'backup_template_value', 'policies': ['policies_value1', 'policies_value2'], 'host': 'host_value', 'applications': ['applications_value1', 'applications_value2'], 'storage_pool': 'storage_pool_value', 'policy_options': ['policy_options_value1', 'policy_options_value2'], 'profile': 'profile_value', 'appliance': 'appliance_value', 'backup_type': 'backup_type_value', 'backup_create_time': {}}, 'security_posture': {'name': 'name_value', 'revision_id': 'revision_id_value', 'posture_deployment_resource': 'posture_deployment_resource_value', 'posture_deployment': 'posture_deployment_value', 'changed_policy': 'changed_policy_value', 'policy_set': 'policy_set_value', 'policy': 'policy_value', 'policy_drift_details': [{'field': 'field_value', 'expected_value': 'expected_value_value', 'detected_value': 'detected_value_value'}]}, 'log_entries': [{'cloud_logging_entry': {'insert_id': 'insert_id_value', 'log_id': 'log_id_value', 'resource_container': 'resource_container_value', 'timestamp': {}}}], 'load_balancers': [{'name': 'name_value'}], 'cloud_armor': {'security_policy': {'name': 'name_value', 'type_': 'type__value', 'preview': True}, 'requests': {'ratio': 0.543, 'short_term_allowed': 1934, 'long_term_allowed': 1806, 'long_term_denied': 1679}, 'adaptive_protection': {'confidence': 0.1038}, 'attack': {'volume_pps': 1098, 'volume_bps': 1084, 'classification': 'classification_value'}, 'threat_vector': 'threat_vector_value', 'duration': {'seconds': 751, 'nanos': 543}}, 'notebook': {'name': 'name_value', 'service': 'service_value', 'last_author': 'last_author_value', 'notebook_update_time': {}}, 'toxic_combination': {'attack_exposure_score': 0.2253, 'related_findings': ['related_findings_value1', 'related_findings_value2']}, 'group_memberships': [{'group_type': 1, 'group_id': 'group_id_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 = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] - - 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["finding"].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["finding"][field])): - del request_init["finding"][field][i][subfield] - else: - del request_init["finding"][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 = gcs_finding.Finding( - name='name_value', - canonical_name='canonical_name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - mute=gcs_finding.Finding.Mute.MUTED, - finding_class=gcs_finding.Finding.FindingClass.THREAT, - mute_initiator='mute_initiator_value', - parent_display_name='parent_display_name_value', - description='description_value', - next_steps='next_steps_value', - module_name='module_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_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.update_finding(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.mute == gcs_finding.Finding.Mute.MUTED - assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT - assert response.mute_initiator == 'mute_initiator_value' - assert response.parent_display_name == 'parent_display_name_value' - assert response.description == 'description_value' - assert response.next_steps == 'next_steps_value' - assert response.module_name == 'module_name_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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.update_finding] = mock_rpc - - request = {} - client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_update_finding_rest_required_fields(request_type=securitycenter_service.UpdateFindingRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_finding._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_finding._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_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': "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 = gcs_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.update_finding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_finding_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_finding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("finding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_finding_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_finding") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_finding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateFindingRequest.pb(securitycenter_service.UpdateFindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) - - request = securitycenter_service.UpdateFindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_finding.Finding() - - client.update_finding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_finding_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_finding(request) - - -def test_update_finding_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_finding.Finding() - - # get arguments that satisfy an http rule for this method - sample_request = {'finding': {'name': 'organizations/sample1/sources/sample2/findings/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - finding=gcs_finding.Finding(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 = gcs_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.update_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/v2/{finding.name=organizations/*/sources/*/findings/*}" % client.transport._host, args[1]) - - -def test_update_finding_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_finding_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateMuteConfigRequest, - dict, -]) -def test_update_mute_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} - request_init["mute_config"] = {'name': 'organizations/sample1/muteConfigs/sample2', 'description': 'description_value', 'filter': 'filter_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'most_recent_editor': 'most_recent_editor_value', 'type_': 1, 'expiry_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 = securitycenter_service.UpdateMuteConfigRequest.meta.fields["mute_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["mute_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["mute_config"][field])): - del request_init["mute_config"][field][i][subfield] - else: - del request_init["mute_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 = gcs_mute_config.MuteConfig( - name='name_value', - description='description_value', - filter='filter_value', - most_recent_editor='most_recent_editor_value', - type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_mute_config.MuteConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.most_recent_editor == 'most_recent_editor_value' - assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC - -def test_update_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_mute_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_mute_config] = mock_rpc - - request = {} - client.update_mute_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_mute_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_mute_config_rest_required_fields(request_type=securitycenter_service.UpdateMuteConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_mute_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_mute_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_mute_config.MuteConfig.pb(return_value) - 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_mute_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_mute_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_mute_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("muteConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_mute_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_mute_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_mute_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateMuteConfigRequest.pb(securitycenter_service.UpdateMuteConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_mute_config.MuteConfig.to_json(gcs_mute_config.MuteConfig()) - - request = securitycenter_service.UpdateMuteConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_mute_config.MuteConfig() - - client.update_mute_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_mute_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateMuteConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_mute_config(request) - - -def test_update_mute_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_mute_config.MuteConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'mute_config': {'name': 'organizations/sample1/muteConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - mute_config=gcs_mute_config.MuteConfig(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 = gcs_mute_config.MuteConfig.pb(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_mute_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/v2/{mute_config.name=organizations/*/muteConfigs/*}" % client.transport._host, args[1]) - - -def test_update_mute_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_mute_config( - securitycenter_service.UpdateMuteConfigRequest(), - mute_config=gcs_mute_config.MuteConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_mute_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateNotificationConfigRequest, - dict, -]) -def test_update_notification_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'notification_config': {'name': 'organizations/sample1/locations/sample2/notificationConfigs/sample3'}} - request_init["notification_config"] = {'name': 'organizations/sample1/locations/sample2/notificationConfigs/sample3', 'description': 'description_value', 'pubsub_topic': 'pubsub_topic_value', 'service_account': 'service_account_value', 'streaming_config': {'filter': 'filter_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 = securitycenter_service.UpdateNotificationConfigRequest.meta.fields["notification_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["notification_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["notification_config"][field])): - del request_init["notification_config"][field][i][subfield] - else: - del request_init["notification_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 = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - -def test_update_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_notification_config] = mock_rpc - - request = {} - client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_notification_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_notification_config_rest_required_fields(request_type=securitycenter_service.UpdateNotificationConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_notification_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_notification_config.NotificationConfig.pb(return_value) - 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_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_notification_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_notification_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("notificationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_notification_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_notification_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_notification_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateNotificationConfigRequest.pb(securitycenter_service.UpdateNotificationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_notification_config.NotificationConfig.to_json(gcs_notification_config.NotificationConfig()) - - request = securitycenter_service.UpdateNotificationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_notification_config.NotificationConfig() - - client.update_notification_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_notification_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'notification_config': {'name': 'organizations/sample1/locations/sample2/notificationConfigs/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_notification_config(request) - - -def test_update_notification_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_notification_config.NotificationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'notification_config': {'name': 'organizations/sample1/locations/sample2/notificationConfigs/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - notification_config=gcs_notification_config.NotificationConfig(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 = gcs_notification_config.NotificationConfig.pb(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_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/v2/{notification_config.name=organizations/*/locations/*/notificationConfigs/*}" % client.transport._host, args[1]) - - -def test_update_notification_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_notification_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateResourceValueConfigRequest, - dict, -]) -def test_update_resource_value_config_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} - request_init["resource_value_config"] = {'name': 'organizations/sample1/resourceValueConfigs/sample2', 'resource_value': 1, 'tag_values': ['tag_values_value1', 'tag_values_value2'], 'resource_type': 'resource_type_value', 'scope': 'scope_value', 'resource_labels_selector': {}, 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'cloud_provider': 1, 'sensitive_data_protection_mapping': {'high_sensitivity_mapping': 1, 'medium_sensitivity_mapping': 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 = securitycenter_service.UpdateResourceValueConfigRequest.meta.fields["resource_value_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["resource_value_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["resource_value_config"][field])): - del request_init["resource_value_config"][field][i][subfield] - else: - del request_init["resource_value_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 = gcs_resource_value_config.ResourceValueConfig( - name='name_value', - resource_value=gcs_resource_value_config.ResourceValue.HIGH, - tag_values=['tag_values_value'], - resource_type='resource_type_value', - scope='scope_value', - description='description_value', - cloud_provider=resource.CloudProvider.GOOGLE_CLOUD_PLATFORM, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) - assert response.name == 'name_value' - assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH - assert response.tag_values == ['tag_values_value'] - assert response.resource_type == 'resource_type_value' - assert response.scope == 'scope_value' - assert response.description == 'description_value' - assert response.cloud_provider == resource.CloudProvider.GOOGLE_CLOUD_PLATFORM - -def test_update_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_resource_value_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_resource_value_config] = mock_rpc - - request = {} - client.update_resource_value_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_resource_value_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_resource_value_config_rest_required_fields(request_type=securitycenter_service.UpdateResourceValueConfigRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_resource_value_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_resource_value_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_resource_value_config.ResourceValueConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_resource_value_config.ResourceValueConfig.pb(return_value) - 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_resource_value_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_resource_value_config_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_resource_value_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("resourceValueConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_resource_value_config_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_resource_value_config") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_resource_value_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateResourceValueConfigRequest.pb(securitycenter_service.UpdateResourceValueConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_resource_value_config.ResourceValueConfig.to_json(gcs_resource_value_config.ResourceValueConfig()) - - request = securitycenter_service.UpdateResourceValueConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_resource_value_config.ResourceValueConfig() - - client.update_resource_value_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_resource_value_config_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateResourceValueConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_resource_value_config(request) - - -def test_update_resource_value_config_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_resource_value_config.ResourceValueConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource_value_config': {'name': 'organizations/sample1/resourceValueConfigs/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - resource_value_config=gcs_resource_value_config.ResourceValueConfig(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 = gcs_resource_value_config.ResourceValueConfig.pb(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_resource_value_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/v2/{resource_value_config.name=organizations/*/resourceValueConfigs/*}" % client.transport._host, args[1]) - - -def test_update_resource_value_config_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_resource_value_config( - securitycenter_service.UpdateResourceValueConfigRequest(), - resource_value_config=gcs_resource_value_config.ResourceValueConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_resource_value_config_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSecurityMarksRequest, - dict, -]) -def test_update_security_marks_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks'}} - request_init["security_marks"] = {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks', 'marks': {}, 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields["security_marks"] - - 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["security_marks"].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["security_marks"][field])): - del request_init["security_marks"][field][i][subfield] - else: - del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - -def test_update_security_marks_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_security_marks in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_security_marks] = mock_rpc - - request = {} - client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_security_marks(request) - - # Establish 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_security_marks_rest_required_fields(request_type=securitycenter_service.UpdateSecurityMarksRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_security_marks._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_security_marks._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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_security_marks.SecurityMarks.pb(return_value) - 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_security_marks(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_security_marks_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_security_marks._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("securityMarks", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_security_marks_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_security_marks") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_security_marks") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb(securitycenter_service.UpdateSecurityMarksRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_security_marks.SecurityMarks.to_json(gcs_security_marks.SecurityMarks()) - - request = securitycenter_service.UpdateSecurityMarksRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_security_marks.SecurityMarks() - - client.update_security_marks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_security_marks_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'security_marks': {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_security_marks(request) - - -def test_update_security_marks_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_security_marks.SecurityMarks() - - # get arguments that satisfy an http rule for this method - sample_request = {'security_marks': {'name': 'organizations/sample1/sources/sample2/findings/sample3/securityMarks'}} - - # get truthy value for each flattened field - mock_args = dict( - security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v2/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}" % client.transport._host, args[1]) - - -def test_update_security_marks_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_security_marks_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - securitycenter_service.UpdateSourceRequest, - dict, -]) -def test_update_source_rest(request_type): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request_init["source"] = {'name': 'organizations/sample1/sources/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'canonical_name': 'canonical_name_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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): - del request_init["source"][field][i][subfield] - else: - del request_init["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 = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcs_source.Source.pb(return_value) - 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_source(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - -def test_update_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should 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_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_source] = mock_rpc - - request = {} - client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_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_source_rest_required_fields(request_type=securitycenter_service.UpdateSourceRequest): - transport_class = transports.SecurityCenterRestTransport - - 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_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_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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcs_source.Source.pb(return_value) - 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_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_source_rest_unset_required_fields(): - transport = transports.SecurityCenterRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("source", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_source_rest_interceptors(null_interceptor): - transport = transports.SecurityCenterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SecurityCenterRestInterceptor(), - ) - client = SecurityCenterClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "post_update_source") as post, \ - mock.patch.object(transports.SecurityCenterRestInterceptor, "pre_update_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = securitycenter_service.UpdateSourceRequest.pb(securitycenter_service.UpdateSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) - - request = securitycenter_service.UpdateSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcs_source.Source() - - client.update_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_source_rest_bad_request(transport: str = 'rest', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'source': {'name': 'organizations/sample1/sources/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_source(request) - - -def test_update_source_rest_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcs_source.Source() - - # get arguments that satisfy an http rule for this method - sample_request = {'source': {'name': 'organizations/sample1/sources/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v2/{source.name=organizations/*/sources/*}" % client.transport._host, args[1]) - - -def test_update_source_rest_flattened_error(transport: str = 'rest'): - client = SecurityCenterClient( - credentials=ga_credentials.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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_source_rest_error(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SecurityCenterClient( - 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 = SecurityCenterClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SecurityCenterClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, -]) -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SecurityCenterClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SecurityCenterGrpcTransport, - ) - -def test_security_center_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_security_center_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.securitycenter_v2.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'batch_create_resource_value_configs', - 'bulk_mute_findings', - 'create_big_query_export', - 'create_finding', - 'create_mute_config', - 'create_notification_config', - 'create_source', - 'delete_big_query_export', - 'delete_mute_config', - 'delete_notification_config', - 'delete_resource_value_config', - 'get_big_query_export', - 'get_simulation', - 'get_valued_resource', - 'get_iam_policy', - 'get_mute_config', - 'get_notification_config', - 'get_resource_value_config', - 'get_source', - 'group_findings', - 'list_attack_paths', - 'list_big_query_exports', - 'list_findings', - 'list_mute_configs', - 'list_notification_configs', - 'list_resource_value_configs', - 'list_sources', - 'list_valued_resources', - 'set_finding_state', - 'set_iam_policy', - 'set_mute', - 'test_iam_permissions', - 'update_big_query_export', - 'update_external_system', - 'update_finding', - 'update_mute_config', - 'update_notification_config', - 'update_resource_value_config', - 'update_security_marks', - 'update_source', - '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_security_center_base_transport_with_credentials_file(): - # Instantiate the 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.securitycenter_v2.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - 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_security_center_base_transport_with_adc(): - # Test the default 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.securitycenter_v2.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport() - adc.assert_called_once() - - -def test_security_center_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) - SecurityCenterClient() - 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -def test_security_center_transport_auth_adc(transport_class): - # If 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.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - transports.SecurityCenterRestTransport, - ], -) -def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), - (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_security_center_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host 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( - "securitycenter.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="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_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.SecurityCenterRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_security_center_rest_lro_client(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a 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 - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_no_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_security_center_host_with_port(transport_name): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'securitycenter.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://securitycenter.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_security_center_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SecurityCenterClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SecurityCenterClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.batch_create_resource_value_configs._session - session2 = client2.transport.batch_create_resource_value_configs._session - assert session1 != session2 - session1 = client1.transport.bulk_mute_findings._session - session2 = client2.transport.bulk_mute_findings._session - assert session1 != session2 - session1 = client1.transport.create_big_query_export._session - session2 = client2.transport.create_big_query_export._session - assert session1 != session2 - session1 = client1.transport.create_finding._session - session2 = client2.transport.create_finding._session - assert session1 != session2 - session1 = client1.transport.create_mute_config._session - session2 = client2.transport.create_mute_config._session - assert session1 != session2 - session1 = client1.transport.create_notification_config._session - session2 = client2.transport.create_notification_config._session - assert session1 != session2 - session1 = client1.transport.create_source._session - session2 = client2.transport.create_source._session - assert session1 != session2 - session1 = client1.transport.delete_big_query_export._session - session2 = client2.transport.delete_big_query_export._session - assert session1 != session2 - session1 = client1.transport.delete_mute_config._session - session2 = client2.transport.delete_mute_config._session - assert session1 != session2 - session1 = client1.transport.delete_notification_config._session - session2 = client2.transport.delete_notification_config._session - assert session1 != session2 - session1 = client1.transport.delete_resource_value_config._session - session2 = client2.transport.delete_resource_value_config._session - assert session1 != session2 - session1 = client1.transport.get_big_query_export._session - session2 = client2.transport.get_big_query_export._session - assert session1 != session2 - session1 = client1.transport.get_simulation._session - session2 = client2.transport.get_simulation._session - assert session1 != session2 - session1 = client1.transport.get_valued_resource._session - session2 = client2.transport.get_valued_resource._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.get_mute_config._session - session2 = client2.transport.get_mute_config._session - assert session1 != session2 - session1 = client1.transport.get_notification_config._session - session2 = client2.transport.get_notification_config._session - assert session1 != session2 - session1 = client1.transport.get_resource_value_config._session - session2 = client2.transport.get_resource_value_config._session - assert session1 != session2 - session1 = client1.transport.get_source._session - session2 = client2.transport.get_source._session - assert session1 != session2 - session1 = client1.transport.group_findings._session - session2 = client2.transport.group_findings._session - assert session1 != session2 - session1 = client1.transport.list_attack_paths._session - session2 = client2.transport.list_attack_paths._session - assert session1 != session2 - session1 = client1.transport.list_big_query_exports._session - session2 = client2.transport.list_big_query_exports._session - assert session1 != session2 - session1 = client1.transport.list_findings._session - session2 = client2.transport.list_findings._session - assert session1 != session2 - session1 = client1.transport.list_mute_configs._session - session2 = client2.transport.list_mute_configs._session - assert session1 != session2 - session1 = client1.transport.list_notification_configs._session - session2 = client2.transport.list_notification_configs._session - assert session1 != session2 - session1 = client1.transport.list_resource_value_configs._session - session2 = client2.transport.list_resource_value_configs._session - assert session1 != session2 - session1 = client1.transport.list_sources._session - session2 = client2.transport.list_sources._session - assert session1 != session2 - session1 = client1.transport.list_valued_resources._session - session2 = client2.transport.list_valued_resources._session - assert session1 != session2 - session1 = client1.transport.set_finding_state._session - session2 = client2.transport.set_finding_state._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.set_mute._session - session2 = client2.transport.set_mute._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 - session1 = client1.transport.update_big_query_export._session - session2 = client2.transport.update_big_query_export._session - assert session1 != session2 - session1 = client1.transport.update_external_system._session - session2 = client2.transport.update_external_system._session - assert session1 != session2 - session1 = client1.transport.update_finding._session - session2 = client2.transport.update_finding._session - assert session1 != session2 - session1 = client1.transport.update_mute_config._session - session2 = client2.transport.update_mute_config._session - assert session1 != session2 - session1 = client1.transport.update_notification_config._session - session2 = client2.transport.update_notification_config._session - assert session1 != session2 - session1 = client1.transport.update_resource_value_config._session - session2 = client2.transport.update_resource_value_config._session - assert session1 != session2 - session1 = client1.transport.update_security_marks._session - session2 = client2.transport.update_security_marks._session - assert session1 != session2 - session1 = client1.transport.update_source._session - session2 = client2.transport.update_source._session - assert session1 != session2 -def test_security_center_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcTransport( - 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_security_center_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcAsyncIOTransport( - 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(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_security_center_grpc_lro_client(): - client = SecurityCenterClient( - 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_security_center_grpc_lro_async_client(): - client = SecurityCenterAsyncClient( - 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_attack_path_path(): - organization = "squid" - simulation = "clam" - valued_resource = "whelk" - attack_path = "octopus" - expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, attack_path=attack_path, ) - actual = SecurityCenterClient.attack_path_path(organization, simulation, valued_resource, attack_path) - assert expected == actual - - -def test_parse_attack_path_path(): - expected = { - "organization": "oyster", - "simulation": "nudibranch", - "valued_resource": "cuttlefish", - "attack_path": "mussel", - } - path = SecurityCenterClient.attack_path_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_attack_path_path(path) - assert expected == actual - -def test_big_query_export_path(): - organization = "winkle" - location = "nautilus" - export = "scallop" - expected = "organizations/{organization}/locations/{location}/bigQueryExports/{export}".format(organization=organization, location=location, export=export, ) - actual = SecurityCenterClient.big_query_export_path(organization, location, export) - assert expected == actual - - -def test_parse_big_query_export_path(): - expected = { - "organization": "abalone", - "location": "squid", - "export": "clam", - } - path = SecurityCenterClient.big_query_export_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_big_query_export_path(path) - assert expected == actual - -def test_dlp_job_path(): - project = "whelk" - dlp_job = "octopus" - expected = "projects/{project}/dlpJobs/{dlp_job}".format(project=project, dlp_job=dlp_job, ) - actual = SecurityCenterClient.dlp_job_path(project, dlp_job) - assert expected == actual - - -def test_parse_dlp_job_path(): - expected = { - "project": "oyster", - "dlp_job": "nudibranch", - } - path = SecurityCenterClient.dlp_job_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_dlp_job_path(path) - assert expected == actual - -def test_external_system_path(): - organization = "cuttlefish" - source = "mussel" - finding = "winkle" - externalsystem = "nautilus" - expected = "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format(organization=organization, source=source, finding=finding, externalsystem=externalsystem, ) - actual = SecurityCenterClient.external_system_path(organization, source, finding, externalsystem) - assert expected == actual - - -def test_parse_external_system_path(): - expected = { - "organization": "scallop", - "source": "abalone", - "finding": "squid", - "externalsystem": "clam", - } - path = SecurityCenterClient.external_system_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_external_system_path(path) - assert expected == actual - -def test_finding_path(): - organization = "whelk" - source = "octopus" - finding = "oyster" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - actual = SecurityCenterClient.finding_path(organization, source, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "organization": "nudibranch", - "source": "cuttlefish", - "finding": "mussel", - } - path = SecurityCenterClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_finding_path(path) - assert expected == actual - -def test_mute_config_path(): - organization = "winkle" - mute_config = "nautilus" - expected = "organizations/{organization}/muteConfigs/{mute_config}".format(organization=organization, mute_config=mute_config, ) - actual = SecurityCenterClient.mute_config_path(organization, mute_config) - assert expected == actual - - -def test_parse_mute_config_path(): - expected = { - "organization": "scallop", - "mute_config": "abalone", - } - path = SecurityCenterClient.mute_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_mute_config_path(path) - assert expected == actual - -def test_notification_config_path(): - organization = "squid" - location = "clam" - notification_config = "whelk" - expected = "organizations/{organization}/locations/{location}/notificationConfigs/{notification_config}".format(organization=organization, location=location, notification_config=notification_config, ) - actual = SecurityCenterClient.notification_config_path(organization, location, notification_config) - assert expected == actual - - -def test_parse_notification_config_path(): - expected = { - "organization": "octopus", - "location": "oyster", - "notification_config": "nudibranch", - } - path = SecurityCenterClient.notification_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_notification_config_path(path) - assert expected == actual - -def test_policy_path(): - organization = "cuttlefish" - constraint_name = "mussel" - expected = "organizations/{organization}/policies/{constraint_name}".format(organization=organization, constraint_name=constraint_name, ) - actual = SecurityCenterClient.policy_path(organization, constraint_name) - assert expected == actual - - -def test_parse_policy_path(): - expected = { - "organization": "winkle", - "constraint_name": "nautilus", - } - path = SecurityCenterClient.policy_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_policy_path(path) - assert expected == actual - -def test_resource_value_config_path(): - organization = "scallop" - resource_value_config = "abalone" - expected = "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format(organization=organization, resource_value_config=resource_value_config, ) - actual = SecurityCenterClient.resource_value_config_path(organization, resource_value_config) - assert expected == actual - - -def test_parse_resource_value_config_path(): - expected = { - "organization": "squid", - "resource_value_config": "clam", - } - path = SecurityCenterClient.resource_value_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_resource_value_config_path(path) - assert expected == actual - -def test_security_marks_path(): - organization = "whelk" - asset = "octopus" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.security_marks_path(organization, asset) - assert expected == actual - - -def test_parse_security_marks_path(): - expected = { - "organization": "oyster", - "asset": "nudibranch", - } - path = SecurityCenterClient.security_marks_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_security_marks_path(path) - assert expected == actual - -def test_simulation_path(): - organization = "cuttlefish" - simulation = "mussel" - expected = "organizations/{organization}/simulations/{simulation}".format(organization=organization, simulation=simulation, ) - actual = SecurityCenterClient.simulation_path(organization, simulation) - assert expected == actual - - -def test_parse_simulation_path(): - expected = { - "organization": "winkle", - "simulation": "nautilus", - } - path = SecurityCenterClient.simulation_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_simulation_path(path) - assert expected == actual - -def test_source_path(): - organization = "scallop" - source = "abalone" - expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - actual = SecurityCenterClient.source_path(organization, source) - assert expected == actual - - -def test_parse_source_path(): - expected = { - "organization": "squid", - "source": "clam", - } - path = SecurityCenterClient.source_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_source_path(path) - assert expected == actual - -def test_table_data_profile_path(): - project = "whelk" - table_profile = "octopus" - expected = "projects/{project}/tableProfiles/{table_profile}".format(project=project, table_profile=table_profile, ) - actual = SecurityCenterClient.table_data_profile_path(project, table_profile) - assert expected == actual - - -def test_parse_table_data_profile_path(): - expected = { - "project": "oyster", - "table_profile": "nudibranch", - } - path = SecurityCenterClient.table_data_profile_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_table_data_profile_path(path) - assert expected == actual - -def test_topic_path(): - project = "cuttlefish" - topic = "mussel" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = SecurityCenterClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "winkle", - "topic": "nautilus", - } - path = SecurityCenterClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_topic_path(path) - assert expected == actual - -def test_valued_resource_path(): - organization = "scallop" - simulation = "abalone" - valued_resource = "squid" - expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format(organization=organization, simulation=simulation, valued_resource=valued_resource, ) - actual = SecurityCenterClient.valued_resource_path(organization, simulation, valued_resource) - assert expected == actual - - -def test_parse_valued_resource_path(): - expected = { - "organization": "clam", - "simulation": "whelk", - "valued_resource": "octopus", - } - path = SecurityCenterClient.valued_resource_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_valued_resource_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SecurityCenterClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = SecurityCenterClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = SecurityCenterClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = SecurityCenterClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SecurityCenterClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = SecurityCenterClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = SecurityCenterClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = SecurityCenterClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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 = SecurityCenterClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = SecurityCenterClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.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.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - transport_class = SecurityCenterClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations/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 = 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.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations/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 = 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_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations/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() - - # 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 - - 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(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'organizations/sample1/operations'}, 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() - 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'organizations/sample1/operations'} - request = request_type(**request_init) - # Mock the http request call within the method and 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.ListOperationsResponse() - - # 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 - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterClient( - 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 = SecurityCenterAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "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 = SecurityCenterClient( - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), -]) -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-securitycenter/google/cloud/securitycenter_v1/services/security_center/async_client.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/async_client.py index 42ccb1d1d0fa..5b8d3b8ba86a 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -6517,9 +6517,9 @@ async def sample_delete_event_threat_detection_custom_module(): Its format is: - - "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}". - - "folders/{folder}/eventThreatDetectionSettings/customModules/{module}". - - "projects/{project}/eventThreatDetectionSettings/customModules/{module}". + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/client.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/client.py index d1419ab4636c..a0692e19d518 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/client.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/client.py @@ -7172,9 +7172,9 @@ def sample_delete_event_threat_detection_custom_module(): Its format is: - - "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}". - - "folders/{folder}/eventThreatDetectionSettings/customModules/{module}". - - "projects/{project}/eventThreatDetectionSettings/customModules/{module}". + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/finding.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/finding.py index 055df2a603fc..c32ae215ec32 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/finding.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/finding.py @@ -191,6 +191,9 @@ class Finding(proto.Message): example, the `mute configuration `__ that muted the finding and the user who muted the finding. + mute_info (google.cloud.securitycenter_v1.types.Finding.MuteInfo): + Output only. The mute information regarding + this finding. processes (MutableSequence[google.cloud.securitycenter_v1.types.Process]): Represents operating system processes associated with the Finding. @@ -461,6 +464,83 @@ class FindingClass(proto.Enum): POSTURE_VIOLATION = 6 TOXIC_COMBINATION = 7 + class MuteInfo(proto.Message): + r"""Mute information about the finding, including whether the + finding has a static mute or any matching dynamic mute rules. + + Attributes: + static_mute (google.cloud.securitycenter_v1.types.Finding.MuteInfo.StaticMute): + If set, the static mute applied to this + finding. Static mutes override dynamic mutes. If + unset, there is no static mute. + dynamic_mute_records (MutableSequence[google.cloud.securitycenter_v1.types.Finding.MuteInfo.DynamicMuteRecord]): + The list of dynamic mute rules that currently + match the finding. + """ + + class StaticMute(proto.Message): + r"""Information about the static mute state. A static mute state + overrides any dynamic mute rules that apply to this finding. The + static mute state can be set by a static mute rule or by muting + the finding directly. + + Attributes: + state (google.cloud.securitycenter_v1.types.Finding.Mute): + The static mute state. If the value is ``MUTED`` or + ``UNMUTED``, then the finding's overall mute state will have + the same value. + apply_time (google.protobuf.timestamp_pb2.Timestamp): + When the static mute was applied. + """ + + state: "Finding.Mute" = proto.Field( + proto.ENUM, + number=1, + enum="Finding.Mute", + ) + apply_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + class DynamicMuteRecord(proto.Message): + r"""The record of a dynamic mute rule that matches the finding. + + Attributes: + mute_config (str): + The relative resource name of the mute rule, represented by + a mute config, that created this record, for example + ``organizations/123/muteConfigs/mymuteconfig`` or + ``organizations/123/locations/global/muteConfigs/mymuteconfig``. + match_time (google.protobuf.timestamp_pb2.Timestamp): + When the dynamic mute rule first matched the + finding. + """ + + mute_config: str = proto.Field( + proto.STRING, + number=1, + ) + match_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + static_mute: "Finding.MuteInfo.StaticMute" = proto.Field( + proto.MESSAGE, + number=1, + message="Finding.MuteInfo.StaticMute", + ) + dynamic_mute_records: MutableSequence[ + "Finding.MuteInfo.DynamicMuteRecord" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Finding.MuteInfo.DynamicMuteRecord", + ) + name: str = proto.Field( proto.STRING, number=1, @@ -568,6 +648,11 @@ class FindingClass(proto.Enum): proto.STRING, number=28, ) + mute_info: MuteInfo = proto.Field( + proto.MESSAGE, + number=61, + message=MuteInfo, + ) processes: MutableSequence[process.Process] = proto.RepeatedField( proto.MESSAGE, number=30, diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/mitre_attack.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/mitre_attack.py index f6530d1b7278..28af8c91a1da 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/mitre_attack.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/mitre_attack.py @@ -111,7 +111,7 @@ class Tactic(proto.Enum): class Technique(proto.Enum): r"""MITRE ATT&CK techniques that can be referenced by SCC findings. See: https://attack.mitre.org/techniques/enterprise/ - Next ID: 63 + Next ID: 65 Values: TECHNIQUE_UNSPECIFIED (0): @@ -134,10 +134,14 @@ class Technique(proto.Enum): T1059.004 PYTHON (59): T1059.006 + EXPLOITATION_FOR_PRIVILEGE_ESCALATION (63): + T1068 PERMISSION_GROUPS_DISCOVERY (18): T1069 CLOUD_GROUPS (19): T1069.003 + INDICATOR_REMOVAL_FILE_DELETION (64): + T1070.004 APPLICATION_LAYER_PROTOCOL (45): T1071 DNS (46): @@ -251,8 +255,10 @@ class Technique(proto.Enum): COMMAND_AND_SCRIPTING_INTERPRETER = 6 UNIX_SHELL = 7 PYTHON = 59 + EXPLOITATION_FOR_PRIVILEGE_ESCALATION = 63 PERMISSION_GROUPS_DISCOVERY = 18 CLOUD_GROUPS = 19 + INDICATOR_REMOVAL_FILE_DELETION = 64 APPLICATION_LAYER_PROTOCOL = 45 DNS = 46 SOFTWARE_DEPLOYMENT_TOOLS = 47 diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/mute_config.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/mute_config.py index d8235576b9dc..be606d5de6d6 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/mute_config.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/mute_config.py @@ -84,8 +84,47 @@ class MuteConfig(proto.Message): last edited the mute config. This field is set by the server and will be ignored if provided on config creation or update. + type_ (google.cloud.securitycenter_v1.types.MuteConfig.MuteConfigType): + Optional. The type of the mute config, which + determines what type of mute state the config + affects. The static mute state takes precedence + over the dynamic mute state. Immutable after + creation. STATIC by default if not set during + creation. + expiry_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The expiry of the mute config. Only + applicable for dynamic configs. If the expiry is + set, when the config expires, it is removed from + all findings. """ + class MuteConfigType(proto.Enum): + r"""The type of MuteConfig. + + Values: + MUTE_CONFIG_TYPE_UNSPECIFIED (0): + Unused. + STATIC (1): + A static mute config, which sets the static + mute state of future matching findings to muted. + Once the static mute state has been set, finding + or config modifications will not affect the + state. + DYNAMIC (2): + A dynamic mute config, which is applied to + existing and future matching findings, setting + their dynamic mute state to "muted". If the + config is updated or deleted, or a matching + finding is updated, such that the finding + doesn't match the config, the config will be + removed from the finding, and the finding's + dynamic mute state may become "unmuted" (unless + other configs still match). + """ + MUTE_CONFIG_TYPE_UNSPECIFIED = 0 + STATIC = 1 + DYNAMIC = 2 + name: str = proto.Field( proto.STRING, number=1, @@ -116,6 +155,16 @@ class MuteConfig(proto.Message): proto.STRING, number=7, ) + type_: MuteConfigType = proto.Field( + proto.ENUM, + number=8, + enum=MuteConfigType, + ) + expiry_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/securitycenter_service.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/securitycenter_service.py index b4e881e6260b..0ba9bfbed6da 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/securitycenter_service.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/securitycenter_service.py @@ -192,7 +192,28 @@ class BulkMuteFindingsRequest(proto.Message): This can be a mute configuration name or any identifier for mute/unmute of findings based on the filter. - """ + mute_state (google.cloud.securitycenter_v1.types.BulkMuteFindingsRequest.MuteState): + Optional. All findings matching the given filter will have + their mute state set to this value. The default value is + ``MUTED``. Setting this to ``UNDEFINED`` will clear the mute + state on all matching findings. + """ + + class MuteState(proto.Enum): + r"""The mute state. + + Values: + MUTE_STATE_UNSPECIFIED (0): + Unused. + MUTED (1): + Matching findings will be muted (default). + UNDEFINED (2): + Matching findings will have their mute state + cleared. + """ + MUTE_STATE_UNSPECIFIED = 0 + MUTED = 1 + UNDEFINED = 2 parent: str = proto.Field( proto.STRING, @@ -206,6 +227,11 @@ class BulkMuteFindingsRequest(proto.Message): proto.STRING, number=3, ) + mute_state: MuteState = proto.Field( + proto.ENUM, + number=4, + enum=MuteState, + ) class BulkMuteFindingsResponse(proto.Message): @@ -3235,9 +3261,9 @@ class DeleteEventThreatDetectionCustomModuleRequest(proto.Message): Its format is: - - "organizations/{organization}/eventThreatDetectionSettings/customModules/{module}". - - "folders/{folder}/eventThreatDetectionSettings/customModules/{module}". - - "projects/{project}/eventThreatDetectionSettings/customModules/{module}". + - ``organizations/{organization}/eventThreatDetectionSettings/customModules/{module}``. + - ``folders/{folder}/eventThreatDetectionSettings/customModules/{module}``. + - ``projects/{project}/eventThreatDetectionSettings/customModules/{module}``. """ name: str = proto.Field( diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/vulnerability.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/vulnerability.py index 756365a5e5a4..d956fd3936e1 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/vulnerability.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/vulnerability.py @@ -106,6 +106,9 @@ class Cve(proto.Message): zero_day (bool): Whether or not the vulnerability was zero day when the finding was published. + exploit_release_date (google.protobuf.timestamp_pb2.Timestamp): + Date the first publicly available exploit or + PoC was released. """ class RiskRating(proto.Enum): @@ -204,6 +207,11 @@ class ExploitationActivity(proto.Enum): proto.BOOL, number=8, ) + exploit_release_date: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) class Reference(proto.Message): diff --git a/packages/google-cloud-securitycenter/scripts/fixup_securitycenter_v1_keywords.py b/packages/google-cloud-securitycenter/scripts/fixup_securitycenter_v1_keywords.py index f99f1a291b7b..077baab9f5d2 100644 --- a/packages/google-cloud-securitycenter/scripts/fixup_securitycenter_v1_keywords.py +++ b/packages/google-cloud-securitycenter/scripts/fixup_securitycenter_v1_keywords.py @@ -40,7 +40,7 @@ class securitycenterCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'batch_create_resource_value_configs': ('parent', 'requests', ), - 'bulk_mute_findings': ('parent', 'filter', 'mute_annotation', ), + 'bulk_mute_findings': ('parent', 'filter', 'mute_annotation', 'mute_state', ), 'create_big_query_export': ('parent', 'big_query_export', 'big_query_export_id', ), 'create_event_threat_detection_custom_module': ('parent', 'event_threat_detection_custom_module', ), 'create_finding': ('parent', 'finding_id', 'finding', ), diff --git a/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v1/test_security_center.py b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v1/test_security_center.py index f1cf09cf0cbf..094cc1f0a802 100644 --- a/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v1/test_security_center.py +++ b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v1/test_security_center.py @@ -2945,6 +2945,7 @@ def test_create_mute_config(request_type, transport: str = "grpc"): description="description_value", filter="filter_value", most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, ) response = client.create_mute_config(request) @@ -2961,6 +2962,7 @@ def test_create_mute_config(request_type, transport: str = "grpc"): assert response.description == "description_value" assert response.filter == "filter_value" assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC def test_create_mute_config_empty_call(): @@ -3076,6 +3078,7 @@ async def test_create_mute_config_empty_call_async(): description="description_value", filter="filter_value", most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, ) ) response = await client.create_mute_config() @@ -3151,6 +3154,7 @@ async def test_create_mute_config_async( description="description_value", filter="filter_value", most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, ) ) response = await client.create_mute_config(request) @@ -3168,6 +3172,7 @@ async def test_create_mute_config_async( assert response.description == "description_value" assert response.filter == "filter_value" assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC @pytest.mark.asyncio @@ -6525,6 +6530,7 @@ def test_get_mute_config(request_type, transport: str = "grpc"): description="description_value", filter="filter_value", most_recent_editor="most_recent_editor_value", + type_=mute_config.MuteConfig.MuteConfigType.STATIC, ) response = client.get_mute_config(request) @@ -6541,6 +6547,7 @@ def test_get_mute_config(request_type, transport: str = "grpc"): assert response.description == "description_value" assert response.filter == "filter_value" assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC def test_get_mute_config_empty_call(): @@ -6644,6 +6651,7 @@ async def test_get_mute_config_empty_call_async(): description="description_value", filter="filter_value", most_recent_editor="most_recent_editor_value", + type_=mute_config.MuteConfig.MuteConfigType.STATIC, ) ) response = await client.get_mute_config() @@ -6717,6 +6725,7 @@ async def test_get_mute_config_async( description="description_value", filter="filter_value", most_recent_editor="most_recent_editor_value", + type_=mute_config.MuteConfig.MuteConfigType.STATIC, ) ) response = await client.get_mute_config(request) @@ -6734,6 +6743,7 @@ async def test_get_mute_config_async( assert response.description == "description_value" assert response.filter == "filter_value" assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC @pytest.mark.asyncio @@ -18155,6 +18165,7 @@ def test_update_mute_config(request_type, transport: str = "grpc"): description="description_value", filter="filter_value", most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, ) response = client.update_mute_config(request) @@ -18171,6 +18182,7 @@ def test_update_mute_config(request_type, transport: str = "grpc"): assert response.description == "description_value" assert response.filter == "filter_value" assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC def test_update_mute_config_empty_call(): @@ -18280,6 +18292,7 @@ async def test_update_mute_config_empty_call_async(): description="description_value", filter="filter_value", most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, ) ) response = await client.update_mute_config() @@ -18355,6 +18368,7 @@ async def test_update_mute_config_async( description="description_value", filter="filter_value", most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, ) ) response = await client.update_mute_config(request) @@ -18372,6 +18386,7 @@ async def test_update_mute_config_async( assert response.description == "description_value" assert response.filter == "filter_value" assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC @pytest.mark.asyncio @@ -31569,6 +31584,7 @@ def test_create_finding_rest(request_type): "exploitation_activity": 1, "observed_in_the_wild": True, "zero_day": True, + "exploit_release_date": {}, }, "offending_package": { "package_name": "package_name_value", @@ -31620,6 +31636,12 @@ def test_create_finding_rest(request_type): } ], "mute_initiator": "mute_initiator_value", + "mute_info": { + "static_mute": {"state": 1, "apply_time": {}}, + "dynamic_mute_records": [ + {"mute_config": "mute_config_value", "match_time": {}} + ], + }, "processes": [ { "name": "name_value", @@ -32259,6 +32281,8 @@ def test_create_mute_config_rest(request_type): "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, "most_recent_editor": "most_recent_editor_value", + "type_": 1, + "expiry_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 @@ -32340,6 +32364,7 @@ def get_message_fields(field): description="description_value", filter="filter_value", most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, ) # Wrap the value into a proper Response obj @@ -32360,6 +32385,7 @@ def get_message_fields(field): assert response.description == "description_value" assert response.filter == "filter_value" assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC def test_create_mute_config_rest_use_cached_wrapped_rpc(): @@ -35240,6 +35266,7 @@ def test_get_mute_config_rest(request_type): description="description_value", filter="filter_value", most_recent_editor="most_recent_editor_value", + type_=mute_config.MuteConfig.MuteConfigType.STATIC, ) # Wrap the value into a proper Response obj @@ -35260,6 +35287,7 @@ def test_get_mute_config_rest(request_type): assert response.description == "description_value" assert response.filter == "filter_value" assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC def test_get_mute_config_rest_use_cached_wrapped_rpc(): @@ -43443,6 +43471,7 @@ def test_update_finding_rest(request_type): "exploitation_activity": 1, "observed_in_the_wild": True, "zero_day": True, + "exploit_release_date": {}, }, "offending_package": { "package_name": "package_name_value", @@ -43494,6 +43523,12 @@ def test_update_finding_rest(request_type): } ], "mute_initiator": "mute_initiator_value", + "mute_info": { + "static_mute": {"state": 1, "apply_time": {}}, + "dynamic_mute_records": [ + {"mute_config": "mute_config_value", "match_time": {}} + ], + }, "processes": [ { "name": "name_value", @@ -44110,6 +44145,8 @@ def test_update_mute_config_rest(request_type): "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, "most_recent_editor": "most_recent_editor_value", + "type_": 1, + "expiry_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 @@ -44191,6 +44228,7 @@ def get_message_fields(field): description="description_value", filter="filter_value", most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, ) # Wrap the value into a proper Response obj @@ -44211,6 +44249,7 @@ def get_message_fields(field): assert response.description == "description_value" assert response.filter == "filter_value" assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC def test_update_mute_config_rest_use_cached_wrapped_rpc():